3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 * Base class for most search forms
15 class CRM_Core_Form_Search
extends CRM_Core_Form
{
18 * Are we forced to run a search
25 * Name of search button
29 protected $_searchButtonName;
32 * Name of action button
36 protected $_actionButtonName;
39 * Form values that we will be using
46 * Have we already done this search
53 * What context are we being invoked from
60 * The list of tasks or actions that a searcher can perform on a result set.
64 protected $_taskList = [];
67 * Declare entity reference fields as they will need to be converted.
69 * The entity reference format looks like '2,3' whereas the Query object expects array(2, 3)
70 * or array('IN' => array(2, 3). The latter is the one we are moving towards standardising on.
74 protected $entityReferenceFields = [];
77 * Builds the list of tasks or actions that a searcher can perform on a result set.
79 * To modify the task list, child classes should alter $this->_taskList,
80 * preferably by extending this method.
84 protected function buildTaskList() {
85 return $this->_taskList
;
89 * Should we be adding all the metadata for contact search fields or just for the sort name.
93 protected $sortNameOnly = FALSE;
96 * Metadata for fields on the search form.
98 * Instantiate with empty array for contact to prevent e-notices.
102 protected $searchFieldMetadata = ['Contact' => []];
107 public function getSearchFieldMetadata() {
108 return $this->searchFieldMetadata
;
112 * @param array $searchFieldMetadata
114 public function addSearchFieldMetadata($searchFieldMetadata) {
115 $this->searchFieldMetadata
= array_merge($this->searchFieldMetadata
, $searchFieldMetadata);
119 * Prepare for search by loading options from the url, handling force searches, retrieving form values.
121 * @throws \CRM_Core_Exception
122 * @throws \CiviCRM_API3_Exception
124 public function preProcess() {
125 $this->loadStandardSearchOptionsFromUrl();
127 $this->handleForcedSearch();
129 $this->_formValues
= $this->getFormValues();
133 * This virtual function is used to set the default values of various form elements.
136 * reference to the array of default values
137 * @throws \CRM_Core_Exception
139 public function setDefaultValues() {
140 // Use the form values stored to the form. Ideally 'formValues'
141 // would remain 'pure' & another array would be wrangled.
142 // We don't do that - so we want the version of formValues stored early on.
143 $defaults = (array) $this->get('formValues');
144 foreach (array_keys($this->getSearchFieldMetadata()) as $entity) {
145 $defaults = array_merge($this->getEntityDefaults($entity), $defaults);
151 * Set the form values based on input and preliminary processing.
153 * @throws \CRM_Core_Exception
155 protected function setFormValues() {
156 $this->_formValues
= $this->getFormValues();
157 $this->set('formValues', $this->_formValues
);
158 $this->convertTextStringsToUseLikeOperator();
162 * Common buildForm tasks required by all searches.
164 * @throws \CRM_Core_Exception
166 public function buildQuickForm() {
167 CRM_Core_Resources
::singleton()
168 ->addScriptFile('civicrm', 'js/crm.searchForm.js', 1, 'html-header')
169 ->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
174 'name' => ts('Search'),
179 $this->addClass('crm-search-form');
181 $tasks = $this->buildTaskList();
182 $this->addTaskMenu($tasks);
186 * Add any fields described in metadata to the form.
188 * The goal is to describe all fields in metadata and handle from metadata rather
189 * than existing ad hoc handling.
191 * @throws \CiviCRM_API3_Exception
193 public function addFormFieldsFromMetadata() {
194 $this->addFormRule(['CRM_Core_Form_Search', 'formRule'], $this);
195 $this->_action
= CRM_Core_Action
::ADVANCED
;
196 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
197 foreach ($fields as $fieldName => $fieldSpec) {
198 $fieldType = $fieldSpec['type'] ??
'';
199 if ($fieldType === CRM_Utils_Type
::T_DATE ||
$fieldType === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) ||
$fieldType === CRM_Utils_Type
::T_TIMESTAMP
) {
200 $title = empty($fieldSpec['unique_title']) ?
$fieldSpec['title'] : $fieldSpec['unique_title'];
201 $this->addDatePickerRange($fieldName, $title, ($fieldType === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) ||
$fieldType === CRM_Utils_Type
::T_TIMESTAMP
));
204 // Not quite sure about moving to a mix of keying by entity vs permitting entity to
205 // be passed in. The challenge of the former is that it doesn't permit ordering.
206 // Perhaps keying was the wrong starting point & we should do a flat array as all
207 // fields eventually need to be unique.
208 $props = ['entity' => $fieldSpec['entity'] ??
$entity];
209 if (isset($fields[$fieldName]['unique_title'])) {
210 $props['label'] = $fields[$fieldName]['unique_title'];
212 elseif (isset($fields[$fieldName]['title'])) {
213 $props['label'] = $fields[$fieldName]['title'];
215 if (empty($fieldSpec['is_pseudofield'])) {
216 $this->addField($fieldName, $props);
224 * Global validation rules for the form.
226 * @param array $fields
227 * Posted values of the form.
228 * @param array $files
229 * @param object $form
232 * list of errors to be posted back to the form
234 public static function formRule($fields, $files, $form) {
236 if (!is_a($form, 'CRM_Core_Form_Search')) {
237 // So this gets hit with a form object when doing an activity date search from
238 // advanced search, but a NULL object when doing a pledge search.
241 foreach ($form->getSearchFieldMetadata() as $entity => $spec) {
242 foreach ($spec as $fieldName => $fieldSpec) {
243 if ($fieldSpec['type'] === CRM_Utils_Type
::T_DATE ||
$fieldSpec['type'] === (CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)) {
244 if (!empty($fields[$fieldName . '_high']) && !empty($fields[$fieldName . '_low']) && empty($fields[$fieldName . '_relative'])) {
245 if (strtotime($fields[$fieldName . '_low']) > strtotime($fields[$fieldName . '_high'])) {
246 $errors[$fieldName . '_low'] = ts('%1: Please check that your date range is in correct chronological order.', [1 => $fieldSpec['title']]);
256 * Get the validation rule to apply to a function.
258 * Alphanumeric is designed to always be safe & for now we just return
259 * that but in future we can use tighter rules for types like int, bool etc.
261 * @param string $entity
262 * @param string $fieldName
266 protected function getValidationTypeForField($entity, $fieldName) {
267 switch ($this->getSearchFieldMetadata()[$entity][$fieldName]['type']) {
268 case CRM_Utils_Type
::T_BOOLEAN
:
271 case CRM_Utils_Type
::T_INT
:
272 return 'CommaSeparatedIntegers';
274 case CRM_Utils_Type
::T_DATE
:
275 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
279 return 'Alphanumeric';
284 * Get the defaults for the entity for any fields described in metadata.
286 * @param string $entity
290 * @throws \CRM_Core_Exception
292 protected function getEntityDefaults($entity) {
294 foreach (CRM_Utils_Array
::value($entity, $this->getSearchFieldMetadata(), []) as $fieldName => $fieldSpec) {
295 if (empty($_POST[$fieldName])) {
296 $value = CRM_Utils_Request
::retrieveValue($fieldName, $this->getValidationTypeForField($entity, $fieldName), NULL, NULL, 'GET');
297 if ($value !== NULL) {
298 if ($fieldSpec['html']['type'] === 'Select') {
299 $defaults[$fieldName] = explode(',', $value);
302 $defaults[$fieldName] = $value;
305 if ($fieldSpec['type'] === CRM_Utils_Type
::T_DATE ||
($fieldSpec['type'] === CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
)) {
306 $low = CRM_Utils_Request
::retrieveValue($fieldName . '_low', 'Timestamp', NULL, NULL, 'GET');
307 $high = CRM_Utils_Request
::retrieveValue($fieldName . '_high', 'Timestamp', NULL, NULL, 'GET');
308 if ($low !== NULL ||
$high !== NULL) {
309 $defaults[$fieldName . '_relative'] = 0;
310 $defaults[$fieldName . '_low'] = $low ?
date('Y-m-d H:i:s', strtotime($low)) : NULL;
311 $defaults[$fieldName . '_high'] = $high ?
date('Y-m-d H:i:s', strtotime($high)) : NULL;
314 $relative = CRM_Utils_Request
::retrieveValue($fieldName . '_relative', 'String', NULL, NULL, 'GET');
315 if (!empty($relative) && isset(CRM_Core_OptionGroup
::values('relative_date_filters')[$relative])) {
316 $defaults[$fieldName . '_relative'] = $relative;
326 * Convert any submitted text fields to use 'like' rather than '=' as the operator.
328 * This excludes any with options.
330 * Note this will only pick up fields declared via metadata.
332 protected function convertTextStringsToUseLikeOperator() {
333 foreach ($this->getSearchFieldMetadata() as $entity => $fields) {
334 foreach ($fields as $fieldName => $field) {
335 if (!empty($this->_formValues
[$fieldName]) && empty($field['options']) && empty($field['pseudoconstant'])) {
336 if (in_array($field['type'], [CRM_Utils_Type
::T_STRING
, CRM_Utils_Type
::T_TEXT
])) {
337 $this->_formValues
[$fieldName] = ['LIKE' => CRM_Contact_BAO_Query
::getWildCardedValue(TRUE, 'LIKE', trim($this->_formValues
[$fieldName]))];
345 * Add checkboxes for each row plus a master checkbox.
349 public function addRowSelectors($rows) {
350 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
352 foreach ($rows as $row) {
353 if (!empty($row['checkbox'])) {
354 $this->addElement('checkbox', $row['checkbox'], NULL, NULL, ['class' => 'select-row']);
361 * Add actions menu to search results form.
363 * @param array $tasks
365 public function addTaskMenu($tasks) {
367 foreach ($tasks as $key => $task) {
368 $taskMetaData[$key] = ['title' => $task];
370 parent
::addTaskMenu($taskMetaData);
374 * Add the sort-name field to the form.
376 * There is a setting to determine whether email is included in the search & we look this up to determine
377 * which text to choose.
379 * Note that for translation purposes the full string works better than using 'prefix' hence we use override-able functions
380 * to define the string.
382 * @throws \CiviCRM_API3_Exception
384 protected function addSortNameField() {
385 $title = civicrm_api3('setting', 'getvalue', ['name' => 'includeEmailInName', 'group' => 'Search Preferences']) ?
$this->getSortNameLabelWithEmail() : $this->getSortNameLabelWithOutEmail();
390 CRM_Core_DAO
::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')
392 $this->searchFieldMetadata
['Contact']['sort_name'] = array_merge(CRM_Contact_DAO_Contact
::fields()['sort_name'], ['name' => 'sort_name', 'title' => $title, 'type' => CRM_Utils_Type
::T_STRING
]);
396 * Get the label for the sortName field if email searching is on.
398 * (email searching is a setting under search preferences).
402 protected function getSortNameLabelWithEmail() {
403 return ts('Name or Email');
407 * Get the label for the sortName field if email searching is off.
409 * (email searching is a setting under search preferences).
413 protected function getSortNameLabelWithOutEmail() {
418 * Explicitly declare the form context for addField().
420 public function getDefaultContext() {
425 * Add generic fields that specify the contact.
427 * @throws \CiviCRM_API3_Exception
429 protected function addContactSearchFields() {
430 if (!$this->isFormInViewOrEditMode()) {
433 $this->addSortNameField();
434 if ($this->sortNameOnly
) {
438 $this->_group
= CRM_Core_PseudoConstant
::nestedGroup();
440 $this->add('select', 'group', $this->getGroupLabel(), $this->_group
, FALSE,
443 'multiple' => 'multiple',
444 'class' => 'crm-select2',
447 $this->searchFieldMetadata
['Contact']['group'] = ['name' => 'group', 'type' => CRM_Utils_Type
::T_INT
, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Select']];
450 $contactTags = CRM_Core_BAO_Tag
::getTags();
452 $this->add('select', 'contact_tags', $this->getTagLabel(), $contactTags, FALSE,
454 'id' => 'contact_tags',
455 'multiple' => 'multiple',
456 'class' => 'crm-select2',
460 $this->searchFieldMetadata
['Contact']['contact_tags'] = ['name' => 'contact_tags', 'type' => CRM_Utils_Type
::T_INT
, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Select']];
461 $this->addField('contact_type', ['entity' => 'Contact']);
462 $this->searchFieldMetadata
['Contact']['contact_type'] = CRM_Contact_DAO_Contact
::fields()['contact_type'];
464 if (CRM_Core_Permission
::check('access deleted contacts') && Civi
::settings()->get('contact_undelete')) {
465 $this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
466 $this->searchFieldMetadata
['Contact']['deleted_contacts'] = ['name' => 'deleted_contacts', 'type' => CRM_Utils_Type
::T_INT
, 'is_pseudofield' => TRUE, 'html' => ['type' => 'Checkbox']];
472 * Get the label for the group field.
476 protected function getGroupLabel() {
477 return ts('Group(s)');
481 * Get the label for the tag field.
483 * We do this in a function so the 'ts' wraps the whole string to allow
484 * better translation.
488 protected function getTagLabel() {
493 * we allow the controller to set force/reset externally, useful when we are being
494 * driven by the wizard framework
496 * @throws \CRM_Core_Exception
498 protected function loadStandardSearchOptionsFromUrl() {
499 $this->_reset
= CRM_Utils_Request
::retrieve('reset', 'Boolean');
500 $this->_force
= CRM_Utils_Request
::retrieve('force', 'Boolean', $this, FALSE);
501 $this->_limit
= CRM_Utils_Request
::retrieve('limit', 'Positive', $this);
502 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this, FALSE, 'search');
503 $this->_ssID
= CRM_Utils_Request
::retrieve('ssID', 'Positive', $this);
504 $this->assign("context", $this->_context
);
508 * Get user submitted values.
510 * Get it from controller only if form has been submitted, else preProcess has set this
512 protected function loadFormValues() {
513 if (!empty($_POST) && !$this->controller
->isModal()) {
514 $this->_formValues
= $this->controller
->exportValues($this->_name
);
517 $this->_formValues
= $this->get('formValues');
520 if (empty($this->_formValues
)) {
521 if (isset($this->_ssID
)) {
522 $this->_formValues
= CRM_Contact_BAO_SavedSearch
::getFormValues($this->_ssID
);
528 * Get the form values.
530 * @todo consolidate with loadFormValues()
534 * @throws \CRM_Core_Exception
536 protected function getFormValues() {
537 if (!empty($_POST) && !$this->_force
) {
538 return $this->controller
->exportValues($this->_name
);
541 return $this->setDefaultValues();
543 return (array) $this->get('formValues');
547 * Get the string processed to determine sort order.
549 * This looks like 'sort_name_u' for Sort name ascending.
551 * @return string|null
553 protected function getSortID() {
554 if ($this->get(CRM_Utils_Sort
::SORT_ID
)) {
555 return CRM_Utils_Sort
::sortIDValue($this->get(CRM_Utils_Sort
::SORT_ID
),
556 $this->get(CRM_Utils_Sort
::SORT_DIRECTION
)
563 * Set the metadata for the form.
565 * @throws \CiviCRM_API3_Exception
567 protected function setSearchMetadata() {}
570 * Handle force=1 in the url.
572 * Search field metadata is normally added in buildForm but we are bypassing that in this flow
573 * (I've always found the flow kinda confusing & perhaps that is the problem but this mitigates)
575 * @throws \CiviCRM_API3_Exception
577 protected function handleForcedSearch() {
578 $this->setSearchMetadata();
579 $this->addContactSearchFields();
580 $this->postProcess();
581 $this->set('force', 0);