From 100e56dc14f676929070d0b70b3ff65db9ef5bd1 Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Sat, 30 Jul 2022 18:04:57 -0400 Subject: [PATCH] Add APIv4-based autocomplete widget --- CRM/Api4/Page/AJAX.php | 3 +- Civi/Api4/Generic/AutocompleteAction.php | 2 +- js/Common.js | 41 ++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/CRM/Api4/Page/AJAX.php b/CRM/Api4/Page/AJAX.php index 0aa40e94d9..638d547624 100644 --- a/CRM/Api4/Page/AJAX.php +++ b/CRM/Api4/Page/AJAX.php @@ -40,7 +40,8 @@ class CRM_Api4_Page_AJAX extends CRM_Core_Page { CRM_Utils_System::civiExit(); } if ($_SERVER['REQUEST_METHOD'] == 'GET' && - strtolower(substr($this->urlPath[4], 0, 3)) != 'get') { + ($this->urlPath[4] !== 'autocomplete' && strtolower(substr($this->urlPath[4], 0, 3)) !== 'get') + ) { $response = [ 'error_code' => 400, 'error_message' => "SECURITY: All requests that modify the database must be http POST, not GET.", diff --git a/Civi/Api4/Generic/AutocompleteAction.php b/Civi/Api4/Generic/AutocompleteAction.php index 339245f184..4ebbf7c7bd 100644 --- a/Civi/Api4/Generic/AutocompleteAction.php +++ b/Civi/Api4/Generic/AutocompleteAction.php @@ -67,7 +67,7 @@ class AutocompleteAction extends AbstractAction { $labelField = CoreUtil::getInfoItem($entityName, 'label_field'); $map = [ 'id' => $idField, - 'text' => $labelField, + 'label' => $labelField, ]; // FIXME: Use metadata if (isset($fields['description'])) { diff --git a/js/Common.js b/js/Common.js index 07eb96b84a..1c8d621b3f 100644 --- a/js/Common.js +++ b/js/Common.js @@ -523,6 +523,47 @@ if (!CRM.vars) CRM.vars = {}; }); }; + // Autocomplete based on APIv4 and Select2. + $.fn.crmAutocomplete = function(entityName, apiParams, select2Options) { + select2Options = select2Options || {}; + return $(this).each(function() { + $(this).crmSelect2({ + 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 + }, apiParams))}; + }, + 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 + multiple = !!select2Options.multiple, + val = $el.val(); + if (val === '') { + return; + } + var params = $.extend({}, apiParams || {}, {ids: val.split(',')}); + CRM.api4(entityName, 'autocomplete', params).then(function(result) { + callback(multiple ? result : result[0]); + }); + } + }); + }); + }; + /** * @see CRM_Core_Form::addEntityRef for docs * @param options object -- 2.25.1