Afform - Apply "type" values to autocomplete filters
authorColeman Watts <coleman@civicrm.org>
Sat, 6 Aug 2022 21:50:40 +0000 (17:50 -0400)
committerColeman Watts <coleman@civicrm.org>
Wed, 10 Aug 2022 02:28:44 +0000 (22:28 -0400)
This ensures that if e.g. a Contact or Activity has its type specified on the form
it will also be limited to that type in autocomplete results when selecting an existing entity.

CRM/Core/BAO/CustomGroup.php
ext/afform/core/Civi/Api4/Subscriber/AutocompleteSubscriber.php

index 3b6e9269cf801a4c1f94599bd010b6e1ba246427..f7c1c6d1af69306c0273560bc07fae70073f16c7 100644 (file)
@@ -2473,7 +2473,7 @@ SELECT  civicrm_custom_group.id as groupID, civicrm_custom_group.title as groupT
       [
         'id' => 'Pledge',
         'label' => ts('Pledges'),
-        'grouping' => 'TODO',
+        'grouping' => NULL,
         'table_name' => 'civicrm_pledge',
       ],
       [
index ece48d09321c9843d6e9cebad527ec80e3740664..685a99c95d94a60cb700bf15beba830998a83749 100644 (file)
@@ -46,19 +46,31 @@ class AutocompleteSubscriber implements EventSubscriberInterface {
       $afform = Afform::get()
         ->addWhere('name', '=', str_replace('afform:', '', $formName))
         ->addSelect('layout')
-        ->setLayoutFormat('shallow')
         ->execute()->first();
       if (!$afform) {
         return;
       }
       $formDataModel = new FormDataModel($afform['layout']);
       $entity = $formDataModel->getEntity($entityName);
-      $defn = [];
-      if (!empty($entity['fields'][$fieldName]['defn'])) {
-        $defn = \CRM_Utils_JS::decode($entity['fields'][$fieldName]['defn']);
+
+      // Look up the "type" fields (e.g. contact_type, activity_type_id, case_type_id, etc)
+      $typeFields = [];
+      if ($entity['type'] === 'Contact') {
+        $typeFields = ['contact_type', 'contact_sub_type'];
+      }
+      else {
+        $extends = array_column(\CRM_Core_BAO_CustomGroup::getCustomGroupExtendsOptions(), 'grouping', 'id');
+        $typeFields = (array) ($extends[$entity['type']] ?? NULL);
       }
+      // If entity has a type set in the values, auto-apply that to filters
+      foreach ($typeFields as $typeField) {
+        if (!empty($entity['data'][$typeField])) {
+          $apiRequest->addFilter($typeField, $entity['data'][$typeField]);
+        }
+      }
+
       $apiRequest->setCheckPermissions($entity['security'] !== 'FBAC');
-      $apiRequest->setSavedSearch($defn['saved_search'] ?? NULL);
+      $apiRequest->setSavedSearch($entity['fields'][$fieldName]['defn']['saved_search'] ?? NULL);
     }
   }