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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Business objects for managing custom data fields.
21 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
24 * Array to hold (formatted) fields for import
28 public static $_importFields = NULL;
31 * Build and retrieve the list of data types and descriptions.
34 * Data type => Description
36 public static function dataType() {
38 'String' => ts('Alphanumeric'),
39 'Int' => ts('Integer'),
40 'Float' => ts('Number'),
41 'Money' => ts('Money'),
44 'Boolean' => ts('Yes or No'),
45 'StateProvince' => ts('State/Province'),
46 'Country' => ts('Country'),
49 'ContactReference' => ts('Contact Reference'),
54 * Build the map of custom field's data types and there respective Util type
57 * Data data-type => CRM_Utils_Type
59 public static function dataToType() {
61 'String' => CRM_Utils_Type
::T_STRING
,
62 'Int' => CRM_Utils_Type
::T_INT
,
63 'Money' => CRM_Utils_Type
::T_MONEY
,
64 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
65 'Float' => CRM_Utils_Type
::T_FLOAT
,
66 'Date' => CRM_Utils_Type
::T_DATE
,
67 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
68 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
69 'StateProvince' => CRM_Utils_Type
::T_INT
,
70 'File' => CRM_Utils_Type
::T_STRING
,
71 'Link' => CRM_Utils_Type
::T_STRING
,
72 'ContactReference' => CRM_Utils_Type
::T_INT
,
73 'Country' => CRM_Utils_Type
::T_INT
,
78 * Takes an associative array and creates a custom field object.
80 * This function is invoked from within the web form layer and also from the api layer
82 * @param array $params
83 * (reference) an assoc array of name/value pairs.
85 * @return CRM_Core_DAO_CustomField
87 public static function create($params) {
88 $customField = self
::createCustomFieldRecord($params);
89 $op = empty($params['id']) ?
'add' : 'modify';
90 self
::createField($customField, $op);
92 CRM_Utils_Hook
::post(($op === 'add' ?
'create' : 'edit'), 'CustomField', $customField->id
, $customField);
94 CRM_Utils_System
::flushCache();
95 // Flush caches is not aggressive about clearing the specific cache we know we want to clear
96 // so do it manually. Ideally we wouldn't need to clear others...
97 Civi
::cache('metadata')->clear();
103 * Create/ update several fields at once in a mysql efficient way.
105 * https://lab.civicrm.org/dev/core/issues/1093
107 * The intention is that apiv4 would expose any BAO with bulkSave as a new action.
109 * @param array $bulkParams
110 * Array of arrays as would be passed into create
111 * @param array $defaults
112 * Default parameters to be be merged into each of the params.
114 * @throws \CiviCRM_API3_Exception
116 public static function bulkSave($bulkParams, $defaults = []) {
117 $addedColumns = $sql = $tables = $customFields = [];
118 foreach ($bulkParams as $index => $fieldParams) {
119 $params = array_merge($defaults, $fieldParams);
120 $customField = self
::createCustomFieldRecord($params);
121 $fieldSQL = self
::getAlterFieldSQL($customField, empty($params['id']) ?
'add' : 'modify');
122 if (!isset($params['custom_group_id'])) {
123 $params['custom_group_id'] = civicrm_api3('CustomField', 'getvalue', ['id' => $customField->id
, 'return' => 'custom_group_id']);
125 if (!isset($params['table_name'])) {
126 if (!isset($tables[$params['custom_group_id']])) {
127 $tables[$params['custom_group_id']] = civicrm_api3('CustomGroup', 'getvalue', [
128 'id' => $params['custom_group_id'],
129 'return' => 'table_name',
132 $params['table_name'] = $tables[$params['custom_group_id']];
134 $sql[$params['table_name']][] = $fieldSQL;
135 $addedColumns[$params['table_name']][] = $customField->name
;
136 $customFields[$index] = $customField;
139 foreach ($sql as $tableName => $statements) {
140 // CRM-7007: do not i18n-rewrite this query
141 CRM_Core_DAO
::executeQuery("ALTER TABLE $tableName " . implode(', ', $statements), [], TRUE, NULL, FALSE, FALSE);
143 if (CRM_Core_Config
::singleton()->logging
) {
144 $logging = new CRM_Logging_Schema();
145 $logging->fixSchemaDifferencesFor($tableName, ['ADD' => $addedColumns[$tableName]]);
148 Civi
::service('sql_triggers')->rebuild($params['table_name'], TRUE);
150 CRM_Utils_System
::flushCache();
151 foreach ($customFields as $index => $customField) {
152 CRM_Utils_Hook
::post(empty($bulkParams[$index]['id']) ?
'create' : 'edit', 'CustomField', $customField->id
, $customField);
157 * Fetch object based on array of properties.
159 * @param array $params
160 * (reference ) an assoc array of name/value pairs.
161 * @param array $defaults
162 * (reference ) an assoc array to hold the flattened values.
164 * @return CRM_Core_DAO_CustomField
166 public static function retrieve(&$params, &$defaults) {
167 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
171 * Update the is_active flag in the db.
174 * Id of the database record.
175 * @param bool $is_active
176 * Value we want to set the is_active field.
179 * true if we found and updated the object, else false
181 public static function setIsActive($id, $is_active) {
183 CRM_Utils_System
::flushCache();
185 //enable-disable CustomField
186 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
187 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
191 * Get the field title.
199 public static function getTitle($id) {
200 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
204 * @param string $context
207 public function getOptions($context = NULL) {
208 CRM_Core_DAO
::buildOptionsContext($context);
213 $cacheKey = "CRM_Core_BAO_CustomField_getOptions_{$this->id}_$context";
214 $cache = CRM_Utils_Cache
::singleton();
215 $options = $cache->get($cacheKey);
216 if (!isset($options)) {
217 if (!$this->data_type ||
!$this->custom_group_id
) {
221 // This will hold the list of options in format key => label
224 if (!empty($this->option_group_id
)) {
225 $options = CRM_Core_OptionGroup
::valuesByID(
226 $this->option_group_id
, FALSE, FALSE, FALSE, $context == 'validate' ?
'name' : 'label', !($context == 'validate' ||
$context == 'get')
229 elseif ($this->data_type
=== 'StateProvince') {
230 $options = CRM_Core_PseudoConstant
::stateProvince();
232 elseif ($this->data_type
=== 'Country') {
233 $options = $context == 'validate' ? CRM_Core_PseudoConstant
::countryIsoCode() : CRM_Core_PseudoConstant
::country();
235 elseif ($this->data_type
=== 'Boolean') {
236 $options = $context == 'validate' ?
[0, 1] : CRM_Core_SelectValues
::boolean();
238 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
239 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, ['context' => $context]);
240 $cache->set($cacheKey, $options);
246 * Store and return an array of all active custom fields.
248 * @param string $customDataType
249 * Type of Custom Data; 'ANY' is a synonym for "all contact data types".
250 * @param bool $showAll
251 * If true returns all fields (includes disabled fields).
252 * @param bool $inline
253 * If true returns all inline fields (includes disabled fields).
254 * @param int $customDataSubType
255 * Custom Data sub type value.
256 * @param int $customDataSubName
257 * Custom Data sub name value.
258 * @param bool $onlyParent
259 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
260 * @param bool $onlySubType
261 * Return only custom data for subtype.
262 * @param bool $checkPermission
263 * If false, do not include permissioning clause.
266 * an array of active custom fields.
268 public static function &getFields(
269 $customDataType = 'Individual',
272 $customDataSubType = NULL,
273 $customDataSubName = NULL,
275 $onlySubType = FALSE,
276 $checkPermission = TRUE
278 if (empty($customDataType)) {
279 $customDataType = ['Contact', 'Individual', 'Organization', 'Household'];
281 if ($customDataType === 'ANY') {
282 // NULL should have been respected but the line above broke that.
283 // boo for us not having enough unit tests back them.
284 $customDataType = NULL;
286 if ($customDataType && !is_array($customDataType)) {
288 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
289 // This is the case when getFieldsForImport() requires fields
290 // limited strictly to a subtype.
291 $customDataSubType = $customDataType;
292 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
296 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
297 // this makes the method flexible to support retrieving fields
298 // for multiple extends value.
299 $customDataType = [$customDataType];
303 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
305 if (is_array($customDataType)) {
306 $cacheKey = implode('_', $customDataType);
309 $cacheKey = $customDataType;
312 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
313 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
314 $cacheKey .= $showAll ?
'_1' : '_0';
315 $cacheKey .= $inline ?
'_1_' : '_0_';
316 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
317 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
318 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
319 $cacheKey .= '_' . CRM_Core_Config
::domainID() . '_';
321 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
323 // also get the permission stuff here
324 if ($checkPermission) {
325 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
330 $permissionClause = '(1)';
333 // lets md5 permission clause and take first 8 characters
334 $cacheKey .= substr(md5($permissionClause), 0, 8);
336 if (strlen($cacheKey) > 40) {
337 $cacheKey = md5($cacheKey);
340 if (!self
::$_importFields ||
341 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
343 if (!self
::$_importFields) {
344 self
::$_importFields = [];
347 // check if we can retrieve from database cache
348 $fields = Civi
::Cache('fields')->get("custom importableFields $cacheKey");
350 if ($fields === NULL) {
351 $cfTable = self
::getTableName();
354 if (is_array($customDataType)) {
356 foreach ($customDataType as $dataType) {
357 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
358 if (in_array($dataType, ['Individual', 'Household', 'Organization'])) {
359 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
362 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
364 $value = $value ?
$value . ", {$val}" : $val;
368 $extends = "AND $cgTable.extends IN ( $value ) ";
372 if (!empty($customDataType) && empty($extends)) {
373 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
374 self
::$_importFields[$cacheKey] = [];
375 return self
::$_importFields[$cacheKey];
379 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
382 $query = "SELECT $cfTable.id, $cfTable.label,
386 $cfTable.default_value,
387 $cfTable.options_per_line, $cfTable.text_length,
388 $cfTable.custom_group_id,
389 $cfTable.is_required,
390 $cfTable.column_name,
391 $cgTable.extends, $cfTable.is_search_range,
392 $cgTable.extends_entity_column_value,
393 $cgTable.extends_entity_column_id,
395 $cfTable.option_group_id,
396 $cfTable.date_format,
397 $cfTable.time_format,
398 $cgTable.is_multiple,
400 og.name as option_group_name
403 ON $cfTable.custom_group_id = $cgTable.id
404 LEFT JOIN civicrm_option_group og
405 ON $cfTable.option_group_id = og.id
409 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
413 $query .= " AND $cgTable.style = 'Inline' ";
416 //get the custom fields for specific type in
417 //combination with fields those support any type.
418 if (!empty($customDataSubType)) {
420 foreach ($customDataSubType as $subtype) {
421 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($subtype, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
;
422 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
425 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
427 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
430 if ($customDataSubName) {
431 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
434 // also get the permission stuff here
435 if ($checkPermission) {
436 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
441 $permissionClause = '(1)';
444 $query .= " $extends AND $permissionClause
445 ORDER BY $cgTable.weight, $cgTable.title,
446 $cfTable.weight, $cfTable.label";
448 $dao = CRM_Core_DAO
::executeQuery($query);
451 while (($dao->fetch()) != NULL) {
452 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
453 $fields[$dao->id
]['id'] = $dao->id
;
454 $fields[$dao->id
]['label'] = $dao->label
;
455 // This seems broken, but not in a new way.
456 $fields[$dao->id
]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
457 // To support the consolidation of various functions & their expectations.
458 $fields[$dao->id
]['title'] = $dao->label
;
459 $fields[$dao->id
]['custom_field_id'] = $dao->id
;
460 $fields[$dao->id
]['groupTitle'] = $dao->title
;
461 $fields[$dao->id
]['data_type'] = $dao->data_type
;
462 $fields[$dao->id
]['name'] = 'custom_' . $dao->id
;
463 $fields[$dao->id
]['type'] = CRM_Utils_Array
::value($dao->data_type
, self
::dataToType());
464 $fields[$dao->id
]['html_type'] = $dao->html_type
;
465 $fields[$dao->id
]['default_value'] = $dao->default_value
;
466 $fields[$dao->id
]['text_length'] = $dao->text_length
;
467 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
468 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
469 $fields[$dao->id
]['extends'] = $dao->extends;
470 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
471 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
472 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
473 $fields[$dao->id
]['is_view'] = $dao->is_view
;
474 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
475 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
476 $fields[$dao->id
]['date_format'] = $dao->date_format
;
477 $fields[$dao->id
]['time_format'] = $dao->time_format
;
478 $fields[$dao->id
]['is_required'] = $dao->is_required
;
479 $fields[$dao->id
]['table_name'] = $dao->table_name
;
480 $fields[$dao->id
]['column_name'] = $dao->column_name
;
481 $fields[$dao->id
]['where'] = $dao->table_name
. '.' . $dao->column_name
;
482 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
483 $fields[$dao->id
]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery
::$extendsMap) ? CRM_Core_BAO_CustomQuery
::$extendsMap[$dao->extends] : '';
484 if (in_array($dao->extends, CRM_Contact_BAO_ContactType
::subTypes())) {
485 // if $extends is a subtype, refer contact table
486 $fields[$dao->id
]['extends_table'] = 'civicrm_contact';
488 // Search table is used by query object searches..
489 $fields[$dao->id
]['search_table'] = ($fields[$dao->id
]['extends_table'] == 'civicrm_contact') ?
'contact_a' : $fields[$dao->id
]['extends_table'];
490 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
493 Civi
::cache('fields')->set("custom importableFields $cacheKey", $fields);
495 self
::$_importFields[$cacheKey] = $fields;
498 return self
::$_importFields[$cacheKey];
502 * Return the field ids and names (with groups) for import purpose.
504 * @param int|string $contactType Contact type
505 * @param bool $showAll
506 * If true returns all fields (includes disabled fields).
507 * @param bool $onlyParent
508 * Return fields ONLY related to basic types.
509 * @param bool $search
510 * When called from search and multiple records need to be returned.
511 * @param bool $checkPermission
512 * If false, do not include permissioning clause.
514 * @param bool $withMultiple
518 public static function getFieldsForImport(
519 $contactType = 'Individual',
523 $checkPermission = TRUE,
524 $withMultiple = FALSE
526 // Note: there are situations when we want getFieldsForImport() return fields related
527 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
528 $fields = &self
::getFields($contactType,
538 $importableFields = [];
539 foreach ($fields as $id => $values) {
540 // for now we should not allow multiple fields in profile / export etc, hence unsetting
542 (!empty($values['is_multiple']) && !$withMultiple)
546 if (!empty($values['text_length'])) {
547 $values['maxlength'] = (int) $values['text_length'];
550 /* generate the key for the fields array */
553 $importableFields[$key] = $values;
554 $importableFields[$key]['import'] = 1;
557 return $importableFields;
561 * Get the field id from an import key.
571 public static function getKeyID($key, $all = FALSE) {
573 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
580 CRM_Utils_Array
::value(2, $match),
584 return $all ?
[NULL, NULL] : NULL;
588 * Use the cache to get all values of a specific custom field.
590 * @param int $fieldID
591 * The custom field ID.
593 * @return CRM_Core_BAO_CustomField
596 public static function getFieldObject($fieldID) {
597 $field = new CRM_Core_BAO_CustomField();
599 // check if we can get the field values from the system cache
600 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
601 $cache = CRM_Utils_Cache
::singleton();
602 $fieldValues = $cache->get($cacheKey);
603 if (empty($fieldValues)) {
604 $field->id
= $fieldID;
605 if (!$field->find(TRUE)) {
606 CRM_Core_Error
::fatal();
610 CRM_Core_DAO
::storeValues($field, $fieldValues);
612 $cache->set($cacheKey, $fieldValues);
615 $field->copyValues($fieldValues);
622 * Add a custom field to an existing form.
624 * @param CRM_Core_Form $qf
625 * Form object (reference).
626 * @param string $elementName
627 * Name of the custom field.
628 * @param int $fieldId
629 * @param bool $useRequired
630 * True if required else false.
631 * @param bool $search
632 * True if used for search else false.
633 * @param string $label
634 * Label for custom field.
635 * @return \HTML_QuickForm_Element|null
636 * @throws \CiviCRM_API3_Exception
638 public static function addQuickFormElement(
639 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
641 $field = self
::getFieldObject($fieldId);
642 $widget = $field->html_type
;
644 $customFieldAttributes = [];
646 // Custom field HTML should indicate group+field name
647 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
648 $dataCrmCustomVal = $groupName . ':' . $field->name
;
649 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
650 $field->attributes
.= $dataCrmCustomAttr;
652 // Fixed for Issue CRM-2183
653 if ($widget == 'TextArea' && $search) {
657 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
659 // FIXME: Why are select state/country separate widget types?
660 $isSelect = (in_array($widget, [
663 'Select State/Province',
664 'Multi-Select State/Province',
666 'Multi-Select Country',
672 $options = $field->getOptions($search ?
'search' : 'create');
674 // Consolidate widget types to simplify the below switch statement
675 if ($search ||
(strpos($widget, 'Select') !== FALSE)) {
679 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
680 $selectAttributes = ['class' => 'crm-select2'];
682 // Search field is always multi-select
683 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
684 $selectAttributes['class'] .= ' huge';
685 $selectAttributes['multiple'] = 'multiple';
686 $selectAttributes['placeholder'] = $placeholder;
689 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
690 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
691 if ($field->option_group_id
&& !$search && $isSelect && $canEditOptions) {
692 $customFieldAttributes +
= [
693 'data-api-entity' => $field->getEntity(),
694 'data-api-field' => 'custom_' . $field->id
,
695 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
697 $selectAttributes +
= $customFieldAttributes;
701 $rangeDataTypes = ['Int', 'Float', 'Money'];
703 if (!isset($label)) {
704 $label = $field->label
;
707 // at some point in time we might want to split the below into small functions
712 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
713 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
714 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
717 if ($field->text_length
) {
718 $field->attributes
.= ' maxlength=' . $field->text_length
;
719 if ($field->text_length
< 20) {
720 $field->attributes
.= ' size=' . $field->text_length
;
723 $element = $qf->add('text', $elementName, $label,
725 $useRequired && !$search
731 $attributes = $dataCrmCustomAttr;
732 if ($field->note_rows
) {
733 $attributes .= 'rows=' . $field->note_rows
;
736 $attributes .= 'rows=4';
738 if ($field->note_columns
) {
739 $attributes .= ' cols=' . $field->note_columns
;
742 $attributes .= ' cols=60';
744 if ($field->text_length
) {
745 $attributes .= ' maxlength=' . $field->text_length
;
747 $element = $qf->add('textarea',
751 $useRequired && !$search
756 $attr = ['data-crm-custom' => $dataCrmCustomVal];
757 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
758 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
759 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
762 'date' => $field->date_format
,
763 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
764 //CRM-18487 - max date should be the last date of the year.
765 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
766 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
768 if ($field->is_search_range
&& $search) {
769 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
770 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
773 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
778 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
779 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
780 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
784 parse_str($field->attributes
, $radioAttributes);
785 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
787 foreach ($options as $v => $l) {
788 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
790 $element = $qf->addGroup($choice, $elementName, $label);
791 $optionEditKey = 'data-option-edit-path';
792 if (isset($selectAttributes[$optionEditKey])) {
793 $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
796 if ($useRequired && !$search) {
797 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
800 $element->setAttribute('allowClear', TRUE);
805 // For all select elements
807 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
808 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
809 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
812 if (empty($selectAttributes['multiple'])) {
813 $options = ['' => $placeholder] +
$options;
815 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
817 // Add and/or option for fields that store multiple values
818 if ($search && self
::isSerialized($field)) {
821 $qf->createElement('radio', NULL, '', ts('Any'), 'or', ['title' => ts('Results may contain any of the selected options')]),
822 $qf->createElement('radio', NULL, '', ts('All'), 'and', ['title' => ts('Results must have all of the selected options')]),
824 $qf->addGroup($operators, $elementName . '_operator');
825 $qf->setDefaults([$elementName . '_operator' => 'or']);
832 foreach ($options as $v => $l) {
833 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
836 $group = $element = $qf->addGroup($check, $elementName, $label);
837 $optionEditKey = 'data-option-edit-path';
838 if (isset($customFieldAttributes[$optionEditKey])) {
839 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
842 if ($useRequired && !$search) {
843 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
848 // we should not build upload file in search mode
853 strtolower($field->html_type
),
857 $useRequired && !$search
859 $qf->addUploadElement($elementName);
862 case 'RichTextEditor':
864 'rows' => $field->note_rows
,
865 'cols' => $field->note_columns
,
866 'data-crm-custom' => $dataCrmCustomVal,
868 if ($field->text_length
) {
869 $attributes['maxlength'] = $field->text_length
;
871 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
874 case 'Autocomplete-Select':
875 static $customUrls = [];
876 // Fixme: why is this a string in the first place??
877 $attributes = array();
878 if ($field->attributes
) {
879 foreach (explode(' ', $field->attributes
) as $at) {
880 if (strpos($at, '=')) {
881 list($k, $v) = explode('=', $at);
882 $attributes[$k] = trim($v, ' "');
886 if ($field->data_type
== 'ContactReference') {
887 // break if contact does not have permission to access ContactReference
888 if (!CRM_Core_Permission
::check('access contact reference fields')) {
891 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
892 $attributes['data-api-entity'] = 'Contact';
893 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
895 $urlParams = "context=customfield&id={$field->id}";
896 $idOfelement = $elementName;
897 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
898 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
899 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
900 // rather than layering on more hacks.
901 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
902 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') +
1)), 0, -1);
904 $customUrls[$idOfelement] = CRM_Utils_System
::url('civicrm/ajax/contactref',
911 // FIXME: This won't work with customFieldOptions hook
913 'entity' => 'OptionValue',
914 'placeholder' => $placeholder,
915 'multiple' => $search,
917 'params' => ['option_group_id' => $field->option_group_id
, 'is_active' => 1],
920 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
923 $qf->assign('customUrls', $customUrls);
927 switch ($field->data_type
) {
929 // integers will have numeric rule applied to them.
930 if ($field->is_search_range
&& $search) {
931 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', [1 => $label]), 'integer');
932 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', [1 => $label]), 'integer');
934 elseif ($widget == 'Text') {
935 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', [1 => $label]), 'integer');
940 if ($field->is_search_range
&& $search) {
941 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', [1 => $label]), 'numeric');
942 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', [1 => $label]), 'numeric');
944 elseif ($widget == 'Text') {
945 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', [1 => $label]), 'numeric');
950 if ($field->is_search_range
&& $search) {
951 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
952 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
954 elseif ($widget == 'Text') {
955 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
960 $element->setAttribute('class', "url");
961 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
964 if ($field->is_view
&& !$search) {
965 $qf->freeze($elementName);
971 * Delete the Custom Field.
973 * @param object $field
976 public static function deleteField($field) {
977 CRM_Utils_System
::flushCache();
979 // first delete the custom option group and values associated with this field
980 if ($field->option_group_id
) {
981 //check if option group is related to any other field, if
982 //not delete the option group and related option values
983 self
::checkOptionGroup($field->option_group_id
);
986 // next drop the column from the custom value table
987 self
::createField($field, 'delete');
990 CRM_Core_BAO_UFField
::delUFField($field->id
);
991 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
993 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
997 * @param string|int|array|null $value
998 * @param CRM_Core_BAO_CustomField|int|array|string $field
999 * @param int $entityId
1003 * @throws \CRM_Core_Exception
1005 public static function displayValue($value, $field, $entityId = NULL) {
1006 $field = is_array($field) ?
$field['id'] : $field;
1007 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1010 throw new CRM_Core_Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1013 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1014 $field = self
::getFieldObject($fieldId);
1017 $fieldInfo = ['options' => $field->getOptions()] +
(array) $field;
1019 $displayValue = self
::formatDisplayValue($value, $fieldInfo, $entityId);
1021 // Call hook to alter display value.
1022 CRM_Utils_Hook
::alterCustomFieldDisplayValue($displayValue, $value, $entityId, $fieldInfo);
1024 return $displayValue;
1028 * Lower-level logic for rendering a custom field value
1030 * @param string|array $value
1031 * @param array $field
1032 * @param int|null $entityId
1036 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1038 if (self
::isSerialized($field) && !is_array($value)) {
1039 $value = CRM_Utils_Array
::explodePadded($value);
1042 if ($field['html_type'] == 'CheckBox' && $value) {
1043 $value = CRM_Utils_Array
::convertCheckboxFormatToArray($value);
1046 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1048 switch ($field['html_type']) {
1051 case 'Autocomplete-Select':
1053 case 'Select Country':
1054 case 'Select State/Province':
1056 case 'Multi-Select':
1057 case 'Multi-Select State/Province':
1058 case 'Multi-Select Country':
1059 if ($field['data_type'] == 'ContactReference' && $value) {
1060 if (is_numeric($value)) {
1061 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1067 elseif (is_array($value)) {
1069 foreach ($value as $key => $val) {
1070 $v[] = $field['options'][$val] ??
NULL;
1072 $display = implode(', ', $v);
1075 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1080 $customFormat = NULL;
1082 // FIXME: Are there any legitimate reasons why $value would be an array?
1083 // Or should we throw an exception here if it is?
1084 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1086 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1087 $format = $field['date_format'] ??
NULL;
1090 if (array_key_exists($format, $actualPHPFormats)) {
1091 $customTimeFormat = (array) $actualPHPFormats[$format];
1092 switch (CRM_Utils_Array
::value('time_format', $field)) {
1094 $customTimeFormat[] = 'g:iA';
1098 $customTimeFormat[] = 'G:i';
1102 //If time is not selected remove time from value.
1103 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1105 $customFormat = implode(" ", $customTimeFormat);
1108 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1112 // In the context of displaying a profile, show file/image
1115 if (CRM_Utils_Rule
::positiveInteger($value)) {
1119 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1121 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1123 $display = $url['file_url'];
1127 // In other contexts show a paperclip icon
1128 if (CRM_Utils_Rule
::integer($value)) {
1129 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1131 $file_description = '';
1133 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1135 catch (CiviCRM_API3_Exception
$dontcare) {
1139 $display = "{$icons[$value]}{$file_description}";
1142 //CRM-18396, if filename is passed instead
1150 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1154 $display = nl2br($display);
1158 if ($field['data_type'] == 'Money' && isset($value)) {
1159 // $value can also be an array(while using IN operator from search builder or api).
1160 foreach ((array) $value as $val) {
1161 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1163 $display = implode(', ', $disp);
1171 * Set default values for custom data used in profile.
1173 * @param int $customFieldId
1175 * @param string $elementName
1176 * Custom field name.
1177 * @param array $defaults
1178 * Associated array of fields.
1179 * @param int $contactId
1183 * @param mixed $value
1184 * If passed - dont fetch value from db,.
1185 * just format the given value
1187 public static function setProfileDefaults(
1195 //get the type of custom field
1196 $customField = new CRM_Core_BAO_CustomField();
1197 $customField->id
= $customFieldId;
1198 $customField->find(TRUE);
1201 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1202 $value = $customField->default_value
;
1206 if (!isset($value)) {
1207 $info = self
::getTableColumnGroup($customFieldId);
1208 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1209 $result = CRM_Core_DAO
::executeQuery($query);
1210 if ($result->fetch()) {
1211 $value = $result->value
;
1215 if ($customField->data_type
== 'Country') {
1217 $config = CRM_Core_Config
::singleton();
1218 if ($config->defaultContactCountry
) {
1219 $value = CRM_Core_BAO_Country
::defaultContactCountry();
1225 //set defaults if mode is registration
1226 if (!trim($value) &&
1228 (!in_array($mode, [CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
]))
1230 $value = $customField->default_value
;
1233 if ($customField->data_type
== 'Money' && isset($value)) {
1234 $value = number_format($value, 2);
1236 if (self
::isSerialized($customField)) {
1237 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1238 $defaults[$elementName] = [];
1239 $checkedValue = CRM_Utils_Array
::explodePadded($value);
1240 foreach ($customOption as $val) {
1241 if (in_array($val['value'], $checkedValue)) {
1242 if ($customField->html_type
== 'CheckBox') {
1243 $defaults[$elementName][$val['value']] = 1;
1246 $defaults[$elementName][$val['value']] = $val['value'];
1252 $defaults[$elementName] = $value;
1259 * @param int $contactID
1261 * @param int $fileID
1262 * @param bool $absolute
1264 * @param string $multiRecordWhereClause
1268 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1271 $params = ['id' => $cfID];
1273 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1274 $columnName = $defaults['column_name'];
1276 //table name of custom data
1277 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1278 $defaults['custom_group_id'],
1282 //query to fetch id from civicrm_file
1283 if ($multiRecordWhereClause) {
1284 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1287 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1289 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1294 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1299 $result['file_id'] = $fileID;
1301 if ($fileType == 'image/jpeg' ||
1302 $fileType == 'image/pjpeg' ||
1303 $fileType == 'image/gif' ||
1304 $fileType == 'image/x-png' ||
1305 $fileType == 'image/png'
1307 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1312 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1313 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1314 $url = CRM_Utils_System
::url('civicrm/file',
1315 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1316 $absolute, NULL, TRUE, TRUE
1318 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1320 // for non image files
1322 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1326 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1327 $url = CRM_Utils_System
::url('civicrm/file',
1328 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1329 $absolute, NULL, TRUE, TRUE
1331 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1339 * Format custom fields before inserting.
1341 * @param int $customFieldId
1343 * @param array $customFormatted
1345 * @param mixed $value
1346 * Value of custom field.
1347 * @param string $customFieldExtend
1348 * Custom field extends.
1349 * @param int $customValueId
1350 * Custom option value id.
1351 * @param int $entityId
1352 * Entity id (contribution, membership...).
1353 * @param bool $inline
1354 * Consider inline custom groups only.
1355 * @param bool $checkPermission
1356 * If false, do not include permissioning clause.
1357 * @param bool $includeViewOnly
1358 * If true, fields marked 'View Only' are included. Required for APIv3.
1360 * @return array|NULL
1361 * formatted custom field array
1363 public static function formatCustomField(
1364 $customFieldId, &$customFormatted, $value,
1365 $customFieldExtend, $customValueId = NULL,
1368 $checkPermission = TRUE,
1369 $includeViewOnly = FALSE
1371 //get the custom fields for the entity
1372 //subtype and basic type
1373 $customDataSubType = NULL;
1374 if ($customFieldExtend) {
1375 // This is the case when getFieldsForImport() requires fields
1376 // of subtype and its parent.CRM-5143
1377 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1378 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1379 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1380 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1381 if (is_array($customFieldExtend)) {
1382 $customFieldExtend = array_unique(array_values($customFieldExtend));
1387 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1397 if (!array_key_exists($customFieldId, $customFields)) {
1401 // return if field is a 'code' field
1402 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1406 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1408 if (!$customValueId &&
1409 // we always create new entites for is_multiple unless specified
1410 !$customFields[$customFieldId]['is_multiple'] &&
1416 WHERE entity_id={$entityId}";
1418 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1421 //fix checkbox, now check box always submits values
1422 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1424 // Note that only during merge this is not an array, and you can directly use value
1425 if (is_array($value)) {
1426 $selectedValues = [];
1427 foreach ($value as $selId => $val) {
1429 $selectedValues[] = $selId;
1432 if (!empty($selectedValues)) {
1433 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1435 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1443 elseif (self
::isSerialized($customFields[$customFieldId])) {
1444 $value = $value ? CRM_Utils_Array
::implodePadded($value) : '';
1447 if (self
::isSerialized($customFields[$customFieldId]) &&
1448 $customFields[$customFieldId]['data_type'] == 'String' &&
1449 !empty($customFields[$customFieldId]['text_length']) &&
1452 // lets make sure that value is less than the length, else we'll
1453 // be losing some data, CRM-7481
1454 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1455 // need to do a few things here
1457 // 1. lets find a new length
1458 $newLength = $customFields[$customFieldId]['text_length'];
1459 $minLength = strlen($value);
1460 while ($newLength < $minLength) {
1461 $newLength = $newLength * 2;
1464 // set the custom field meta data to have a length larger than value
1465 // alter the custom value table column to match this length
1466 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1471 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1472 if (!CRM_Utils_System
::isNull($value)) {
1473 $format = $customFields[$customFieldId]['date_format'];
1474 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1479 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1480 $customFields[$customFieldId]['data_type'] == 'Money'
1486 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1487 $value = CRM_Utils_Rule
::cleanMoney($value);
1491 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1492 $customFields[$customFieldId]['data_type'] == 'Country'
1502 if ($customFields[$customFieldId]['data_type'] == 'File') {
1503 if (empty($value)) {
1507 $config = CRM_Core_Config
::singleton();
1509 // If we are already passing the file id as a value then retrieve and set the file data
1510 if (CRM_Utils_Rule
::integer($value)) {
1511 $fileDAO = new CRM_Core_DAO_File();
1512 $fileDAO->id
= $value;
1513 $fileDAO->find(TRUE);
1516 $fName = $fileDAO->uri
;
1517 $mimeType = $fileDAO->mime_type
;
1521 $fName = $value['name'];
1522 $mimeType = $value['type'];
1525 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1527 // rename this file to go into the secure directory only if
1528 // user has uploaded new file not existing verfied on the basis of $fileID
1529 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1530 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1533 if ($customValueId && empty($fileID)) {
1538 $params = [1 => [$customValueId, 'Integer']];
1539 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1542 $fileDAO = new CRM_Core_DAO_File();
1545 $fileDAO->id
= $fileID;
1548 $fileDAO->uri
= $filename;
1549 $fileDAO->mime_type
= $mimeType;
1550 $fileDAO->upload_date
= date('YmdHis');
1552 $fileID = $fileDAO->id
;
1556 if (!is_array($customFormatted)) {
1557 $customFormatted = [];
1560 if (!array_key_exists($customFieldId, $customFormatted)) {
1561 $customFormatted[$customFieldId] = [];
1565 if ($customValueId) {
1566 $index = $customValueId;
1569 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1570 $customFormatted[$customFieldId][$index] = [];
1572 $customFormatted[$customFieldId][$index] = [
1573 'id' => $customValueId > 0 ?
$customValueId : NULL,
1575 'type' => $customFields[$customFieldId]['data_type'],
1576 'custom_field_id' => $customFieldId,
1577 'custom_group_id' => $groupID,
1578 'table_name' => $tableName,
1579 'column_name' => $columnName,
1580 'file_id' => $fileID,
1581 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1584 //we need to sort so that custom fields are created in the order of entry
1585 krsort($customFormatted[$customFieldId]);
1586 return $customFormatted;
1590 * Get default custom table schema.
1592 * @param array $params
1596 public static function defaultCustomTableSchema($params) {
1597 // add the id and extends_id
1599 'name' => $params['name'],
1600 'is_multiple' => $params['is_multiple'],
1601 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1605 'type' => 'int unsigned',
1608 'attributes' => 'AUTO_INCREMENT',
1609 'comment' => 'Default MySQL primary key',
1612 'name' => 'entity_id',
1613 'type' => 'int unsigned',
1615 'comment' => 'Table that this extends',
1616 'fk_table_name' => $params['extends_name'],
1617 'fk_field_name' => 'id',
1618 'fk_attributes' => 'ON DELETE CASCADE',
1623 if (!$params['is_multiple']) {
1624 $table['indexes'] = [
1627 'field_name_1' => 'entity_id',
1635 * Create custom field.
1637 * @param CRM_Core_DAO_CustomField $field
1638 * @param string $operation
1640 public static function createField($field, $operation) {
1641 $sql = str_repeat(' ', 8);
1642 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1643 $sql .= "ALTER TABLE " . $tableName;
1644 $sql .= self
::getAlterFieldSQL($field, $operation);
1646 // CRM-7007: do not i18n-rewrite this query
1647 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1649 $config = CRM_Core_Config
::singleton();
1650 if ($config->logging
) {
1651 // CRM-16717 not sure why this was originally limited to add.
1652 // For example custom tables can have field length changes - which need to flow through to logging.
1653 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1654 if ($operation === 'add' ||
$operation === 'modify') {
1655 $logging = new CRM_Logging_Schema();
1656 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name
]]);
1660 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
1664 * @param CRM_Core_DAO_CustomField $field
1665 * @param string $operation
1669 public static function getAlterFieldSQL($field, $operation) {
1670 $indexExist = $operation === 'add' ?
FALSE : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $field->id
, 'is_searchable');
1671 $params = self
::prepareCreateParams($field, $operation);
1672 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1673 // a function only used by Custom Field creation...
1674 $params['required'] = FALSE;
1675 return CRM_Core_BAO_SchemaHandler
::getFieldAlterSQL($params, $indexExist);
1679 * Determine whether it would be safe to move a field.
1681 * @param int $fieldID
1682 * FK to civicrm_custom_field.
1683 * @param int $newGroupID
1684 * FK to civicrm_custom_group.
1687 * array(string) or TRUE
1689 public static function _moveFieldValidate($fieldID, $newGroupID) {
1692 $field = new CRM_Core_DAO_CustomField();
1693 $field->id
= $fieldID;
1694 if (!$field->find(TRUE)) {
1695 $errors['fieldID'] = 'Invalid ID for custom field';
1699 $oldGroup = new CRM_Core_DAO_CustomGroup();
1700 $oldGroup->id
= $field->custom_group_id
;
1701 if (!$oldGroup->find(TRUE)) {
1702 $errors['fieldID'] = 'Invalid ID for old custom group';
1706 $newGroup = new CRM_Core_DAO_CustomGroup();
1707 $newGroup->id
= $newGroupID;
1708 if (!$newGroup->find(TRUE)) {
1709 $errors['newGroupID'] = 'Invalid ID for new custom group';
1715 FROM civicrm_custom_field a
1716 INNER JOIN civicrm_custom_field b
1718 AND a.label = b.label
1719 AND b.custom_group_id = %2
1722 1 => [$field->id
, 'Integer'],
1723 2 => [$newGroup->id
, 'Integer'],
1725 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1727 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1730 $tableName = $oldGroup->table_name
;
1731 $columnName = $field->column_name
;
1736 WHERE $columnName is not null
1738 $count = CRM_Core_DAO
::singleValueQuery($query);
1742 FROM civicrm_custom_group
1743 WHERE id IN ( %1, %2 )
1746 1 => [$oldGroup->id
, 'Integer'],
1747 2 => [$newGroup->id
, 'Integer'],
1750 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1752 while ($dao->fetch()) {
1753 $extends[] = $dao->extends;
1755 if ($extends[0] != $extends[1]) {
1756 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1760 return empty($errors) ?
TRUE : $errors;
1764 * Move a custom data field from one group (table) to another.
1766 * @param int $fieldID
1767 * FK to civicrm_custom_field.
1768 * @param int $newGroupID
1769 * FK to civicrm_custom_group.
1771 public static function moveField($fieldID, $newGroupID) {
1772 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1773 if (TRUE !== $validation) {
1774 CRM_Core_Error
::fatal(implode(' ', $validation));
1776 $field = new CRM_Core_DAO_CustomField();
1777 $field->id
= $fieldID;
1780 $newGroup = new CRM_Core_DAO_CustomGroup();
1781 $newGroup->id
= $newGroupID;
1782 $newGroup->find(TRUE);
1784 $oldGroup = new CRM_Core_DAO_CustomGroup();
1785 $oldGroup->id
= $field->custom_group_id
;
1786 $oldGroup->find(TRUE);
1789 $add->custom_group_id
= $newGroup->id
;
1790 self
::createField($add, 'add');
1792 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1793 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1794 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1796 CRM_Core_DAO
::executeQuery($sql);
1799 $del->custom_group_id
= $oldGroup->id
;
1800 self
::createField($del, 'delete');
1804 CRM_Utils_System
::flushCache();
1808 * Create an option value for a custom field option group ID.
1810 * @param array $params
1811 * @param string $value
1812 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1813 * @param string $index
1814 * @param string $dataType
1816 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $index, $dataType) {
1817 if (strlen(trim($value))) {
1818 $optionValue = new CRM_Core_DAO_OptionValue();
1819 $optionValue->option_group_id
= $optionGroup->id
;
1820 $optionValue->label
= $params['option_label'][$index];
1821 $optionValue->name
= $params['option_name'][$index] ?? CRM_Utils_String
::titleToVar($params['option_label'][$index]);
1822 switch ($dataType) {
1824 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1828 $optionValue->value
= intval($value);
1832 $optionValue->value
= floatval($value);
1836 $optionValue->value
= trim($value);
1839 $optionValue->weight
= $params['option_weight'][$index];
1840 $optionValue->is_active
= $params['option_status'][$index] ??
FALSE;
1841 $optionValue->description
= $params['option_description'][$index] ??
NULL;
1842 $optionValue->color
= $params['option_color'][$index] ??
NULL;
1843 $optionValue->icon
= $params['option_icon'][$index] ??
NULL;
1844 $optionValue->save();
1849 * Prepare for the create operation.
1851 * Munge params, create the option values if needed.
1853 * This could be called by a single create or a batchCreate.
1855 * @param array $params
1859 protected static function prepareCreate($params) {
1860 $op = empty($params['id']) ?
'create' : 'edit';
1861 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1862 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1863 if ($op === 'create') {
1864 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1865 if (!isset($params['column_name'])) {
1866 // if add mode & column_name not present, calculate it.
1867 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1869 if (!isset($params['name'])) {
1870 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1874 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'column_name');
1877 $htmlType = $params['html_type'] ??
NULL;
1878 $dataType = $params['data_type'] ??
NULL;
1880 if ($htmlType === 'Select Date' && empty($params['date_format'])) {
1881 $params['date_format'] = Civi
::settings()->get('dateInputFormat');
1884 if ($htmlType === 'CheckBox' ||
$htmlType === 'Multi-Select') {
1885 if (isset($params['default_checkbox_option'])) {
1887 foreach (array_keys($params['default_checkbox_option']) as $k => $v) {
1888 if ($params['option_value'][$v]) {
1889 $defaultArray[] = $params['option_value'][$v];
1893 if (!empty($defaultArray)) {
1894 // also add the separator before and after the value per new convention (CRM-1604)
1895 $params['default_value'] = CRM_Utils_Array
::implodePadded($defaultArray);
1899 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])) {
1900 $params['default_value'] = $params['option_value'][$params['default_option']];
1905 // create any option group & values if required
1906 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1907 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)) {
1908 //CRM-16659: if option_value then create an option group for this custom field.
1909 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
1910 // first create an option group for this custom group
1911 $optionGroup = new CRM_Core_DAO_OptionGroup();
1912 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
1913 $optionGroup->title
= $params['label'];
1914 $optionGroup->is_active
= 1;
1915 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1916 $optionGroup->is_reserved
= 0;
1917 $optionGroup->data_type
= $dataType;
1918 $optionGroup->save();
1919 $params['option_group_id'] = $optionGroup->id
;
1920 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1921 foreach ($params['option_value'] as $k => $v) {
1922 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1928 // check for orphan option groups
1929 if (!empty($params['option_group_id'])) {
1930 if (!empty($params['id'])) {
1931 self
::fixOptionGroups($params['id'], $params['option_group_id']);
1934 // if we do not have a default value
1935 // retrieve it from one of the other custom fields which use this option group
1936 if (empty($params['default_value'])) {
1937 //don't insert only value separator as default value, CRM-4579
1938 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'], $htmlType);
1940 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultValue))) {
1941 $params['default_value'] = $defaultValue;
1946 // Set default textarea attributes
1947 if ($op == 'create' && !isset($params['attributes']) && $htmlType == 'TextArea') {
1948 $params['attributes'] = 'rows=4, cols=60';
1954 * Create database entry for custom field and related option groups.
1956 * @param array $params
1958 * @return CRM_Core_DAO_CustomField
1960 protected static function createCustomFieldRecord($params) {
1961 $transaction = new CRM_Core_Transaction();
1962 $params = self
::prepareCreate($params);
1964 $customField = new CRM_Core_DAO_CustomField();
1965 $customField->copyValues($params);
1966 $customField->save();
1968 //create/drop the index when we toggle the is_searchable flag
1969 $op = empty($params['id']) ?
'add' : 'modify';
1970 if ($op !== 'modify') {
1971 if ($params['is_append_field_id_to_column_name']) {
1972 $params['column_name'] .= "_{$customField->id}";
1974 $customField->column_name
= $params['column_name'];
1975 $customField->save();
1978 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
1979 $transaction->commit();
1981 // make sure all values are present in the object for further processing
1982 $customField->find(TRUE);
1983 return $customField;
1987 * Move custom data from one contact to another.
1989 * This is currently the start of a refactoring. The theory is each
1990 * entity could have a 'move' function with a DAO default one to fall back on.
1992 * At the moment this only does a small part of the process - ie deleting a file field that
1993 * is about to be overwritten. However, the goal is the whole process around the move for
1994 * custom data should be in here.
1996 * This is currently called by the merge class but it makes sense that api could
1997 * expose move actions as moving (e.g) contributions feels like a common
1998 * ask that should be handled by the form layer.
2000 * @param int $oldContactID
2001 * @param int $newContactID
2002 * @param int[] $fieldIDs
2003 * Optional list field ids to move.
2005 * @throws \CiviCRM_API3_Exception
2006 * @throws \Exception
2008 public function move($oldContactID, $newContactID, $fieldIDs) {
2009 if (empty($fieldIDs)) {
2012 $fields = civicrm_api3('CustomField', 'get', ['id' => ['IN' => $fieldIDs], 'return' => ['custom_group_id.is_multiple', 'custom_group_id.table_name', 'column_name', 'data_type'], 'options' => ['limit' => 0]])['values'];
2014 foreach ($fieldIDs as $fieldID) {
2015 $return[] = 'custom_' . $fieldID;
2017 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2018 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2020 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2021 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2022 $fieldTypesNotHandledInMergeAttempt = ['File'];
2023 foreach ($fields as $field) {
2024 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2025 if ($field['data_type'] === 'File' && !$isMultiple) {
2026 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2027 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2029 if (!empty($oldContact['custom_' . $field['id']])) {
2030 CRM_Core_DAO
::executeQuery("
2031 UPDATE civicrm_entity_file
2032 SET entity_id = $newContactID
2033 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2037 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2038 CRM_Core_DAO
::executeQuery(
2039 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2040 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2041 ON DUPLICATE KEY UPDATE
2042 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2049 * Get the database table name and column name for a custom field.
2051 * @param int $fieldID
2052 * The fieldID of the custom field.
2053 * @param bool $force
2054 * Force the sql to be run again (primarily used for tests).
2057 * fatal is fieldID does not exists, else array of tableName, columnName
2058 * @throws \Exception
2060 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2061 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2062 $cache = CRM_Utils_Cache
::singleton();
2063 $fieldValues = $cache->get($cacheKey);
2064 if (empty($fieldValues) ||
$force) {
2066 SELECT cg.table_name, cf.column_name, cg.id
2067 FROM civicrm_custom_group cg,
2068 civicrm_custom_field cf
2069 WHERE cf.custom_group_id = cg.id
2071 $params = [1 => [$fieldID, 'Integer']];
2072 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2074 if (!$dao->fetch()) {
2075 CRM_Core_Error
::fatal();
2077 $fieldValues = [$dao->table_name
, $dao->column_name
, $dao->id
];
2078 $cache->set($cacheKey, $fieldValues);
2080 return $fieldValues;
2084 * Get custom option groups.
2086 * @deprecated Use the API OptionGroup.get
2088 * @param array $includeFieldIds
2089 * Ids of custom fields for which option groups must be included.
2091 * Currently this is required in the cases where option groups are to be included
2092 * for inactive fields : CRM-5369
2096 public static function customOptionGroup($includeFieldIds = NULL) {
2097 static $customOptionGroup = NULL;
2099 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2100 if ($cacheKey == 'force') {
2101 $customOptionGroup[$cacheKey] = NULL;
2104 if (empty($customOptionGroup[$cacheKey])) {
2105 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2107 //support for single as well as array format.
2108 if (!empty($includeFieldIds)) {
2109 if (is_array($includeFieldIds)) {
2110 $includeFieldIds = implode(',', $includeFieldIds);
2112 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2116 SELECT g.id, g.title
2117 FROM civicrm_option_group g
2118 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2119 WHERE {$whereClause}";
2121 $dao = CRM_Core_DAO
::executeQuery($query);
2122 while ($dao->fetch()) {
2123 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2127 return $customOptionGroup[$cacheKey];
2131 * Get defaults for new entity.
2135 public static function getDefaults() {
2137 'is_required' => FALSE,
2138 'is_searchable' => FALSE,
2139 'in_selector' => FALSE,
2140 'is_search_range' => FALSE,
2141 //CRM-15792 - Custom field gets disabled if is_active not set
2142 // this would ideally be a mysql default.
2143 'is_active' => TRUE,
2149 * Fix orphan groups.
2151 * @param int $customFieldId
2153 * @param int $optionGroupId
2156 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2157 // check if option group belongs to any custom Field else delete
2158 // get the current option group
2159 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2163 // get the updated option group
2164 // if both are same return
2165 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2169 // check if option group is related to any other field
2170 self
::checkOptionGroup($currentOptionGroupId);
2174 * Check if option group is related to more than one custom field.
2176 * @param int $optionGroupId
2179 public static function checkOptionGroup($optionGroupId) {
2182 FROM civicrm_custom_field
2183 WHERE option_group_id = {$optionGroupId}";
2185 $count = CRM_Core_DAO
::singleValueQuery($query);
2188 //delete the option group
2189 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2194 * Get option group default.
2196 * @param int $optionGroupId
2197 * @param string $htmlType
2199 * @return null|string
2201 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2203 SELECT default_value, html_type
2204 FROM civicrm_custom_field
2205 WHERE option_group_id = {$optionGroupId}
2206 AND default_value IS NOT NULL
2207 ORDER BY html_type";
2209 $dao = CRM_Core_DAO
::executeQuery($query);
2210 $defaultValue = NULL;
2211 $defaultHTMLType = NULL;
2212 while ($dao->fetch()) {
2213 if ($dao->html_type
== $htmlType) {
2214 return $dao->default_value
;
2216 if ($defaultValue == NULL) {
2217 $defaultValue = $dao->default_value
;
2218 $defaultHTMLType = $dao->html_type
;
2222 // some conversions are needed if either the old or new has a html type which has potential
2223 // multiple default values.
2224 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2225 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2227 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2229 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2230 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2232 $defaultValue = substr($defaultValue, 1, -1);
2233 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2234 substr($defaultValue, 1, -1)
2236 $defaultValue = $values[0];
2239 return $defaultValue;
2243 * Post process function.
2245 * @param array $params
2246 * @param int $entityID
2247 * @param string $customFieldExtends
2248 * @param bool $inline
2249 * @param bool $checkPermissions
2253 public static function postProcess(
2256 $customFieldExtends,
2258 $checkPermissions = TRUE
2262 foreach ($params as $key => $value) {
2263 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2265 // for autocomplete transfer hidden value instead of label
2266 if ($params[$key] && isset($params[$key . '_id'])) {
2267 $value = $params[$key . '_id'];
2270 // we need to append time with date
2271 if ($params[$key] && isset($params[$key . '_time'])) {
2272 $value .= ' ' . $params[$key . '_time'];
2275 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2278 $customFieldExtends,
2279 $customFieldInfo[1],
2290 * Get custom field ID from field/group name/title.
2292 * @param string $fieldName Field name or label
2293 * @param string|null $groupName (Optional) Group name or label
2294 * @param bool $fullString Whether to return "custom_123" or "123"
2296 * @return string|int|null
2297 * @throws \CiviCRM_API3_Exception
2299 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2300 $cacheKey = $groupName . '.' . $fieldName;
2301 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2302 $customFieldParams = [
2303 'name' => $fieldName,
2304 'label' => $fieldName,
2305 'options' => ['or' => [["name", "label"]]],
2309 $customFieldParams['custom_group_id.name'] = $groupName;
2310 $customFieldParams['custom_group_id.title'] = $groupName;
2311 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2314 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2316 if (empty($field['id'])) {
2317 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2318 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2321 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2322 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2327 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2329 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2333 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2339 public static function getNameFromID($ids) {
2340 if (is_array($ids)) {
2341 $ids = implode(',', $ids);
2344 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2345 FROM civicrm_custom_field f
2346 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2347 WHERE f.id IN ($ids)";
2349 $dao = CRM_Core_DAO
::executeQuery($sql);
2351 while ($dao->fetch()) {
2352 $result[$dao->id
] = [
2353 'field_name' => $dao->field_name
,
2354 'field_label' => $dao->field_label
,
2355 'group_name' => $dao->group_name
,
2356 'group_title' => $dao->group_title
,
2363 * Validate custom data.
2365 * @param array $params
2366 * Custom data submitted.
2367 * ie array( 'custom_1' => 'validate me' );
2370 * validation errors.
2372 public static function validateCustomData($params) {
2374 if (!is_array($params) ||
empty($params)) {
2378 //pick up profile fields.
2379 $profileFields = [];
2380 $ufGroupId = $params['ufGroupId'] ??
NULL;
2382 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2384 CRM_Core_Action
::VIEW
2388 //lets start w/ params.
2389 foreach ($params as $key => $value) {
2390 $customFieldID = self
::getKeyID($key);
2391 if (!$customFieldID) {
2395 //load the structural info for given field.
2396 $field = new CRM_Core_DAO_CustomField();
2397 $field->id
= $customFieldID;
2398 if (!$field->find(TRUE)) {
2401 $dataType = $field->data_type
;
2403 $profileField = CRM_Utils_Array
::value($key, $profileFields, []);
2404 $fieldTitle = $profileField['title'] ??
NULL;
2405 $isRequired = $profileField['is_required'] ??
NULL;
2407 $fieldTitle = $field->label
;
2410 //no need to validate.
2411 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2415 //lets validate first for required field.
2416 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2417 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
2421 //now time to take care of custom field form rules.
2422 $ruleName = $errorMsg = NULL;
2423 switch ($dataType) {
2425 $ruleName = 'integer';
2426 $errorMsg = ts('%1 must be an integer (whole number).',
2427 array(1 => $fieldTitle)
2432 $ruleName = 'money';
2433 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2434 array(1 => $fieldTitle)
2439 $ruleName = 'numeric';
2440 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2441 array(1 => $fieldTitle)
2446 $ruleName = 'wikiURL';
2447 $errorMsg = ts('%1 must be valid Website.',
2448 array(1 => $fieldTitle)
2453 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2455 $funName = "CRM_Utils_Rule::{$ruleName}";
2456 if (is_callable($funName)) {
2457 $valid = call_user_func($funName, $value);
2460 $errors[$key] = $errorMsg;
2469 * Is this field a multi record field.
2471 * @param int $customId
2475 public static function isMultiRecordField($customId) {
2476 $isMultipleWithGid = FALSE;
2477 if (!is_numeric($customId)) {
2478 $customId = self
::getKeyID($customId);
2480 if (is_numeric($customId)) {
2481 $sql = "SELECT cg.id cgId
2482 FROM civicrm_custom_group cg
2483 INNER JOIN civicrm_custom_field cf
2484 ON cg.id = cf.custom_group_id
2485 WHERE cf.id = %1 AND cg.is_multiple = 1";
2486 $params[1] = [$customId, 'Integer'];
2487 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2488 if ($dao->fetch()) {
2490 $isMultipleWithGid = $dao->cgId
;
2495 return $isMultipleWithGid;
2499 * Does this field type have any select options?
2501 * @param array $field
2505 public static function hasOptions($field) {
2506 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2507 $field = (array) $field;
2508 // This will include boolean fields with Yes/No options.
2509 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2512 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2513 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2514 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2517 if (strpos($field['html_type'], 'Select') !== FALSE) {
2520 return !empty($field['option_group_id']);
2524 * Does this field store a serialized string?
2526 * @param array|object $field
2530 public static function isSerialized($field) {
2531 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2532 $html_type = is_object($field) ?
$field->html_type
: $field['html_type'];
2533 // FIXME: Currently the only way to know if data is serialized is by looking at the html_type. It would be cleaner to decouple this.
2534 return ($html_type === 'CheckBox' ||
strpos($html_type, 'Multi') !== FALSE);
2538 * Get api entity for this field
2542 public function getEntity() {
2543 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2544 return in_array($entity, ['Individual', 'Household', 'Organization']) ?
'Contact' : $entity;
2548 * Set pseudoconstant properties for field metadata.
2550 * @param array $field
2551 * @param string|null $optionGroupName
2553 private static function getOptionsForField(&$field, $optionGroupName) {
2554 if ($optionGroupName) {
2555 $field['pseudoconstant'] = [
2556 'optionGroupName' => $optionGroupName,
2557 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2560 elseif ($field['data_type'] == 'Boolean') {
2561 $field['pseudoconstant'] = [
2562 'callback' => 'CRM_Core_SelectValues::boolean',
2565 elseif ($field['data_type'] == 'Country') {
2566 $field['pseudoconstant'] = [
2567 'table' => 'civicrm_country',
2568 'keyColumn' => 'id',
2569 'labelColumn' => 'name',
2570 'nameColumn' => 'iso_code',
2573 elseif ($field['data_type'] == 'StateProvince') {
2574 $field['pseudoconstant'] = [
2575 'table' => 'civicrm_state_province',
2576 'keyColumn' => 'id',
2577 'labelColumn' => 'name',
2583 * @param CRM_Core_DAO_CustomField $field
2584 * @param 'add|modify' $operation
2588 protected static function prepareCreateParams($field, $operation) {
2589 $tableName = CRM_Core_DAO
::getFieldValue(
2590 'CRM_Core_DAO_CustomGroup',
2591 $field->custom_group_id
,
2596 'table_name' => $tableName,
2597 'operation' => $operation,
2598 'name' => $field->column_name
,
2599 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2603 'required' => $field->is_required
,
2604 'searchable' => $field->is_searchable
,
2607 if ($operation == 'delete') {
2608 $fkName = "{$tableName}_{$field->column_name}";
2609 if (strlen($fkName) >= 48) {
2610 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2612 $params['fkName'] = $fkName;
2614 if ($field->data_type
== 'Country' && !self
::isSerialized($field)) {
2615 $params['fk_table_name'] = 'civicrm_country';
2616 $params['fk_field_name'] = 'id';
2617 $params['fk_attributes'] = 'ON DELETE SET NULL';
2619 elseif ($field->data_type
== 'StateProvince' && !self
::isSerialized($field)) {
2620 $params['fk_table_name'] = 'civicrm_state_province';
2621 $params['fk_field_name'] = 'id';
2622 $params['fk_attributes'] = 'ON DELETE SET NULL';
2624 elseif ($field->data_type
== 'StateProvince' ||
$field->data_type
== 'Country') {
2625 $params['type'] = 'varchar(255)';
2627 elseif ($field->data_type
== 'File') {
2628 $params['fk_table_name'] = 'civicrm_file';
2629 $params['fk_field_name'] = 'id';
2630 $params['fk_attributes'] = 'ON DELETE SET NULL';
2632 elseif ($field->data_type
== 'ContactReference') {
2633 $params['fk_table_name'] = 'civicrm_contact';
2634 $params['fk_field_name'] = 'id';
2635 $params['fk_attributes'] = 'ON DELETE SET NULL';
2637 if (isset($field->default_value
)) {
2638 $params['default'] = "'{$field->default_value}'";