From 4c993609f146b0d5ccc4685812782242a165b084 Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Tue, 29 Apr 2014 10:29:57 -0700 Subject: [PATCH] CRM-13966 - Add entityRef support for free tagging --- js/Common.js | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/js/Common.js b/js/Common.js index 2df825d164..ae938704ed 100644 --- a/js/Common.js +++ b/js/Common.js @@ -276,7 +276,7 @@ CRM.validate = CRM.validate || { options.select = options.select || {}; return $(this).each(function() { var - $el = $(this), + $el = $(this).off('.crmEntity'), entity = options.entity || $el.data('api-entity') || 'contact', selectParams = {}; $el.data('api-entity', entity); @@ -327,7 +327,7 @@ CRM.validate = CRM.validate || { } } }; - if ($el.data('create-links')) { + if ($el.data('create-links') && entity.toLowerCase() === 'contact') { selectParams.formatInputTooShort = function() { var txt = $el.data('select-params').formatInputTooShort || $.fn.select2.defaults.formatInputTooShort.call(this); if ($el.data('create-links')) { @@ -339,7 +339,7 @@ CRM.validate = CRM.validate || { var txt = $el.data('select-params').formatNoMatches || $.fn.select2.defaults.formatNoMatches; return txt + '
' + formatSelect2CreateLinks($el); }; - $el.off('.createLinks').on('select2-open.createLinks', function() { + $el.on('select2-open.crmEntity', function() { var $el = $(this); $('#select2-drop').off('.crmEntity').on('click.crmEntity', 'a.crm-add-entity', function(e) { $el.select2('close'); @@ -361,7 +361,38 @@ CRM.validate = CRM.validate || { }); }); } - $el.crmSelect2($.extend(settings, $el.data('select-params'), selectParams)); + // Create new items inline - works for tags + else if ($el.data('create-links')) { + 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.crmSelect2($.extend(settings, $el.data('select-params'), selectParams)) + .on('select2-selecting.crmEntity', function(e) { + if (e.val === "0") { + e.object.label = e.object.term; + CRM.api3(entity, 'create', $.extend({name: e.object.term}, $el.data('api-params').params || {})) + .done(function(created) { + var + multiple = !!$el.data('select-params').multiple, + val = $el.select2('val'), + data = $el.select2('data'), + item = {id: created.id, label: e.object.term}; + if (val === "0") { + $el.select2('data', item); + } + else if ($.isArray(val) && $.inArray("0", val) > -1) { + _.remove(data, {id: "0"}); + data.push(item); + $el.select2('data', data); + } + }); + } + }); }); }; -- 2.25.1