Bridge search displays and afforms
[civicrm-core.git] / ext / search / Civi / Search / AfformSearchMetadataInjector.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 namespace Civi\Search;
13
14 /**
15 * Class AfformSearchMetadataInjector
16 * @package Civi\Search
17 */
18 class AfformSearchMetadataInjector {
19
20 /**
21 * Injects settings data into search displays embedded in afforms
22 *
23 * @param \Civi\Core\Event\GenericHookEvent $e
24 * @see CRM_Utils_Hook::alterAngular()
25 */
26 public static function preprocess($e) {
27 $changeSet = \Civi\Angular\ChangeSet::create('searchSettings')
28 ->alterHtml(';\\.aff\\.html$;', function($doc, $path) {
29 $displayTypes = array_column(\Civi\Search\Display::getDisplayTypes(['name']), 'name');
30
31 if ($displayTypes) {
32 $displayTypeTags = 'crm-search-display-' . implode(', crm-search-display-', $displayTypes);
33 foreach (pq($displayTypeTags, $doc) as $component) {
34 $searchName = pq($component)->attr('search-name');
35 $displayName = pq($component)->attr('display-name');
36 if ($searchName && $displayName) {
37 $display = \Civi\Api4\SearchDisplay::get(FALSE)
38 ->addWhere('name', '=', $displayName)
39 ->addWhere('saved_search.name', '=', $searchName)
40 ->addSelect('settings', 'saved_search.api_entity', 'saved_search.api_params')
41 ->execute()->first();
42 if ($display) {
43 pq($component)->attr('settings', \CRM_Utils_JS::encode($display['settings'] ?? []));
44 pq($component)->attr('api-entity', \CRM_Utils_JS::encode($display['saved_search.api_entity']));
45 pq($component)->attr('api-params', \CRM_Utils_JS::encode($display['saved_search.api_params']));
46
47 // Add entity names to the fieldset so that afform can populate field metadata
48 $fieldset = pq($component)->parents('[af-fieldset]');
49 if ($fieldset->length) {
50 $entityList = array_merge([$display['saved_search.api_entity']], array_column($display['saved_search.api_params']['join'] ?? [], 0));
51 $fieldset->attr('api-entities', \CRM_Utils_JS::encode($entityList));
52 }
53 }
54 }
55 }
56 }
57 });
58 $e->angular->add($changeSet);
59
60 }
61
62 }