forked from civicrm/civicrm-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommon.js
2017 lines (1908 loc) · 77.9 KB
/
Common.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// https://civicrm.org/licensing
/* global CRM:true */
var CRM = CRM || {};
var cj = CRM.$ = jQuery;
CRM._ = _;
/**
* Short-named function for string translation, defined in global scope so it's available everywhere.
*
* @param text string for translating
* @param params object key:value of additional parameters
*
* @return string
*/
function ts(text, params) {
"use strict";
var d = (params && params.domain) ? ('strings::' + params.domain) : null;
if (d && CRM[d] && CRM[d][text]) {
text = CRM[d][text];
}
else if (CRM.strings[text]) {
text = CRM.strings[text];
}
if (typeof(params) === 'object') {
for (var i in params) {
if (typeof(params[i]) === 'string' || typeof(params[i]) === 'number') {
// sprintf emulation: escape % characters in the replacements to avoid conflicts
text = text.replace(new RegExp('%' + i, 'g'), String(params[i]).replace(/%/g, '%-crmescaped-'));
}
}
return text.replace(/%-crmescaped-/g, '%');
}
return text;
}
// Legacy code - ignore warnings
/* jshint ignore:start */
/**
* This function is called by default at the bottom of template files which have forms that have
* conditionally displayed/hidden sections and elements. The PHP is responsible for generating
* a list of 'blocks to show' and 'blocks to hide' and the template passes these parameters to
* this function.
*
* @deprecated
* @param showBlocks Array of element Id's to be displayed
* @param hideBlocks Array of element Id's to be hidden
* @param elementType Value to set display style to for showBlocks (e.g. 'block' or 'table-row' or ...)
*/
function on_load_init_blocks(showBlocks, hideBlocks, elementType) {
if (elementType == null) {
elementType = 'block';
}
var myElement, i;
/* This loop is used to display the blocks whose IDs are present within the showBlocks array */
for (i = 0; i < showBlocks.length; i++) {
myElement = document.getElementById(showBlocks[i]);
/* getElementById returns null if element id doesn't exist in the document */
if (myElement != null) {
myElement.style.display = elementType;
}
else {
alert('showBlocks array item not in .tpl = ' + showBlocks[i]);
}
}
/* This loop is used to hide the blocks whose IDs are present within the hideBlocks array */
for (i = 0; i < hideBlocks.length; i++) {
myElement = document.getElementById(hideBlocks[i]);
/* getElementById returns null if element id doesn't exist in the document */
if (myElement != null) {
myElement.style.display = 'none';
}
else {
alert('showBlocks array item not in .tpl = ' + hideBlocks[i]);
}
}
}
/**
* This function is called when we need to show or hide a related form element (target_element)
* based on the value (trigger_value) of another form field (trigger_field).
*
* @deprecated
* @param trigger_field_id HTML id of field whose onchange is the trigger
* @param trigger_value List of integers - option value(s) which trigger show-element action for target_field
* @param target_element_id HTML id of element to be shown or hidden
* @param target_element_type Type of element to be shown or hidden ('block' or 'table-row')
* @param field_type Type of element radio/select
* @param invert Boolean - if true, we HIDE target on value match; if false, we SHOW target on value match
*/
function showHideByValue(trigger_field_id, trigger_value, target_element_id, target_element_type, field_type, invert) {
var target, j;
if (field_type == 'select') {
var trigger = trigger_value.split("|");
var selectedOptionValue = cj('#' + trigger_field_id).val();
target = target_element_id.split("|");
for (j = 0; j < target.length; j++) {
if (invert) {
cj('#' + target[j]).show();
}
else {
cj('#' + target[j]).hide();
}
for (var i = 0; i < trigger.length; i++) {
if (selectedOptionValue == trigger[i]) {
if (invert) {
cj('#' + target[j]).hide();
}
else {
cj('#' + target[j]).show();
}
}
}
}
}
else {
if (field_type == 'radio') {
target = target_element_id.split("|");
for (j = 0; j < target.length; j++) {
if (cj('[name="' + trigger_field_id + '"]:first').is(':checked')) {
if (invert) {
cj('#' + target[j]).hide();
}
else {
cj('#' + target[j]).show();
}
}
else {
if (invert) {
cj('#' + target[j]).show();
}
else {
cj('#' + target[j]).hide();
}
}
}
}
}
}
var submitcount = 0;
/**
* Function to show / hide the row in optionFields
* @deprecated
* @param index string, element whose innerHTML is to hide else will show the hidden row.
*/
function showHideRow(index) {
if (index) {
cj('tr#optionField_' + index).hide();
if (cj('table#optionField tr:hidden:first').length) {
cj('div#optionFieldLink').show();
}
}
else {
cj('table#optionField tr:hidden:first').show();
if (!cj('table#optionField tr:hidden:last').length) {
cj('div#optionFieldLink').hide();
}
}
return false;
}
/* jshint ignore:end */
if (!CRM.utils) CRM.utils = {};
if (!CRM.strings) CRM.strings = {};
if (!CRM.vars) CRM.vars = {};
(function ($, _, undefined) {
"use strict";
/* jshint validthis: true */
// Theme classes for unattached elements
$.fn.select2.defaults.dropdownCssClass = $.ui.dialog.prototype.options.dialogClass = 'crm-container';
// https://github.com/ivaynberg/select2/pull/2090
$.fn.select2.defaults.width = 'resolve';
// Workaround for https://github.com/ivaynberg/select2/issues/1246
$.ui.dialog.prototype._allowInteraction = function(e) {
return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop, .cke_dialog, .ck-balloon-panel, #civicrm-menu').length;
};
// Implements jQuery hook.prop
$.propHooks.disabled = {
set: function (el, value, name) {
// Sync button enabled status with wrapper css
if ($(el).is('.crm-button.crm-form-submit')) {
$(el).parent().toggleClass('crm-button-disabled', !!value);
}
// Sync button enabled status with dialog button
if ($(el).is('.ui-dialog input.crm-form-submit')) {
$(el).closest('.ui-dialog').find('.ui-dialog-buttonset button[data-identifier='+ $(el).attr('name') +']').prop('disabled', value);
}
if ($(el).is('.crm-form-date-wrapper .crm-hidden-date')) {
$(el).siblings().prop('disabled', value);
}
}
};
var scriptsLoaded = {};
CRM.loadScript = function(url, appendCacheCode) {
if (!scriptsLoaded[url]) {
var script = document.createElement('script'),
src = url;
if (appendCacheCode !== false) {
src += (_.includes(url, '?') ? '&r=' : '?r=') + CRM.config.resourceCacheCode;
}
scriptsLoaded[url] = $.Deferred();
script.onload = function () {
// Give the script time to execute
window.setTimeout(function () {
if (window.jQuery === CRM.$ && CRM.CMSjQuery) {
window.jQuery = CRM.CMSjQuery;
}
scriptsLoaded[url].resolve();
}, 100);
};
// Make jQuery global available while script is loading
if (window.jQuery !== CRM.$) {
CRM.CMSjQuery = window.jQuery;
window.jQuery = CRM.$;
}
script.src = src;
document.getElementsByTagName("head")[0].appendChild(script);
}
return scriptsLoaded[url];
};
/**
* Populate a select list, overwriting the existing options except for the placeholder.
* @param select jquery selector - 1 or more select elements
* @param options array in format returned by api.getoptions
* @param placeholder string|bool - new placeholder or false (default) to keep the old one
* @param value string|array - will silently update the element with new value without triggering change
*/
CRM.utils.setOptions = function(select, options, placeholder, value) {
$(select).each(function() {
var
$elect = $(this),
val = value || $elect.val() || [],
opts = placeholder || placeholder === '' ? '' : '[value!=""]';
$elect.find('option' + opts).remove();
var newOptions = CRM.utils.renderOptions(options, val);
if (options.length == 0) {
$elect.removeClass('required');
} else if ($elect.hasClass('crm-field-required') && !$elect.hasClass('required')) {
$elect.addClass('required');
}
if (typeof placeholder === 'string') {
if ($elect.is('[multiple]')) {
select.attr('placeholder', placeholder);
} else {
newOptions = '<option value="">' + placeholder + '</option>' + newOptions;
}
}
$elect.append(newOptions);
if (!value) {
$elect.trigger('crmOptionsUpdated', $.extend({}, options)).trigger('change');
}
});
};
/**
* Render an option list
* @param options {array}
* @param val {string} default value
* @param escapeHtml {bool}
* @return string
*/
CRM.utils.renderOptions = function(options, val, escapeHtml) {
var rendered = '',
esc = escapeHtml === false ? _.identity : _.escape;
if (!$.isArray(val)) {
val = [val];
}
_.each(options, function(option) {
if (option.children) {
rendered += '<optgroup label="' + esc(option.value) + '">' +
CRM.utils.renderOptions(option.children, val) +
'</optgroup>';
} else {
var selected = ($.inArray('' + option.key, val) > -1) ? 'selected="selected"' : '';
rendered += '<option value="' + esc(option.key) + '"' + selected + '>' + esc(option.value) + '</option>';
}
});
return rendered;
};
CRM.utils.getOptions = function(select) {
var options = [];
$('option', select).each(function() {
var option = {key: $(this).attr('value'), value: $(this).text()};
if (option.key !== '') {
options.push(option);
}
});
return options;
};
function chainSelect() {
var $form = $(this).closest('form'),
$target = $('select[data-name="' + $(this).data('target') + '"]', $form),
data = $target.data(),
val = $(this).val();
$target.prop('disabled', true);
if ($target.is('select.crm-chain-select-control')) {
$('select[data-name="' + $target.data('target') + '"]', $form).prop('disabled', true).blur();
}
if (!(val && val.length)) {
CRM.utils.setOptions($target.blur(), [], data.emptyPrompt);
} else {
$target.addClass('loading');
$.getJSON(CRM.url(data.callback), {_value: val}, function(vals) {
$target.prop('disabled', false).removeClass('loading');
CRM.utils.setOptions($target, vals || [], (vals && vals.length ? data.selectPrompt : data.nonePrompt));
});
}
}
/**
* Compare Form Input values against cached initial value.
*
* @return {Boolean} true if changes have been made.
*/
CRM.utils.initialValueChanged = function(el) {
var isDirty = false;
$(':input:visible, .select2-container:visible+:input:hidden', el).not('[type=submit], [type=button], .crm-action-menu, :disabled').each(function () {
var
initialValue = $(this).data('crm-initial-value'),
currentValue = $(this).is(':checkbox, :radio') ? $(this).prop('checked') : $(this).val();
// skip change of value for submit buttons
if (initialValue !== undefined && !_.isEqual(initialValue, currentValue)) {
isDirty = true;
}
});
return isDirty;
};
/**
* This provides defaults for ui.dialog which either need to be calculated or are different from global defaults
*
* @param settings
* @returns {*}
*/
CRM.utils.adjustDialogDefaults = function(settings) {
settings = $.extend({width: '65%', height: '40%', modal: true}, settings || {});
// Support relative height
if (typeof settings.height === 'string' && settings.height.indexOf('%') > 0) {
settings.height = parseInt($(window).height() * (parseFloat(settings.height)/100), 10);
}
// Responsive adjustment - increase percent width on small screens
if (typeof settings.width === 'string' && settings.width.indexOf('%') > 0) {
var screenWidth = $(window).width(),
percentage = parseInt(settings.width.replace('%', ''), 10),
gap = 100-percentage;
if (screenWidth < 701) {
settings.width = '100%';
}
else if (screenWidth < 1400) {
settings.width = '' + parseInt(percentage+gap-((screenWidth - 700)/7*(gap)/100), 10) + '%';
}
}
if (settings.dialogClass && !_.includes(settings.dialogClass, 'crm-container')) {
settings.dialogClass += ' crm-container';
}
return settings;
};
function formatCrmSelect2(row) {
var icon = row.icon || $(row.element).data('icon'),
color = row.color || $(row.element).data('color'),
description = row.description || $(row.element).data('description'),
ret = '';
if (icon) {
ret += '<i class="crm-i ' + icon + '" aria-hidden="true"></i> ';
}
if (color) {
ret += '<span class="crm-select-item-color" style="background-color: ' + color + '"></span> ';
}
return ret + _.escape(row.text) + (description ? '<div class="crm-select2-row-description"><p>' + _.escape(description) + '</p></div>' : '');
}
/**
* Helper to generate an icon with alt text.
*
* See also smarty `{icon}` and CRM_Core_Page::crmIcon() functions
*
* @param string icon
* The Font Awesome icon class to use.
* @param string text
* Alt text to display.
* @param mixed condition
* This will only display if this is truthy.
*
* @return string
* The formatted icon markup.
*/
CRM.utils.formatIcon = function (icon, text, condition) {
if (typeof condition !== 'undefined' && !condition) {
return '';
}
var title = '';
var sr = '';
if (text) {
text = _.escape(text);
title = ' title="' + text + '"';
sr = '<span class="sr-only">' + text + '</span>';
}
return '<i class="crm-i ' + icon + '"' + title + ' aria-hidden="true"></i>' + sr;
};
/**
* Wrapper for select2 initialization function; supplies defaults
* @param options object
*/
$.fn.crmSelect2 = function(options) {
if (options === 'destroy') {
return $(this).each(function() {
$(this)
.removeClass('crm-ajax-select')
.off('.crmSelect2')
.select2('destroy');
});
}
return $(this).each(function () {
var
$el = $(this),
iconClass,
settings = {
allowClear: !$el.hasClass('required'),
formatResult: formatCrmSelect2,
formatSelection: formatCrmSelect2
};
// quickform doesn't support optgroups so here's a hack :(
// Instead of using wrapAll or similar that repeatedly appends options to the group and redraw the page (=> very slow on large lists),
// build bulk HTML and insert in single shot
var optGroups = {};
$('option[value^=crm_optgroup]', this).each(function () {
var groupHtml = '';
$(this).nextUntil('option[value^=crm_optgroup]').each(function () {
groupHtml += this.outerHTML;
});
optGroups[$(this).text()] = groupHtml;
$(this).remove();
});
var replacedHtml = '';
for (var groupLabel in optGroups) {
replacedHtml += '<optgroup label="' + groupLabel + '">' + optGroups[groupLabel] + '</optgroup>';
}
if (replacedHtml) {
$el.html(replacedHtml);
}
// quickform does not support disabled option, so yet another hack to
// add disabled property for option values
$('option[value^=crm_disabled_opt]', this).attr('disabled', 'disabled');
// Placeholder icon - total hack hikacking the escapeMarkup function but select2 3.5 dosn't have any other callbacks for this :(
if ($el.is('[class*=fa-]')) {
settings.escapeMarkup = function (m) {
var out = _.escape(m),
placeholder = settings.placeholder || $el.data('placeholder') || $el.attr('placeholder') || $('option[value=""]', $el).text();
if (m.length && placeholder === m) {
iconClass = $el.attr('class').match(/(fa-\S*)/)[1];
out = '<i class="crm-i ' + iconClass + '" aria-hidden="true"></i> ' + out;
}
return out;
};
}
$el
.off('.crmSelect2')
.on('select2-loaded.crmSelect2', function() {
// Use description as title for each option
$('.crm-select2-row-description', '#select2-drop').each(function() {
$(this).closest('.select2-result-label').attr('title', $(this).text());
});
// Collapsible optgroups should be expanded when searching (searching happens within select2-drop for single selects, but within the element for multiselects; this handles both)
if ($('#select2-drop.collapsible-optgroups-enabled .select2-search input.select2-input, .select2-dropdown-open.collapsible-optgroups .select2-search-field input.select2-input').val()) {
$('#select2-drop.collapsible-optgroups-enabled li.select2-result-with-children')
.addClass('optgroup-expanded');
}
})
// Handle collapsible optgroups
.on('select2-open', function(e) {
var isCollapsible = $(e.target).hasClass('collapsible-optgroups');
$('#select2-drop')
.off('.collapseOptionGroup')
.toggleClass('collapsible-optgroups-enabled', isCollapsible);
if (isCollapsible) {
$('#select2-drop')
.on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
$(this).parent().toggleClass('optgroup-expanded');
})
// If the first item in the list is an optgroup, expand it
.find('li.select2-result-with-children:first-child').addClass('optgroup-expanded');
}
})
.on('select2-close', function() {
$('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
});
// Defaults for single-selects
if ($el.is('select:not([multiple])')) {
settings.minimumResultsForSearch = 10;
if ($('option:first', this).val() === '') {
settings.placeholderOption = 'first';
}
}
$.extend(settings, $el.data('select-params') || {}, options || {});
if (settings.ajax) {
$el.addClass('crm-ajax-select');
}
$el.select2(settings);
});
};
function getStaticOptions(staticItems) {
var staticPresets = {
user_contact_id: {
id: 'user_contact_id',
label: ts('Select Current User'),
icon: 'fa-user-circle-o'
}
};
return _.transform(staticItems || [], function(staticItems, option) {
staticItems.push(_.isString(option) ? staticPresets[option] : option);
});
}
function renderQuickAddMarkup(quickAddLinks) {
if (!quickAddLinks || !quickAddLinks.length) {
return '';
}
let markup = '<div class="crm-entityref-links crm-entityref-quick-add">';
CRM.config.quickAdd.forEach((link) => {
if (quickAddLinks.includes(link.path)) {
markup += ' <a class="crm-hover-button" href="' + _.escape(CRM.url(link.path)) + '">' +
'<i class="crm-i ' + _.escape(link.icon) + '" aria-hidden="true"></i> ' +
_.escape(link.title) + '</a>';
}
});
markup += '</div>';
return markup;
}
function renderStaticOptionMarkup(staticItems) {
if (!staticItems.length) {
return '';
}
var markup = '<div class="crm-entityref-links crm-entityref-links-static">';
_.each(staticItems, function(link) {
markup += ' <a class="crm-hover-button" href="#' + _.escape(link.id) + '">' +
'<i class="crm-i ' + _.escape(link.icon) + '" aria-hidden="true"></i> ' +
_.escape(link.label) + '</a>';
});
markup += '</div>';
return markup;
}
// Autocomplete based on APIv4 and Select2.
$.fn.crmAutocomplete = function(entityName, apiParams, select2Options) {
function getApiParams() {
if (typeof apiParams === 'function') {
return apiParams();
}
return apiParams || {};
}
if (entityName === 'destroy') {
return $(this).off('.crmEntity').crmSelect2('destroy');
}
select2Options = select2Options || {};
return $(this).each(function() {
const $el = $(this).off('.crmEntity');
let staticItems = getStaticOptions(select2Options.static),
quickAddLinks = select2Options.quickAdd,
multiple = !!select2Options.multiple;
$el.crmSelect2(_.extend({
ajax: {
quietMillis: 250,
url: CRM.url('civicrm/ajax/api4/' + entityName + '/autocomplete'),
data: function (input, pageNum) {
return {params: JSON.stringify(_.assign({
input: input,
page: pageNum || 1
}, getApiParams()))};
},
results: function(data) {
return {
results: data.values,
more: data.count > data.countFetched
};
},
},
minimumInputLength: 1,
formatResult: CRM.utils.formatSelect2Result,
formatSelection: formatEntityRefSelection,
escapeMarkup: _.identity,
initSelection: function($el, callback) {
var val = $el.val();
if (val === '') {
return;
}
var idsNeeded = _.difference(val.split(','), _.pluck(staticItems, 'id')),
existing = _.filter(staticItems, function(item) {
return _.includes(val.split(','), item.id);
});
// If we already have the data, just return it
if (!idsNeeded.length) {
callback(multiple ? existing : existing[0]);
} else {
var params = $.extend({}, getApiParams(), {ids: idsNeeded});
CRM.api4(entityName, 'autocomplete', params).then(function (result) {
callback(multiple ? result.concat(existing) : result[0]);
});
}
},
formatInputTooShort: function() {
let html = _.escape($.fn.select2.defaults.formatInputTooShort.call(this));
html += renderStaticOptionMarkup(staticItems);
html += renderQuickAddMarkup(quickAddLinks);
return html;
},
formatNoMatches: function() {
let html = _.escape($.fn.select2.defaults.formatNoMatches);
html += renderQuickAddMarkup(quickAddLinks);
return html;
}
}, select2Options));
$el.on('select2-open.crmEntity', function(){
var $el = $(this);
$('#select2-drop')
.off('.crmEntity')
// Add static item to selection when clicking static links
.on('click.crmEntity', '.crm-entityref-links-static a', function() {
let id = $(this).attr('href').substring(1),
item = _.findWhere(staticItems, {id: id});
$el.select2('close');
if (multiple) {
var selection = $el.select2('data');
if (!_.findWhere(selection, {id: id})) {
selection.push(item);
$el.select2('data', selection, true);
}
} else {
$el.select2('data', item, true);
}
return false;
})
// Pop-up Afform when clicking quick-add links
.on('click.crmEntity', '.crm-entityref-quick-add a', function() {
let url = $(this).attr('href');
$el.select2('close');
CRM.loadForm(url).on('crmFormSuccess', (e, data) => {
// Quick-add Afform has been submitted, parse submission data for id of created entity
const response = data.submissionResponse && data.submissionResponse[0];
let createdId;
if (typeof response === 'object') {
let key = getApiParams().key || 'id';
// Loop through entities created by the afform (there should be only one)
Object.keys(response).forEach((entity) => {
if (Array.isArray(response[entity]) && response[entity][0] && response[entity][0][key]) {
createdId = response[entity][0][key];
}
});
}
// Update field value with new id and the widget will automatically fetch the label
if (createdId) {
if (multiple && $el.val()) {
// Select2 v3 uses a string instead of array for multiple values
$el.val($el.val() + ',' + createdId).change();
} else {
$el.val('' + createdId).change();
}
}
});
return false;
});
});
});
};
/**
* @see CRM_Core_Form::addEntityRef for docs
* @param options object
*/
$.fn.crmEntityRef = function(options) {
if (options === 'destroy') {
return $(this).each(function() {
var entity = $(this).data('api-entity') || '';
$(this)
.off('.crmEntity')
.removeClass('crm-form-entityref crm-' + _.kebabCase(entity) + '-ref')
.crmSelect2('destroy');
});
}
options = options || {};
options.select = options.select || {};
return $(this).each(function() {
var
$el = $(this).off('.crmEntity'),
entity = options.entity || $el.data('api-entity') || 'Contact',
selectParams = {};
// Legacy: fix entity name if passed in as snake case
if (entity.charAt(0).toUpperCase() !== entity.charAt(0)) {
entity = _.capitalize(_.camelCase(entity));
}
$el.data('api-entity', entity);
$el.data('select-params', $.extend({}, $el.data('select-params') || {}, options.select));
$el.data('api-params', $.extend(true, {}, $el.data('api-params') || {}, options.api));
$el.data('create-links', options.create || $el.data('create-links'));
$el.addClass('crm-form-entityref crm-' + _.kebabCase(entity) + '-ref');
var settings = {
// Use select2 ajax helper instead of CRM.api3 because it provides more value
ajax: {
url: CRM.url('civicrm/ajax/rest'),
quietMillis: 300,
data: function (input, page_num) {
var params = getEntityRefApiParams($el);
params.input = input;
params.page_num = page_num;
return {
entity: $el.data('api-entity'),
action: 'getlist',
json: JSON.stringify(params)
};
},
results: function(data) {
return {more: data.more_results, results: data.values || []};
}
},
minimumInputLength: 1,
formatResult: CRM.utils.formatSelect2Result,
formatSelection: formatEntityRefSelection,
escapeMarkup: _.identity,
initSelection: function($el, callback) {
var
multiple = !!$el.data('select-params').multiple,
val = $el.val(),
stored = $el.data('entity-value') || [];
if (val === '') {
return;
}
var idsNeeded = _.difference(val.split(','), _.pluck(stored, 'id'));
var existing = _.remove(stored, function(item) {
return _.includes(val.split(','), item.id);
});
// If we already have this data, just return it
if (!idsNeeded.length) {
callback(multiple ? existing : existing[0]);
} else {
var params = $.extend({}, $el.data('api-params') || {}, {id: idsNeeded.join(',')});
CRM.api3($el.data('api-entity'), 'getlist', params).done(function(result) {
callback(multiple ? result.values.concat(existing) : result.values[0]);
// Trigger change (store data to avoid an infinite loop of lookups)
$el.data('entity-value', result.values).trigger('change');
});
}
}
};
// Create new items inline - works for tags
if ($el.data('create-links') && entity === 'Tag') {
selectParams.createSearchChoice = function(term, data) {
if (!_.findKey(data, {label: term})) {
return {id: "0", term: term, label: term + ' (' + ts('new tag') + ')'};
}
};
selectParams.tokenSeparators = [','];
selectParams.createSearchChoicePosition = 'bottom';
$el.on('select2-selecting.crmEntity', function(e) {
if (e.val === "0") {
// Create a new term
e.object.label = e.object.term;
CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {}))
.done(function(created) {
var
val = $el.select2('val'),
data = $el.select2('data'),
item = {id: created.id, label: e.object.term};
if (val === "0") {
$el.select2('data', item, true);
}
else if ($.isArray(val) && $.inArray("0", val) > -1) {
_.remove(data, {id: "0"});
data.push(item);
$el.select2('data', data, true);
}
});
}
});
}
else {
selectParams.formatInputTooShort = function() {
var txt = _.escape($el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this));
txt += entityRefFiltersMarkup($el) + renderEntityRefCreateLinks($el);
return txt;
};
selectParams.formatNoMatches = function() {
var txt = _.escape($el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches);
txt += entityRefFiltersMarkup($el) + renderEntityRefCreateLinks($el);
return txt;
};
$el.on('select2-open.crmEntity', function() {
var $el = $(this);
$('#select2-drop')
.off('.crmEntity')
.on('click.crmEntity', 'a.crm-add-entity', function(e) {
var extra = $el.data('api-params').extra,
formUrl = $(this).attr('href') + '&returnExtra=display_name,sort_name' + (extra ? (',' + extra) : '');
$el.select2('close');
CRM.loadForm(formUrl, {
dialog: {width: '50%', height: 220}
}).on('crmFormSuccess', function(e, data) {
if (data.status === 'success' && data.id) {
if (!data.crmMessages) {
CRM.status(ts('%1 Created', {1: data.label || data.extra.display_name}));
}
data.label = data.label || data.extra.sort_name;
if ($el.select2('container').hasClass('select2-container-multi')) {
var selection = $el.select2('data');
selection.push(data);
$el.select2('data', selection, true);
} else {
$el.select2('data', data, true);
}
}
});
return false;
})
.on('change.crmEntity', '.crm-entityref-filter-value', function() {
var filter = $el.data('user-filter') || {};
filter.value = $(this).val();
$(this).toggleClass('active', !!filter.value);
$el.data('user-filter', filter);
if (filter.value && $(this).is('select')) {
// Once a filter has been chosen, rerender create links and refocus the search box
$el.select2('close');
$el.select2('open');
} else {
$('.crm-entityref-links-create', '#select2-drop').replaceWith(renderEntityRefCreateLinks($el));
}
})
.on('change.crmEntity', 'select.crm-entityref-filter-key', function() {
var filter = {key: $(this).val()};
$(this).toggleClass('active', !!filter.key);
$el.data('user-filter', filter);
renderEntityRefFilterValue($el);
$('.crm-entityref-filter-key', '#select2-drop').focus();
});
});
}
$el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams));
});
};
/**
* Combine api-params with user-filter
* @param $el
* @returns {*}
*/
function getEntityRefApiParams($el) {
var
params = $.extend({params: {}}, $el.data('api-params') || {}),
// Prevent original data from being modified - $.extend and _.clone don't cut it, they pass nested objects by reference!
combined = _.cloneDeep(params),
filter = $.extend({}, $el.data('user-filter') || {});
if (filter.key && filter.value) {
// Fieldname may be prefixed with joins
var fieldName = _.last(filter.key.split('.'));
// Special case for contact type/sub-type combo
if (fieldName === 'contact_type' && (filter.value.indexOf('__') > 0)) {
combined.params[filter.key] = filter.value.split('__')[0];
combined.params[filter.key.replace('contact_type', 'contact_sub_type')] = filter.value.split('__')[1];
} else {
// Allow json-encoded api filters e.g. {"BETWEEN":[123,456]}
combined.params[filter.key] = filter.value.charAt(0) === '{' ? $.parseJSON(filter.value) : filter.value;
}
}
return combined;
}
CRM.utils.copyAttributes = function ($source, $target, attributes) {
_.each(attributes, function(name) {
if ($source.attr(name) !== undefined) {
$target.attr(name, $source.attr(name));
}
});
};
CRM.utils.formatSelect2Result = function (row) {
var markup = '<div class="crm-select2-row">';
if (row.image !== undefined) {
markup += '<div class="crm-select2-image"><img src="' + _.escape(row.image) + '"/></div>';
}
else if (row.icon_class) {
markup += '<div class="crm-select2-icon"><div class="crm-icon ' + _.escape(row.icon_class) + '-icon"></div></div>';
}
markup += '<div><div class="crm-select2-row-label ' + _.escape(row.label_class || '') + '">' +
(row.color ? '<span class="crm-select-item-color" style="background-color: ' + _.escape(row.color) + '"></span> ' : '') +
(row.icon ? '<i class="crm-i ' + _.escape(row.icon) + '" aria-hidden="true"></i> ' : '') +
_.escape((row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : '')) +
'</div>' +
'<div class="crm-select2-row-description">';
$.each(row.description || [], function(k, text) {
markup += '<p>' + _.escape(text) + '</p> ';
});
markup += '</div></div></div>';
return markup;
};
function formatEntityRefSelection(row) {
return (row.color ? '<span class="crm-select-item-color" style="background-color: ' + _.escape(row.color) + '"></span> ' : '') +
_.escape((row.prefix !== undefined ? row.prefix + ' ' : '') + row.label + (row.suffix !== undefined ? ' ' + row.suffix : ''));
}
function renderEntityRefCreateLinks($el) {
var
createLinks = $el.data('create-links'),
params = getEntityRefApiParams($el).params,
entity = $el.data('api-entity'),
markup = '<div class="crm-entityref-links crm-entityref-links-create">';
if (!createLinks || (createLinks === true && !CRM.config.entityRef.links[entity])) {
return '';
}
if (createLinks === true) {
if (!params.contact_type) {
createLinks = CRM.config.entityRef.links[entity];
}
else if (typeof params.contact_type === 'string') {
createLinks = _.where(CRM.config.entityRef.links[entity], {type: params.contact_type});
} else {
// lets assume it's an array with filters such as IN etc
createLinks = [];
_.each(params.contact_type, function(types) {
_.each(types, function(type) {
createLinks.push(_.findWhere(CRM.config.entityRef.links[entity], {type: type}));
});
});
}
}
_.each(createLinks, function(link) {
markup += ' <a class="crm-add-entity crm-hover-button" href="' + _.escape(link.url) + '">' +
'<i class="crm-i ' + _.escape(link.icon || 'fa-plus-circle') + '" aria-hidden="true"></i> ' +
_.escape(link.label) + '</a>';
});
markup += '</div>';
return markup;
}
function getEntityRefFilters($el) {
var
entity = $el.data('api-entity'),
filters = CRM.config.entityRef.filters[entity] || [],
params = $.extend({params: {}}, $el.data('api-params') || {}).params,
result = [];
_.each(filters, function(filter) {
_.defaults(filter, {type: 'select', 'attributes': {}, entity: entity});
if (!params[filter.key]) {
// Filter out options if params don't match its condition
if (filter.condition && !_.isMatch(params, _.pick(filter.condition, _.keys(params)))) {
return;
}
result.push(filter);
}
else if (filter.key == 'contact_type' && typeof params.contact_sub_type === 'undefined') {
result.push(filter);
}
});
return result;
}
/**
* Provide markup for entity ref filters
*/
function entityRefFiltersMarkup($el) {
var
filters = getEntityRefFilters($el),
filter = $el.data('user-filter') || {},
filterSpec = filter.key ? _.find(filters, {key: filter.key}) : null;
if (!filters.length) {
return '';
}
var markup = '<div class="crm-entityref-filters">' +
'<select class="crm-entityref-filter-key' + (filter.key ? ' active' : '') + '">' +
'<option value="">' + _.escape(ts('Refine search...')) + '</option>' +
CRM.utils.renderOptions(filters, filter.key) +
'</select>' + entityRefFilterValueMarkup($el, filter, filterSpec) + '</div>';