1 (function(angular
, $, _
) {
2 // example <select crm-mailing-templates crm-mailing="mymailing"></select>
3 angular
.module('crmMailing').directive('crmMailingTemplates', function(crmUiAlert
) {
10 link: function(scope
, element
, attrs
, ngModel
) {
11 scope
.template
= ngModel
.$viewValue
;
13 var refreshUI
= ngModel
.$render
= function refresuhUI() {
14 scope
.template
= ngModel
.$viewValue
;
15 if (ngModel
.$viewValue
) {
16 $(element
).select2('val', ngModel
.$viewValue
);
20 // @return string HTML representing an option
21 function formatItem(item
) {
23 // return `text` for optgroup
26 return '<span class="crmMailing-template">' + item
.text
+ '</span>';
31 entity
: 'civicrm_msg_templates',
38 placeholder
: "<i class='fa fa-clipboard'></i> Mailing Templates",
39 formatResult
: formatItem
,
40 escapeMarkup: function(m
) {
44 initSelection: function(el
, cb
) {
48 CRM
.api3('MessageTemplate', 'getlist', { params
: { id
: value
}, label_field
: 'msg_title' }).then(function(tlist
) {
53 $(tlist
.values
).each(function(id
, val
) {
55 template
.text
= val
.label
;
63 url
: CRM
.url('civicrm/ajax/rest'),
65 data: function(input
, page_num
) {
69 entity
: 'civicrm_msg_templates',
74 rcpAjaxState
.page_i
= page_num
- rcpAjaxState
.page_n
;
75 var filterParams
= { is_active
: 1, workflow_id
: { "IS NULL": 1 } };
79 page_num
: rcpAjaxState
.page_i
,
80 label_field
: 'msg_title',
81 search_field
: 'msg_title',
86 transport: function(params
) {
87 CRM
.api3('MessageTemplate', 'getlist', params
.data
).then(params
.success
, params
.error
);
89 results: function(data
) {
92 children
: $.map(data
.values
, function(obj
) {
93 return { id
: obj
.id
, text
: obj
.label
};
97 if (rcpAjaxState
.page_i
== 1 && data
.count
) {
98 results
.text
= ts('Message Templates');
101 more
= data
.more_results
;
103 if (more
&& !data
.more_results
) {
104 rcpAjaxState
.page_n
+= rcpAjaxState
.page_i
;
107 return { more
: more
, results
: [ results
] };
112 $(element
).on('select2-selecting', function(e
) {
113 // in here is where the template HTML should be loaded
114 var entity_id
= parseInt(e
.val
);
115 ngModel
.$viewValue
= entity_id
;
117 scope
.$parent
.loadTemplate(scope
.$parent
.$parent
.mailing
, entity_id
);
119 $(element
).select2('close');
124 scope
.$watchCollection("template", refreshUI
);
125 setTimeout(refreshUI
, 50);
131 })(angular
, CRM
.$, CRM
._
);