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 $changeSerialize = self
::getChangeSerialize($params);
89 $customField = self
::createCustomFieldRecord($params);
90 // When deserializing a field, the update needs to run before the schema change
91 if ($changeSerialize === 0) {
92 CRM_Core_DAO
::singleValueQuery(self
::getAlterSerializeSQL($customField));
94 $op = empty($params['id']) ?
'add' : 'modify';
95 self
::createField($customField, $op);
96 // When serializing a field, the update needs to run after the schema change
97 if ($changeSerialize === 1) {
98 CRM_Core_DAO
::singleValueQuery(self
::getAlterSerializeSQL($customField));
101 CRM_Utils_Hook
::post(($op === 'add' ?
'create' : 'edit'), 'CustomField', $customField->id
, $customField);
103 CRM_Utils_System
::flushCache();
104 // Flush caches is not aggressive about clearing the specific cache we know we want to clear
105 // so do it manually. Ideally we wouldn't need to clear others...
106 Civi
::cache('metadata')->clear();
112 * Save multiple fields, now deprecated in favor of self::writeRecords.
113 * https://lab.civicrm.org/dev/core/issues/1093
116 * @param array $bulkParams
117 * Array of arrays as would be passed into create
118 * @param array $defaults
119 * Default parameters to be be merged into each of the params.
121 * @throws \CiviCRM_API3_Exception
123 public static function bulkSave($bulkParams, $defaults = []) {
124 foreach ($bulkParams as $index => $fieldParams) {
125 $bulkParams[$index] = array_merge($defaults, $fieldParams);
127 self
::writeRecords($bulkParams);
131 * Create/update several fields at once in a mysql efficient way.
133 * @param array $records
134 * @return CRM_Core_DAO_CustomField[]
135 * @throws CRM_Core_Exception
136 * @throws CiviCRM_API3_Exception
138 public static function writeRecords(array $records) {
139 $addedColumns = $sql = $customFields = $pre = $post = [];
140 foreach ($records as $index => $params) {
141 CRM_Utils_Hook
::pre(empty($params['id']) ?
'create' : 'edit', 'CustomField', $params['id'] ??
NULL, $params);
143 $changeSerialize = self
::getChangeSerialize($params);
144 $customField = self
::createCustomFieldRecord($params);
145 // Serialize/deserialize sql must run after/before the table is altered
146 if ($changeSerialize === 0) {
147 $pre[] = self
::getAlterSerializeSQL($customField);
149 if ($changeSerialize === 1) {
150 $post[] = self
::getAlterSerializeSQL($customField);
152 $fieldSQL = self
::getAlterFieldSQL($customField, empty($params['id']) ?
'add' : 'modify');
154 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customField->custom_group_id
, 'table_name');
155 $sql[$tableName][] = $fieldSQL;
156 $addedColumns[$tableName][] = $customField->name
;
157 $customFields[$index] = $customField;
160 foreach ($pre as $query) {
161 CRM_Core_DAO
::executeQuery($query);
164 foreach ($sql as $tableName => $statements) {
165 // CRM-7007: do not i18n-rewrite this query
166 CRM_Core_DAO
::executeQuery("ALTER TABLE $tableName " . implode(', ', $statements), [], TRUE, NULL, FALSE, FALSE);
168 if (CRM_Core_Config
::singleton()->logging
) {
169 $logging = new CRM_Logging_Schema();
170 $logging->fixSchemaDifferencesFor($tableName, ['ADD' => $addedColumns[$tableName]]);
173 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
176 foreach ($post as $query) {
177 CRM_Core_DAO
::executeQuery($query);
180 CRM_Utils_System
::flushCache();
181 Civi
::cache('metadata')->clear();
183 foreach ($customFields as $index => $customField) {
184 CRM_Utils_Hook
::post(empty($records[$index]['id']) ?
'create' : 'edit', 'CustomField', $customField->id
, $customField);
186 return $customFields;
190 * Fetch object based on array of properties.
192 * @param array $params
193 * An assoc array of name/value pairs.
194 * @param array $defaults
195 * (reference ) an assoc array to hold the flattened values.
197 * @return CRM_Core_DAO_CustomField
199 public static function retrieve($params, &$defaults) {
200 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
204 * Update the is_active flag in the db.
207 * Id of the database record.
208 * @param bool $is_active
209 * Value we want to set the is_active field.
212 * true if we found and updated the object, else false
214 public static function setIsActive($id, $is_active) {
216 CRM_Utils_System
::flushCache();
218 //enable-disable CustomField
219 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
220 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
224 * Get the field title.
232 public static function getTitle($id) {
233 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
237 * @param string $context
240 public function getOptions($context = NULL) {
241 CRM_Core_DAO
::buildOptionsContext($context);
246 $cacheKey = "CRM_Core_BAO_CustomField_getOptions_{$this->id}_$context";
247 $cache = CRM_Utils_Cache
::singleton();
248 $options = $cache->get($cacheKey);
249 if (!isset($options)) {
250 if (!$this->data_type ||
!$this->custom_group_id
) {
254 // This will hold the list of options in format key => label
257 if (!empty($this->option_group_id
)) {
258 $options = CRM_Core_OptionGroup
::valuesByID(
259 $this->option_group_id
, FALSE, FALSE, FALSE, $context == 'validate' ?
'name' : 'label', !($context == 'validate' ||
$context == 'get')
262 elseif ($this->data_type
=== 'StateProvince') {
263 $options = CRM_Core_PseudoConstant
::stateProvince();
265 elseif ($this->data_type
=== 'Country') {
266 $options = $context == 'validate' ? CRM_Core_PseudoConstant
::countryIsoCode() : CRM_Core_PseudoConstant
::country();
268 elseif ($this->data_type
=== 'Boolean') {
269 $options = $context == 'validate' ?
[0, 1] : CRM_Core_SelectValues
::boolean();
271 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
272 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, ['context' => $context]);
273 $cache->set($cacheKey, $options);
281 public static function buildOptions($fieldName, $context = NULL, $props = []) {
282 $options = parent
::buildOptions($fieldName, $context, $props);
283 // This provides legacy support for APIv3, allowing no-longer-existent html types
284 if ($fieldName == 'html_type' && isset($props['version']) && $props['version'] == 3) {
285 $options['Multi-Select'] = 'Multi-Select';
286 $options['Select Country'] = 'Select Country';
287 $options['Multi-Select Country'] = 'Multi-Select Country';
288 $options['Select State/Province'] = 'Select State/Province';
289 $options['Multi-Select State/Province'] = 'Multi-Select State/Province';
295 * Store and return an array of all active custom fields.
297 * @param string $customDataType
298 * Type of Custom Data; 'ANY' is a synonym for "all contact data types".
299 * @param bool $showAll
300 * If true returns all fields (includes disabled fields).
301 * @param bool $inline
302 * If true returns all inline fields (includes disabled fields).
303 * @param int $customDataSubType
304 * Custom Data sub type value.
305 * @param int $customDataSubName
306 * Custom Data sub name value.
307 * @param bool $onlyParent
308 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
309 * @param bool $onlySubType
310 * Return only custom data for subtype.
311 * @param bool $checkPermission
312 * If false, do not include permissioning clause.
315 * an array of active custom fields.
316 * @throws \CRM_Core_Exception
318 public static function &getFields(
319 $customDataType = 'Individual',
322 $customDataSubType = NULL,
323 $customDataSubName = NULL,
325 $onlySubType = FALSE,
326 $checkPermission = TRUE
328 if (empty($customDataType)) {
329 $customDataType = ['Contact', 'Individual', 'Organization', 'Household'];
331 if ($customDataType === 'ANY') {
332 // NULL should have been respected but the line above broke that.
333 // boo for us not having enough unit tests back them.
334 $customDataType = NULL;
336 if ($customDataType && !is_array($customDataType)) {
338 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
339 // This is the case when getFieldsForImport() requires fields
340 // limited strictly to a subtype.
341 $customDataSubType = $customDataType;
342 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
346 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
347 // this makes the method flexible to support retrieving fields
348 // for multiple extends value.
349 $customDataType = [$customDataType];
353 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
355 if (is_array($customDataType)) {
356 $cacheKey = implode('_', $customDataType);
359 $cacheKey = $customDataType;
362 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
363 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
364 $cacheKey .= $showAll ?
'_1' : '_0';
365 $cacheKey .= $inline ?
'_1_' : '_0_';
366 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
367 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
368 $cacheKey .= $checkPermission ?
'_1_' . CRM_Core_Session
::getLoggedInContactID() . '_' : '_0_0_';
369 $cacheKey .= '_' . CRM_Core_Config
::domainID() . '_';
371 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
373 // also get the permission stuff here
374 if ($checkPermission) {
375 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
380 $permissionClause = '(1)';
383 // lets md5 permission clause and take first 8 characters
384 $cacheKey .= substr(md5($permissionClause), 0, 8);
386 if (strlen($cacheKey) > 40) {
387 $cacheKey = md5($cacheKey);
390 if (!self
::$_importFields ||
391 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
393 if (!self
::$_importFields) {
394 self
::$_importFields = [];
397 // check if we can retrieve from database cache
398 $fields = Civi
::Cache('fields')->get("custom importableFields $cacheKey");
400 if ($fields === NULL) {
403 if (is_array($customDataType)) {
405 foreach ($customDataType as $dataType) {
406 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
407 if (in_array($dataType, ['Individual', 'Household', 'Organization'])) {
408 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
411 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
413 $value = $value ?
$value . ", {$val}" : $val;
417 $extends = "AND $cgTable.extends IN ( $value ) ";
421 if (!empty($customDataType) && empty($extends)) {
422 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
423 self
::$_importFields[$cacheKey] = [];
424 return self
::$_importFields[$cacheKey];
428 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
430 // Temporary hack - in 5.27 a new field is added to civicrm_custom_field. There is a high
431 // risk this function is called before the upgrade page can be reached and if
432 // so it will potentially result in fatal error.
433 $serializeField = CRM_Core_BAO_Domain
::isDBVersionAtLeast('5.27.alpha1') ?
"custom_field.serialize," : '';
435 $query = "SELECT custom_field.id, custom_field.label,
437 custom_field.data_type,
438 custom_field.html_type,
439 custom_field.default_value,
440 custom_field.options_per_line, custom_field.text_length,
441 custom_field.custom_group_id,
442 custom_field.is_required,
443 custom_field.column_name,
444 $cgTable.extends, custom_field.is_search_range,
445 $cgTable.extends_entity_column_value,
446 $cgTable.extends_entity_column_id,
447 custom_field.is_view,
448 custom_field.option_group_id,
449 custom_field.date_format,
450 custom_field.time_format,
451 $cgTable.is_multiple,
454 og.name as option_group_name
455 FROM civicrm_custom_field custom_field
457 ON custom_field.custom_group_id = $cgTable.id
458 LEFT JOIN civicrm_option_group og
459 ON custom_field.option_group_id = og.id
463 $query .= " AND custom_field.is_active = 1 AND $cgTable.is_active = 1 ";
467 $query .= " AND $cgTable.style = 'Inline' ";
470 //get the custom fields for specific type in
471 //combination with fields those support any type.
472 if (!empty($customDataSubType)) {
474 foreach ($customDataSubType as $subtype) {
475 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($subtype, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
;
476 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
479 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
481 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
484 if ($customDataSubName) {
485 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
488 // also get the permission stuff here
489 if ($checkPermission) {
490 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
495 $permissionClause = '(1)';
498 $query .= " $extends AND $permissionClause
499 ORDER BY $cgTable.weight, $cgTable.title,
500 custom_field.weight, custom_field.label";
502 $dao = CRM_Core_DAO
::executeQuery($query);
505 while (($dao->fetch()) != NULL) {
506 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
507 $fields[$dao->id
]['id'] = $dao->id
;
508 $fields[$dao->id
]['label'] = $dao->label
;
509 // This seems broken, but not in a new way.
510 $fields[$dao->id
]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
511 // To support the consolidation of various functions & their expectations.
512 $fields[$dao->id
]['title'] = $dao->label
;
513 $fields[$dao->id
]['custom_field_id'] = $dao->id
;
514 $fields[$dao->id
]['groupTitle'] = $dao->title
;
515 $fields[$dao->id
]['data_type'] = $dao->data_type
;
516 $fields[$dao->id
]['name'] = 'custom_' . $dao->id
;
517 $fields[$dao->id
]['type'] = CRM_Utils_Array
::value($dao->data_type
, self
::dataToType());
518 $fields[$dao->id
]['html_type'] = $dao->html_type
;
519 $fields[$dao->id
]['default_value'] = $dao->default_value
;
520 $fields[$dao->id
]['text_length'] = $dao->text_length
;
521 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
522 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
523 $fields[$dao->id
]['extends'] = $dao->extends;
524 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
525 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
526 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
527 $fields[$dao->id
]['is_view'] = $dao->is_view
;
528 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
529 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
530 $fields[$dao->id
]['date_format'] = $dao->date_format
;
531 $fields[$dao->id
]['time_format'] = $dao->time_format
;
532 $fields[$dao->id
]['is_required'] = $dao->is_required
;
533 $fields[$dao->id
]['table_name'] = $dao->table_name
;
534 $fields[$dao->id
]['column_name'] = $dao->column_name
;
535 $fields[$dao->id
]['serialize'] = $serializeField ?
$dao->serialize
: (int) self
::isSerialized($dao);
536 $fields[$dao->id
]['where'] = $dao->table_name
. '.' . $dao->column_name
;
537 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
538 $fields[$dao->id
]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery
::$extendsMap) ? CRM_Core_BAO_CustomQuery
::$extendsMap[$dao->extends] : '';
539 if (in_array($dao->extends, CRM_Contact_BAO_ContactType
::subTypes())) {
540 // if $extends is a subtype, refer contact table
541 $fields[$dao->id
]['extends_table'] = 'civicrm_contact';
543 // Search table is used by query object searches..
544 $fields[$dao->id
]['search_table'] = ($fields[$dao->id
]['extends_table'] == 'civicrm_contact') ?
'contact_a' : $fields[$dao->id
]['extends_table'];
545 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
548 Civi
::cache('fields')->set("custom importableFields $cacheKey", $fields);
550 self
::$_importFields[$cacheKey] = $fields;
553 return self
::$_importFields[$cacheKey];
557 * Return the field ids and names (with groups) for import purpose.
559 * @param int|string $contactType Contact type
560 * @param bool $showAll
561 * If true returns all fields (includes disabled fields).
562 * @param bool $onlyParent
563 * Return fields ONLY related to basic types.
564 * @param bool $search
565 * When called from search and multiple records need to be returned.
566 * @param bool $checkPermission
567 * If false, do not include permissioning clause.
569 * @param bool $withMultiple
573 public static function getFieldsForImport(
574 $contactType = 'Individual',
578 $checkPermission = TRUE,
579 $withMultiple = FALSE
581 // Note: there are situations when we want getFieldsForImport() return fields related
582 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
583 $fields = &self
::getFields($contactType,
593 $importableFields = [];
594 foreach ($fields as $id => $values) {
595 // for now we should not allow multiple fields in profile / export etc, hence unsetting
597 (!empty($values['is_multiple']) && !$withMultiple)
601 if (!empty($values['text_length'])) {
602 $values['maxlength'] = (int) $values['text_length'];
605 /* generate the key for the fields array */
608 $importableFields[$key] = $values;
609 $importableFields[$key]['import'] = 1;
612 return $importableFields;
616 * Get the field id from an import key.
626 public static function getKeyID($key, $all = FALSE) {
628 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
635 CRM_Utils_Array
::value(2, $match),
639 return $all ?
[NULL, NULL] : NULL;
643 * Use the cache to get all values of a specific custom field.
645 * @param int $fieldID
646 * The custom field ID.
648 * @return CRM_Core_BAO_CustomField
650 * @throws CRM_Core_Exception
652 public static function getFieldObject($fieldID) {
653 $field = new CRM_Core_BAO_CustomField();
655 // check if we can get the field values from the system cache
656 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
657 $cache = CRM_Utils_Cache
::singleton();
658 $fieldValues = $cache->get($cacheKey);
659 if (empty($fieldValues)) {
660 $field->id
= $fieldID;
661 if (!$field->find(TRUE)) {
662 throw new CRM_Core_Exception('Cannot find Custom Field');
666 CRM_Core_DAO
::storeValues($field, $fieldValues);
668 $cache->set($cacheKey, $fieldValues);
671 $field->copyValues($fieldValues);
678 * Add a custom field to an existing form.
680 * @param CRM_Core_Form $qf
681 * Form object (reference).
682 * @param string $elementName
683 * Name of the custom field.
684 * @param int $fieldId
685 * @param bool $useRequired
686 * True if required else false.
687 * @param bool $search
688 * True if used for search else false.
689 * @param string $label
690 * Label for custom field.
691 * @return \HTML_QuickForm_Element|null
692 * @throws \CiviCRM_API3_Exception
694 public static function addQuickFormElement(
695 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
697 $field = self
::getFieldObject($fieldId);
698 $widget = $field->html_type
;
700 $customFieldAttributes = [];
702 if (!isset($label)) {
703 $label = $field->label
;
706 // DAO stores attributes as a string, but it's hard to manipulate and
707 // CRM_Core_Form::add() wants them as an array.
708 $fieldAttributes = self
::attributesFromString($field->attributes
);
710 // Custom field HTML should indicate group+field name
711 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
712 $fieldAttributes['data-crm-custom'] = $groupName . ':' . $field->name
;
714 // Fixed for Issue CRM-2183
715 if ($widget == 'TextArea' && $search) {
719 $placeholder = $search ?
ts('- any %1 -', [1 => $label]) : ts('- select %1 -', [1 => $label]);
721 if (in_array($widget, [
726 $options = $field->getOptions($search ?
'search' : 'create');
728 // Consolidate widget types to simplify the below switch statement
733 // Search field is always multi-select
734 if ($search ||
(self
::isSerialized($field) && $widget === 'Select')) {
735 $fieldAttributes['class'] = ltrim(($fieldAttributes['class'] ??
'') . ' huge');
736 $fieldAttributes['multiple'] = 'multiple';
737 $fieldAttributes['placeholder'] = $placeholder;
740 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
741 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
742 if ($field->option_group_id
&& !$search && $canEditOptions) {
743 $customFieldAttributes +
= [
744 'data-api-entity' => $field->getEntity(),
745 'data-api-field' => 'custom_' . $field->id
,
746 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
748 $fieldAttributes = array_merge($fieldAttributes, $customFieldAttributes);
752 $rangeDataTypes = ['Int', 'Float', 'Money'];
754 // at some point in time we might want to split the below into small functions
759 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
760 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $fieldAttributes);
761 $qf->add('text', $elementName . '_to', ts('To'), $fieldAttributes);
764 if ($field->text_length
) {
765 $fieldAttributes['maxlength'] = $field->text_length
;
766 if ($field->text_length
< 20) {
767 $fieldAttributes['size'] = $field->text_length
;
770 $element = $qf->add('text', $elementName, $label,
772 $useRequired && !$search
778 $fieldAttributes['rows'] = $field->note_rows ??
4;
779 $fieldAttributes['cols'] = $field->note_columns ??
60;
781 if ($field->text_length
) {
782 $fieldAttributes['maxlength'] = $field->text_length
;
784 $element = $qf->add('textarea',
788 $useRequired && !$search
793 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
794 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
795 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
798 'date' => $field->date_format
,
799 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
800 //CRM-18487 - max date should be the last date of the year.
801 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
802 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
804 if ($field->is_search_range
&& $search) {
805 $qf->add('datepicker', $elementName . '_from', $label, $fieldAttributes +
array('placeholder' => ts('From')), FALSE, $params);
806 $qf->add('datepicker', $elementName . '_to', NULL, $fieldAttributes +
array('placeholder' => ts('To')), FALSE, $params);
809 $element = $qf->add('datepicker', $elementName, $label, $fieldAttributes, $useRequired && !$search, $params);
814 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
815 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $fieldAttributes);
816 $qf->add('text', $elementName . '_to', ts('To'), $fieldAttributes);
819 $fieldAttributes = array_merge($fieldAttributes, $customFieldAttributes);
820 if ($search ||
empty($useRequired)) {
821 $fieldAttributes['allowClear'] = TRUE;
823 $qf->addRadio($elementName, $label, $options, $fieldAttributes, NULL, $useRequired);
827 // For all select elements
829 $fieldAttributes['class'] = ltrim(($fieldAttributes['class'] ??
'') . ' crm-select2');
831 if (empty($fieldAttributes['multiple'])) {
832 $options = ['' => $placeholder] +
$options;
834 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $fieldAttributes);
836 // Add and/or option for fields that store multiple values
837 if ($search && self
::isSerialized($field)) {
838 $qf->addRadio($elementName . '_operator', '', [
841 ], [], NULL, FALSE, [
842 'or' => ['title' => ts('Results may contain any of the selected options')],
843 'and' => ['title' => ts('Results must have all of the selected options')],
845 $qf->setDefaults([$elementName . '_operator' => 'or']);
851 foreach ($options as $v => $l) {
852 // TODO: I'm not sure if this is supposed to exclude whatever might be
853 // in $field->attributes (available in array format as
854 // $fieldAttributes). Leaving as-is for now.
855 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
858 $group = $element = $qf->addGroup($check, $elementName, $label);
859 $optionEditKey = 'data-option-edit-path';
860 if (isset($customFieldAttributes[$optionEditKey])) {
861 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
864 if ($useRequired && !$search) {
865 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
870 // we should not build upload file in search mode
875 strtolower($field->html_type
),
879 $useRequired && !$search
881 $qf->addUploadElement($elementName);
884 case 'RichTextEditor':
885 $fieldAttributes['rows'] = $field->note_rows
;
886 $fieldAttributes['cols'] = $field->note_columns
;
887 if ($field->text_length
) {
888 $fieldAttributes['maxlength'] = $field->text_length
;
890 $element = $qf->add('wysiwyg', $elementName, $label, $fieldAttributes, $useRequired && !$search);
893 case 'Autocomplete-Select':
894 static $customUrls = [];
895 if ($field->data_type
== 'ContactReference') {
896 // break if contact does not have permission to access ContactReference
897 if (!CRM_Core_Permission
::check('access contact reference fields')) {
900 $fieldAttributes['class'] = ltrim(($fieldAttributes['class'] ??
'') . ' crm-form-contact-reference huge');
901 $fieldAttributes['data-api-entity'] = 'Contact';
902 if (!empty($field->serialize
) ||
$search) {
903 $fieldAttributes['multiple'] = TRUE;
905 $element = $qf->add('text', $elementName, $label, $fieldAttributes, $useRequired && !$search);
907 $urlParams = "context=customfield&id={$field->id}";
908 $idOfelement = $elementName;
909 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
910 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
911 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
912 // rather than layering on more hacks.
913 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
914 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') +
1)), 0, -1);
916 $customUrls[$idOfelement] = CRM_Utils_System
::url('civicrm/ajax/contactref',
923 // FIXME: This won't work with customFieldOptions hook
924 $fieldAttributes +
= [
925 'entity' => 'OptionValue',
926 'placeholder' => $placeholder,
927 'multiple' => $search ?
TRUE : !empty($field->serialize
),
929 'params' => ['option_group_id' => $field->option_group_id
, 'is_active' => 1],
932 $element = $qf->addEntityRef($elementName, $label, $fieldAttributes, $useRequired && !$search);
935 $qf->assign('customUrls', $customUrls);
939 switch ($field->data_type
) {
941 // integers will have numeric rule applied to them.
942 if ($field->is_search_range
&& $search && $widget != 'Select') {
943 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', [1 => $label]), 'integer');
944 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', [1 => $label]), 'integer');
946 elseif ($widget == 'Text') {
947 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', [1 => $label]), 'integer');
952 if ($field->is_search_range
&& $search) {
953 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', [1 => $label]), 'numeric');
954 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', [1 => $label]), 'numeric');
956 elseif ($widget == 'Text') {
957 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', [1 => $label]), 'numeric');
962 if ($field->is_search_range
&& $search) {
963 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
964 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
966 elseif ($widget == 'Text') {
967 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
972 $element->setAttribute('class', "url");
973 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
976 if ($field->is_view
&& !$search) {
977 $qf->freeze($elementName);
983 * Take a string of HTML element attributes and turn it into an associative
986 * @param string $attrString
987 * The attributes as a string, e.g. `rows=3 cols=40`.
990 * The attributes as an array, e.g. `['rows' => 3, 'cols' => 40]`.
992 public static function attributesFromString($attrString) {
994 foreach (explode(' ', $attrString) as $at) {
995 if (strpos($at, '=')) {
996 list($k, $v) = explode('=', $at);
997 $attributes[$k] = trim($v, ' "');
1004 * Delete the Custom Field.
1006 * @param object $field
1009 public static function deleteField($field) {
1010 CRM_Utils_System
::flushCache();
1012 // first delete the custom option group and values associated with this field
1013 if ($field->option_group_id
) {
1014 //check if option group is related to any other field, if
1015 //not delete the option group and related option values
1016 self
::checkOptionGroup($field->option_group_id
);
1018 // next drop the column from the custom value table
1019 self
::createField($field, 'delete');
1022 CRM_Core_BAO_UFField
::delUFField($field->id
);
1023 CRM_Core_BAO_Mapping
::removeFieldFromMapping('custom_' . $field->id
);
1024 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1026 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
1030 * @param string|int|array|null $value
1031 * @param CRM_Core_BAO_CustomField|int|array|string $field
1032 * @param int $entityId
1036 * @throws \CRM_Core_Exception
1038 public static function displayValue($value, $field, $entityId = NULL) {
1039 $field = is_array($field) ?
$field['id'] : $field;
1040 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1043 throw new CRM_Core_Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1046 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1047 $field = self
::getFieldObject($fieldId);
1050 $fieldInfo = ['options' => $field->getOptions()] +
(array) $field;
1052 $displayValue = self
::formatDisplayValue($value, $fieldInfo, $entityId);
1054 // Call hook to alter display value.
1055 CRM_Utils_Hook
::alterCustomFieldDisplayValue($displayValue, $value, $entityId, $fieldInfo);
1057 return $displayValue;
1061 * Lower-level logic for rendering a custom field value
1063 * @param string|array $value
1064 * @param array $field
1065 * @param int|null $entityId
1069 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1071 if (self
::isSerialized($field) && !is_array($value)) {
1072 $value = CRM_Utils_Array
::explodePadded($value);
1075 if ($field['html_type'] == 'CheckBox' && $value) {
1076 $value = CRM_Utils_Array
::convertCheckboxFormatToArray($value);
1079 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1081 switch ($field['html_type']) {
1084 case 'Autocomplete-Select':
1087 if ($field['data_type'] == 'ContactReference' && (is_array($value) ||
is_numeric($value))) {
1089 foreach ((array) $value as $contactId) {
1090 $displayNames[] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'display_name');
1092 $display = implode(', ', $displayNames);
1094 elseif ($field['data_type'] == 'ContactReference') {
1097 elseif (is_array($value)) {
1099 foreach ($value as $key => $val) {
1100 $v[] = $field['options'][$val] ??
NULL;
1102 $display = implode(', ', $v);
1105 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1106 // For float type (see Number and Money) $value would be decimal like
1107 // 1.00 (because it is stored in db as decimal), while options array
1108 // key would be integer like 1. In this case expression on line above
1109 // would return empty string (default value), despite the fact that
1110 // matching option exists in the array.
1111 // In such cases we could just get intval($value) and fetch matching
1112 // option again, but this would not work if key is float like 5.6.
1113 // So we need to truncate trailing zeros to make it work as expected.
1114 if ($display === '' && strpos($value, '.') !== FALSE) {
1115 // Use round() to truncate trailing zeros, e.g:
1116 // 10.00 -> 10, 10.60 -> 10.6, 10.69 -> 10.69.
1117 $value = (string) round($value, 5);
1118 $display = $field['options'][$value] ??
'';
1124 $customFormat = NULL;
1126 // FIXME: Are there any legitimate reasons why $value would be an array?
1127 // Or should we throw an exception here if it is?
1128 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1130 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1131 $format = $field['date_format'] ??
NULL;
1134 if (array_key_exists($format, $actualPHPFormats)) {
1135 $customTimeFormat = (array) $actualPHPFormats[$format];
1136 switch (CRM_Utils_Array
::value('time_format', $field)) {
1138 $customTimeFormat[] = 'g:iA';
1142 $customTimeFormat[] = 'G:i';
1146 //If time is not selected remove time from value.
1147 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1149 $customFormat = implode(" ", $customTimeFormat);
1152 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1156 // In the context of displaying a profile, show file/image
1159 if (CRM_Utils_Rule
::positiveInteger($value)) {
1163 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1165 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1167 $display = $url['file_url'];
1171 // In other contexts show a paperclip icon
1172 if (CRM_Utils_Rule
::integer($value)) {
1173 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1175 $file_description = '';
1177 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1179 catch (CiviCRM_API3_Exception
$dontcare) {
1183 $display = "{$icons[$value]}{$file_description}";
1186 //CRM-18396, if filename is passed instead
1194 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1198 $display = nl2br($display);
1202 if ($field['data_type'] == 'Money' && isset($value)) {
1203 // $value can also be an array(while using IN operator from search builder or api).
1204 foreach ((array) $value as $val) {
1205 $disp[] = CRM_Utils_Money
::formatLocaleNumericRoundedForDefaultCurrency($val);
1207 $display = implode(', ', $disp);
1209 elseif ($field['data_type'] == 'Float' && isset($value)) {
1210 // $value can also be an array(while using IN operator from search builder or api).
1211 foreach ((array) $value as $val) {
1212 $disp[] = CRM_Utils_Number
::formatLocaleNumeric($val);
1214 $display = implode(', ', $disp);
1222 * Set default values for custom data used in profile.
1224 * @param int $customFieldId
1226 * @param string $elementName
1227 * Custom field name.
1228 * @param array $defaults
1229 * Associated array of fields.
1230 * @param int $contactId
1234 * @param mixed $value
1235 * If passed - dont fetch value from db,.
1236 * just format the given value
1238 public static function setProfileDefaults(
1246 //get the type of custom field
1247 $customField = new CRM_Core_BAO_CustomField();
1248 $customField->id
= $customFieldId;
1249 $customField->find(TRUE);
1252 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1253 $value = $customField->default_value
;
1257 if (!isset($value)) {
1258 $info = self
::getTableColumnGroup($customFieldId);
1259 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1260 $result = CRM_Core_DAO
::executeQuery($query);
1261 if ($result->fetch()) {
1262 $value = $result->value
;
1266 if ($customField->data_type
== 'Country') {
1268 $config = CRM_Core_Config
::singleton();
1269 if ($config->defaultContactCountry
) {
1270 $value = CRM_Core_BAO_Country
::defaultContactCountry();
1276 //set defaults if mode is registration
1277 if (!trim($value) &&
1279 (!in_array($mode, [CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
]))
1281 $value = $customField->default_value
;
1284 if ($customField->data_type
== 'Money' && isset($value)) {
1285 $value = number_format($value, 2);
1287 if (self
::isSerialized($customField) && $value) {
1288 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1289 $defaults[$elementName] = [];
1290 $checkedValue = CRM_Utils_Array
::explodePadded($value);
1291 foreach ($customOption as $val) {
1292 if (in_array($val['value'], $checkedValue)) {
1293 if ($customField->html_type
== 'CheckBox') {
1294 $defaults[$elementName][$val['value']] = 1;
1297 $defaults[$elementName][$val['value']] = $val['value'];
1303 $defaults[$elementName] = $value;
1310 * @param int $contactID
1312 * @param int $fileID
1313 * @param bool $absolute
1315 * @param string $multiRecordWhereClause
1319 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1322 $params = ['id' => $cfID];
1324 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1325 $columnName = $defaults['column_name'];
1327 //table name of custom data
1328 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1329 $defaults['custom_group_id'],
1333 //query to fetch id from civicrm_file
1334 if ($multiRecordWhereClause) {
1335 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1338 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1340 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1345 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1350 $result['file_id'] = $fileID;
1352 if ($fileType == 'image/jpeg' ||
1353 $fileType == 'image/pjpeg' ||
1354 $fileType == 'image/gif' ||
1355 $fileType == 'image/x-png' ||
1356 $fileType == 'image/png'
1358 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1363 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1364 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1365 $url = CRM_Utils_System
::url('civicrm/file',
1366 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1367 $absolute, NULL, TRUE, TRUE
1369 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1371 // for non image files
1373 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1377 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1378 $url = CRM_Utils_System
::url('civicrm/file',
1379 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1380 $absolute, NULL, TRUE, TRUE
1382 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1390 * Format custom fields before inserting.
1392 * @param int $customFieldId
1394 * @param array $customFormatted
1396 * @param mixed $value
1397 * Value of custom field.
1398 * @param string $customFieldExtend
1399 * Custom field extends.
1400 * @param int $customValueId
1401 * Custom option value id.
1402 * @param int $entityId
1403 * Entity id (contribution, membership...).
1404 * @param bool $inline
1405 * Consider inline custom groups only.
1406 * @param bool $checkPermission
1407 * If false, do not include permissioning clause.
1408 * @param bool $includeViewOnly
1409 * If true, fields marked 'View Only' are included. Required for APIv3.
1411 * @return array|NULL
1412 * formatted custom field array
1414 public static function formatCustomField(
1415 $customFieldId, &$customFormatted, $value,
1416 $customFieldExtend, $customValueId = NULL,
1419 $checkPermission = TRUE,
1420 $includeViewOnly = FALSE
1422 //get the custom fields for the entity
1423 //subtype and basic type
1424 $customDataSubType = NULL;
1425 if ($customFieldExtend) {
1426 // This is the case when getFieldsForImport() requires fields
1427 // of subtype and its parent.CRM-5143
1428 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1429 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1430 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1431 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1432 if (is_array($customFieldExtend)) {
1433 $customFieldExtend = array_unique(array_values($customFieldExtend));
1438 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1448 if (!array_key_exists($customFieldId, $customFields)) {
1452 // return if field is a 'code' field
1453 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1457 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1459 if (!$customValueId &&
1460 // we always create new entites for is_multiple unless specified
1461 !$customFields[$customFieldId]['is_multiple'] &&
1467 WHERE entity_id={$entityId}";
1469 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1472 //fix checkbox, now check box always submits values
1473 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1475 // Note that only during merge this is not an array, and you can directly use value
1476 if (is_array($value)) {
1477 $selectedValues = [];
1478 foreach ($value as $selId => $val) {
1480 $selectedValues[] = $selId;
1483 if (!empty($selectedValues)) {
1484 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1486 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1494 elseif (self
::isSerialized($customFields[$customFieldId])) {
1495 // Select2 v3 returns a comma-separated string.
1496 if ($customFields[$customFieldId]['html_type'] == 'Autocomplete-Select' && is_string($value)) {
1497 $value = explode(',', $value);
1500 $value = $value ? CRM_Utils_Array
::implodePadded($value) : '';
1503 if (self
::isSerialized($customFields[$customFieldId]) &&
1504 $customFields[$customFieldId]['data_type'] == 'String' &&
1505 !empty($customFields[$customFieldId]['text_length']) &&
1508 // lets make sure that value is less than the length, else we'll
1509 // be losing some data, CRM-7481
1510 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1511 // need to do a few things here
1513 // 1. lets find a new length
1514 $newLength = $customFields[$customFieldId]['text_length'];
1515 $minLength = strlen($value);
1516 while ($newLength < $minLength) {
1517 $newLength = $newLength * 2;
1520 // set the custom field meta data to have a length larger than value
1521 // alter the custom value table column to match this length
1522 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1527 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1528 if (!CRM_Utils_System
::isNull($value)) {
1529 $format = $customFields[$customFieldId]['date_format'];
1530 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1535 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1536 $customFields[$customFieldId]['data_type'] == 'Money'
1542 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1543 $value = CRM_Utils_Rule
::cleanMoney($value);
1547 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1548 $customFields[$customFieldId]['data_type'] == 'Country'
1558 if ($customFields[$customFieldId]['data_type'] == 'File') {
1559 if (empty($value)) {
1563 $config = CRM_Core_Config
::singleton();
1565 // If we are already passing the file id as a value then retrieve and set the file data
1566 if (CRM_Utils_Rule
::integer($value)) {
1567 $fileDAO = new CRM_Core_DAO_File();
1568 $fileDAO->id
= $value;
1569 $fileDAO->find(TRUE);
1572 $fName = $fileDAO->uri
;
1573 $mimeType = $fileDAO->mime_type
;
1576 elseif (empty($value['name'])) {
1577 // Happens when calling the API to update custom fields values, but the filename
1578 // is empty, for an existing entity (in a specific case, was from a d7-webform
1579 // that was updating a relationship with a File customfield, so $value['id'] was
1580 // not empty, but the filename was empty.
1584 $fName = $value['name'];
1585 $mimeType = $value['type'];
1588 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1590 // rename this file to go into the secure directory only if
1591 // user has uploaded new file not existing verfied on the basis of $fileID
1592 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1593 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1596 if ($customValueId && empty($fileID)) {
1601 $params = [1 => [$customValueId, 'Integer']];
1602 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1605 $fileDAO = new CRM_Core_DAO_File();
1608 $fileDAO->id
= $fileID;
1611 $fileDAO->uri
= $filename;
1612 $fileDAO->mime_type
= $mimeType;
1613 $fileDAO->upload_date
= date('YmdHis');
1615 $fileID = $fileDAO->id
;
1619 if (!is_array($customFormatted)) {
1620 $customFormatted = [];
1623 if (!array_key_exists($customFieldId, $customFormatted)) {
1624 $customFormatted[$customFieldId] = [];
1628 if ($customValueId) {
1629 $index = $customValueId;
1632 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1633 $customFormatted[$customFieldId][$index] = [];
1635 $customFormatted[$customFieldId][$index] = [
1636 'id' => $customValueId > 0 ?
$customValueId : NULL,
1638 'type' => $customFields[$customFieldId]['data_type'],
1639 'custom_field_id' => $customFieldId,
1640 'custom_group_id' => $groupID,
1641 'table_name' => $tableName,
1642 'column_name' => $columnName,
1643 'file_id' => $fileID,
1644 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1647 //we need to sort so that custom fields are created in the order of entry
1648 krsort($customFormatted[$customFieldId]);
1649 return $customFormatted;
1653 * Get default custom table schema.
1655 * @param array $params
1659 public static function defaultCustomTableSchema($params) {
1660 // add the id and extends_id
1661 $collation = CRM_Core_BAO_SchemaHandler
::getInUseCollation();
1662 $characterSet = 'utf8';
1663 if (stripos($collation, 'utf8mb4') !== FALSE) {
1664 $characterSet = 'utf8mb4';
1667 'name' => $params['name'],
1668 'is_multiple' => $params['is_multiple'],
1669 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET {$characterSet} COLLATE {$collation}",
1673 'type' => 'int unsigned',
1676 'attributes' => 'AUTO_INCREMENT',
1677 'comment' => 'Default MySQL primary key',
1680 'name' => 'entity_id',
1681 'type' => 'int unsigned',
1683 'comment' => 'Table that this extends',
1684 'fk_table_name' => $params['extends_name'],
1685 'fk_field_name' => 'id',
1686 'fk_attributes' => 'ON DELETE CASCADE',
1691 // If on MySQL 5.6 include ROW_FORMAT=DYNAMIC to fix unit tests
1692 $databaseVersion = CRM_Utils_SQL
::getDatabaseVersion();
1693 if (version_compare($databaseVersion, '5.7', '<') && version_compare($databaseVersion, '5.6', '>=')) {
1694 $table['attributes'] = $table['attributes'] . ' ROW_FORMAT=DYNAMIC';
1697 if (!$params['is_multiple']) {
1698 $table['indexes'] = [
1701 'field_name_1' => 'entity_id',
1709 * Create custom field.
1711 * @param CRM_Core_DAO_CustomField $field
1712 * @param string $operation
1714 public static function createField($field, $operation) {
1715 $sql = str_repeat(' ', 8);
1716 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1717 $sql .= "ALTER TABLE " . $tableName;
1718 $sql .= self
::getAlterFieldSQL($field, $operation);
1720 // CRM-7007: do not i18n-rewrite this query
1721 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1723 $config = CRM_Core_Config
::singleton();
1724 if ($config->logging
) {
1725 // CRM-16717 not sure why this was originally limited to add.
1726 // For example custom tables can have field length changes - which need to flow through to logging.
1727 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1728 if ($operation === 'add' ||
$operation === 'modify') {
1729 $logging = new CRM_Logging_Schema();
1730 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name
]]);
1734 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
1738 * @param CRM_Core_DAO_CustomField $field
1739 * @param string $operation add|modify|delete
1743 public static function getAlterFieldSQL($field, $operation) {
1744 $params = self
::prepareCreateParams($field, $operation);
1745 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1746 // a function only used by Custom Field creation...
1747 $params['required'] = FALSE;
1748 return CRM_Core_BAO_SchemaHandler
::getFieldAlterSQL($params);
1752 * Get query to reformat existing values for a field when changing its serialize attribute
1754 * @param CRM_Core_DAO_CustomField $field
1757 private static function getAlterSerializeSQL($field) {
1758 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1759 $col = $field->column_name
;
1760 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
1761 if ($field->serialize
) {
1762 return "UPDATE `$table` SET `$col` = CONCAT('$sp', `$col`, '$sp') WHERE `$col` IS NOT NULL AND `$col` NOT LIKE '$sp%' AND `$col` != ''";
1765 return "UPDATE `$table` SET `$col` = SUBSTRING_INDEX(SUBSTRING(`$col`, 2), '$sp', 1) WHERE `$col` LIKE '$sp%'";
1770 * Determine whether it would be safe to move a field.
1772 * @param int $fieldID
1773 * FK to civicrm_custom_field.
1774 * @param int $newGroupID
1775 * FK to civicrm_custom_group.
1778 * array(string) or TRUE
1780 public static function _moveFieldValidate($fieldID, $newGroupID) {
1783 $field = new CRM_Core_DAO_CustomField();
1784 $field->id
= $fieldID;
1785 if (!$field->find(TRUE)) {
1786 $errors['fieldID'] = 'Invalid ID for custom field';
1790 $oldGroup = new CRM_Core_DAO_CustomGroup();
1791 $oldGroup->id
= $field->custom_group_id
;
1792 if (!$oldGroup->find(TRUE)) {
1793 $errors['fieldID'] = 'Invalid ID for old custom group';
1797 $newGroup = new CRM_Core_DAO_CustomGroup();
1798 $newGroup->id
= $newGroupID;
1799 if (!$newGroup->find(TRUE)) {
1800 $errors['newGroupID'] = 'Invalid ID for new custom group';
1806 FROM civicrm_custom_field a
1807 INNER JOIN civicrm_custom_field b
1809 AND a.label = b.label
1810 AND b.custom_group_id = %2
1813 1 => [$field->id
, 'Integer'],
1814 2 => [$newGroup->id
, 'Integer'],
1816 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1818 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1821 $tableName = $oldGroup->table_name
;
1822 $columnName = $field->column_name
;
1827 WHERE $columnName is not null
1829 $count = CRM_Core_DAO
::singleValueQuery($query);
1833 FROM civicrm_custom_group
1834 WHERE id IN ( %1, %2 )
1837 1 => [$oldGroup->id
, 'Integer'],
1838 2 => [$newGroup->id
, 'Integer'],
1841 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1843 while ($dao->fetch()) {
1844 $extends[] = $dao->extends;
1846 if ($extends[0] != $extends[1]) {
1847 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1851 return empty($errors) ?
TRUE : $errors;
1855 * Move a custom data field from one group (table) to another.
1857 * @param int $fieldID
1858 * FK to civicrm_custom_field.
1859 * @param int $newGroupID
1860 * FK to civicrm_custom_group.
1862 * @throws CRM_Core_Exception
1864 public static function moveField($fieldID, $newGroupID) {
1865 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1866 if (TRUE !== $validation) {
1867 throw new CRM_Core_Exception(implode(' ', $validation));
1869 $field = new CRM_Core_DAO_CustomField();
1870 $field->id
= $fieldID;
1873 $newGroup = new CRM_Core_DAO_CustomGroup();
1874 $newGroup->id
= $newGroupID;
1875 $newGroup->find(TRUE);
1877 $oldGroup = new CRM_Core_DAO_CustomGroup();
1878 $oldGroup->id
= $field->custom_group_id
;
1879 $oldGroup->find(TRUE);
1882 $add->custom_group_id
= $newGroup->id
;
1883 self
::createField($add, 'add');
1885 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, `{$field->column_name}`)
1886 SELECT entity_id, `{$field->column_name}` FROM {$oldGroup->table_name}
1887 ON DUPLICATE KEY UPDATE `{$field->column_name}` = {$oldGroup->table_name}.`{$field->column_name}`
1889 CRM_Core_DAO
::executeQuery($sql);
1892 $del->custom_group_id
= $oldGroup->id
;
1893 self
::createField($del, 'delete');
1897 CRM_Utils_System
::flushCache();
1901 * Create an option value for a custom field option group ID.
1903 * @param array $params
1904 * @param string $value
1905 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1906 * @param string $index
1907 * @param string $dataType
1909 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $index, $dataType) {
1910 if (strlen(trim($value))) {
1911 $optionValue = new CRM_Core_DAO_OptionValue();
1912 $optionValue->option_group_id
= $optionGroup->id
;
1913 $optionValue->label
= $params['option_label'][$index];
1914 $optionValue->name
= $params['option_name'][$index] ?? CRM_Utils_String
::titleToVar($params['option_label'][$index]);
1915 switch ($dataType) {
1917 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1921 $optionValue->value
= intval($value);
1925 $optionValue->value
= floatval($value);
1929 $optionValue->value
= trim($value);
1932 $optionValue->weight
= $params['option_weight'][$index];
1933 $optionValue->is_active
= $params['option_status'][$index] ??
FALSE;
1934 $optionValue->description
= $params['option_description'][$index] ??
NULL;
1935 $optionValue->color
= $params['option_color'][$index] ??
NULL;
1936 $optionValue->icon
= $params['option_icon'][$index] ??
NULL;
1937 $optionValue->save();
1942 * Prepare for the create operation.
1944 * Munge params, create the option values if needed.
1946 * This could be called by a single create or a batchCreate.
1948 * @param array $params
1952 protected static function prepareCreate($params) {
1953 $op = empty($params['id']) ?
'create' : 'edit';
1954 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1955 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1956 if ($op === 'create') {
1957 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1958 if (!isset($params['column_name'])) {
1959 // if add mode & column_name not present, calculate it.
1960 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1962 if (!isset($params['name'])) {
1963 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1967 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'column_name');
1970 $htmlType = $params['html_type'] ??
NULL;
1971 $dataType = $params['data_type'] ??
NULL;
1973 if ($htmlType === 'Select Date' && empty($params['date_format'])) {
1974 $params['date_format'] = Civi
::settings()->get('dateInputFormat');
1977 // Checkboxes are always serialized in current schema
1978 if ($htmlType == 'CheckBox') {
1979 $params['serialize'] = CRM_Core_DAO
::SERIALIZE_SEPARATOR_BOOKEND
;
1982 if (!empty($params['serialize'])) {
1983 if (isset($params['default_checkbox_option'])) {
1985 foreach (array_keys($params['default_checkbox_option']) as $k => $v) {
1986 if ($params['option_value'][$v]) {
1987 $defaultArray[] = $params['option_value'][$v];
1991 if (!empty($defaultArray)) {
1992 // also add the separator before and after the value per new convention (CRM-1604)
1993 $params['default_value'] = CRM_Utils_Array
::implodePadded($defaultArray);
1997 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])) {
1998 $params['default_value'] = $params['option_value'][$params['default_option']];
2003 // create any option group & values if required
2004 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
2005 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)) {
2006 //CRM-16659: if option_value then create an option group for this custom field.
2007 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
2008 // first create an option group for this custom group
2009 $optionGroup = new CRM_Core_DAO_OptionGroup();
2010 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
2011 $optionGroup->title
= $params['label'];
2012 $optionGroup->is_active
= 1;
2013 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
2014 $optionGroup->is_reserved
= 0;
2015 $optionGroup->data_type
= $dataType;
2016 $optionGroup->save();
2017 $params['option_group_id'] = $optionGroup->id
;
2018 if (!empty($params['option_value']) && is_array($params['option_value'])) {
2019 foreach ($params['option_value'] as $k => $v) {
2020 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
2026 // Remove option group IDs from fields changed to Text html_type.
2027 if ($htmlType == 'Text') {
2028 $params['option_group_id'] = '';
2031 // check for orphan option groups
2032 if (!empty($params['option_group_id'])) {
2033 if (!empty($params['id'])) {
2034 self
::fixOptionGroups($params['id'], $params['option_group_id']);
2037 // if we do not have a default value
2038 // retrieve it from one of the other custom fields which use this option group
2039 if (empty($params['default_value'])) {
2040 //don't insert only value separator as default value, CRM-4579
2041 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'], !empty($params['serialize']));
2043 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultValue))) {
2044 $params['default_value'] = $defaultValue;
2049 // Set default textarea attributes
2050 if ($op == 'create' && !isset($params['attributes']) && $htmlType == 'TextArea') {
2051 $params['attributes'] = 'rows=4, cols=60';
2057 * Create database entry for custom field and related option groups.
2059 * @param array $params
2061 * @return CRM_Core_DAO_CustomField
2063 protected static function createCustomFieldRecord($params) {
2064 $transaction = new CRM_Core_Transaction();
2065 $params = self
::prepareCreate($params);
2067 $customField = new CRM_Core_DAO_CustomField();
2068 $customField->copyValues($params);
2069 $customField->save();
2071 //create/drop the index when we toggle the is_searchable flag
2072 $op = empty($params['id']) ?
'add' : 'modify';
2073 if ($op !== 'modify') {
2074 if ($params['is_append_field_id_to_column_name']) {
2075 $params['column_name'] .= "_{$customField->id}";
2077 $customField->column_name
= $params['column_name'];
2078 $customField->save();
2081 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
2082 $transaction->commit();
2084 // make sure all values are present in the object for further processing
2085 $customField->find(TRUE);
2087 return $customField;
2094 protected static function getChangeSerialize($params) {
2095 if (isset($params['serialize']) && !empty($params['id'])) {
2096 if ($params['serialize'] != CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'serialize')) {
2097 return (int) $params['serialize'];
2104 * Move custom data from one contact to another.
2106 * This is currently the start of a refactoring. The theory is each
2107 * entity could have a 'move' function with a DAO default one to fall back on.
2109 * At the moment this only does a small part of the process - ie deleting a file field that
2110 * is about to be overwritten. However, the goal is the whole process around the move for
2111 * custom data should be in here.
2113 * This is currently called by the merge class but it makes sense that api could
2114 * expose move actions as moving (e.g) contributions feels like a common
2115 * ask that should be handled by the form layer.
2117 * @param int $oldContactID
2118 * @param int $newContactID
2119 * @param int[] $fieldIDs
2120 * Optional list field ids to move.
2122 * @throws \CiviCRM_API3_Exception
2123 * @throws \Exception
2125 public function move($oldContactID, $newContactID, $fieldIDs) {
2126 if (empty($fieldIDs)) {
2129 $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'];
2131 foreach ($fieldIDs as $fieldID) {
2132 $return[] = 'custom_' . $fieldID;
2134 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2135 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2137 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2138 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2139 $fieldTypesNotHandledInMergeAttempt = ['File'];
2140 foreach ($fields as $field) {
2141 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2142 if ($field['data_type'] === 'File' && !$isMultiple) {
2143 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2144 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2146 if (!empty($oldContact['custom_' . $field['id']])) {
2147 CRM_Core_DAO
::executeQuery("
2148 UPDATE civicrm_entity_file
2149 SET entity_id = $newContactID
2150 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2154 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2155 CRM_Core_DAO
::executeQuery(
2156 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, `{$field['column_name']}`)
2157 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2158 ON DUPLICATE KEY UPDATE
2159 `{$field['column_name']}` = {$oldContact['custom_' . $field['id']]}
2166 * Get the database table name and column name for a custom field.
2168 * @param int $fieldID
2169 * The fieldID of the custom field.
2170 * @param bool $force
2171 * Force the sql to be run again (primarily used for tests).
2174 * fatal is fieldID does not exists, else array of tableName, columnName
2175 * @throws \CRM_Core_Exception
2177 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2178 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2179 $cache = CRM_Utils_Cache
::singleton();
2180 $fieldValues = $cache->get($cacheKey);
2181 if (empty($fieldValues) ||
$force) {
2183 SELECT cg.table_name, cf.column_name, cg.id
2184 FROM civicrm_custom_group cg,
2185 civicrm_custom_field cf
2186 WHERE cf.custom_group_id = cg.id
2188 $params = [1 => [$fieldID, 'Integer']];
2189 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2191 if (!$dao->fetch()) {
2192 throw new CRM_Core_Exception("Cannot find table and column information for Custom Field " . $fieldID);
2194 $fieldValues = [$dao->table_name
, $dao->column_name
, $dao->id
];
2195 $cache->set($cacheKey, $fieldValues);
2197 return $fieldValues;
2201 * Get custom option groups.
2203 * @deprecated Use the API OptionGroup.get
2205 * @param array $includeFieldIds
2206 * Ids of custom fields for which option groups must be included.
2208 * Currently this is required in the cases where option groups are to be included
2209 * for inactive fields : CRM-5369
2213 public static function customOptionGroup($includeFieldIds = NULL) {
2214 static $customOptionGroup = NULL;
2216 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2217 if ($cacheKey == 'force') {
2218 $customOptionGroup[$cacheKey] = NULL;
2221 if (empty($customOptionGroup[$cacheKey])) {
2222 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2224 //support for single as well as array format.
2225 if (!empty($includeFieldIds)) {
2226 if (is_array($includeFieldIds)) {
2227 $includeFieldIds = implode(',', $includeFieldIds);
2229 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2233 SELECT g.id, g.title
2234 FROM civicrm_option_group g
2235 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2236 WHERE {$whereClause}";
2238 $dao = CRM_Core_DAO
::executeQuery($query);
2239 while ($dao->fetch()) {
2240 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2244 return $customOptionGroup[$cacheKey];
2248 * Get defaults for new entity.
2252 public static function getDefaults() {
2254 'is_required' => FALSE,
2255 'is_searchable' => FALSE,
2256 'in_selector' => FALSE,
2257 'is_search_range' => FALSE,
2258 //CRM-15792 - Custom field gets disabled if is_active not set
2259 // this would ideally be a mysql default.
2260 'is_active' => TRUE,
2266 * Fix orphan groups.
2268 * @param int $customFieldId
2270 * @param int $optionGroupId
2273 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2274 // check if option group belongs to any custom Field else delete
2275 // get the current option group
2276 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2280 // get the updated option group
2281 // if both are same return
2282 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2286 // check if option group is related to any other field
2287 self
::checkOptionGroup($currentOptionGroupId);
2291 * Check if option group is related to more than one custom field.
2293 * @param int $optionGroupId
2296 public static function checkOptionGroup($optionGroupId) {
2299 FROM civicrm_custom_field
2300 WHERE option_group_id = {$optionGroupId}";
2302 $count = CRM_Core_DAO
::singleValueQuery($query);
2305 //delete the option group
2306 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2311 * Get option group default.
2313 * @param int $optionGroupId
2314 * @param bool $serialize
2316 * @return null|string
2318 public static function getOptionGroupDefault($optionGroupId, $serialize) {
2320 SELECT default_value, serialize
2321 FROM civicrm_custom_field
2322 WHERE option_group_id = {$optionGroupId}
2323 AND default_value IS NOT NULL";
2325 $dao = CRM_Core_DAO
::executeQuery($query);
2326 while ($dao->fetch()) {
2327 if ($dao->serialize
== $serialize) {
2328 return $dao->default_value
;
2330 $defaultValue = $dao->default_value
;
2333 // Convert serialization
2334 if (isset($defaultValue) && $serialize) {
2335 return CRM_Utils_Array
::implodePadded([$defaultValue]);
2337 elseif (isset($defaultValue)) {
2338 return CRM_Utils_Array
::explodePadded($defaultValue)[0];
2344 * Post process function.
2346 * @param array $params
2347 * @param int $entityID
2348 * @param string $customFieldExtends
2349 * @param bool $inline
2350 * @param bool $checkPermissions
2354 public static function postProcess(
2357 $customFieldExtends,
2359 $checkPermissions = TRUE
2363 foreach ($params as $key => $value) {
2364 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2366 // for autocomplete transfer hidden value instead of label
2367 if ($params[$key] && isset($params[$key . '_id'])) {
2368 $value = $params[$key . '_id'];
2371 // we need to append time with date
2372 if ($params[$key] && isset($params[$key . '_time'])) {
2373 $value .= ' ' . $params[$key . '_time'];
2376 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2379 $customFieldExtends,
2380 $customFieldInfo[1],
2391 * Get custom field ID from field/group name/title.
2393 * @param string $fieldName Field name or label
2394 * @param string|null $groupName (Optional) Group name or label
2395 * @param bool $fullString Whether to return "custom_123" or "123"
2397 * @return string|int|null
2398 * @throws \CiviCRM_API3_Exception
2400 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2401 $cacheKey = $groupName . '.' . $fieldName;
2402 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2403 $customFieldParams = [
2404 'name' => $fieldName,
2405 'label' => $fieldName,
2406 'options' => ['or' => [["name", "label"]]],
2410 $customFieldParams['custom_group_id.name'] = $groupName;
2411 $customFieldParams['custom_group_id.title'] = $groupName;
2412 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2415 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2417 if (empty($field['id'])) {
2418 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2419 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2422 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2423 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2428 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2430 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2434 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2440 public static function getNameFromID($ids) {
2441 if (is_array($ids)) {
2442 $ids = implode(',', $ids);
2445 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2446 FROM civicrm_custom_field f
2447 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2448 WHERE f.id IN ($ids)";
2450 $dao = CRM_Core_DAO
::executeQuery($sql);
2452 while ($dao->fetch()) {
2453 $result[$dao->id
] = [
2454 'field_name' => $dao->field_name
,
2455 'field_label' => $dao->field_label
,
2456 'group_name' => $dao->group_name
,
2457 'group_title' => $dao->group_title
,
2464 * Validate custom data.
2466 * @param array $params
2467 * Custom data submitted.
2468 * ie array( 'custom_1' => 'validate me' );
2471 * validation errors.
2473 public static function validateCustomData($params) {
2475 if (!is_array($params) ||
empty($params)) {
2479 //pick up profile fields.
2480 $profileFields = [];
2481 $ufGroupId = $params['ufGroupId'] ??
NULL;
2483 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2485 CRM_Core_Action
::VIEW
2489 //lets start w/ params.
2490 foreach ($params as $key => $value) {
2491 $customFieldID = self
::getKeyID($key);
2492 if (!$customFieldID) {
2496 //load the structural info for given field.
2497 $field = new CRM_Core_DAO_CustomField();
2498 $field->id
= $customFieldID;
2499 if (!$field->find(TRUE)) {
2502 $dataType = $field->data_type
;
2504 $profileField = CRM_Utils_Array
::value($key, $profileFields, []);
2505 $fieldTitle = $profileField['title'] ??
NULL;
2506 $isRequired = $profileField['is_required'] ??
NULL;
2508 $fieldTitle = $field->label
;
2511 //no need to validate.
2512 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2516 //lets validate first for required field.
2517 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2518 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
2522 //now time to take care of custom field form rules.
2523 $ruleName = $errorMsg = NULL;
2524 switch ($dataType) {
2526 $ruleName = 'integer';
2527 $errorMsg = ts('%1 must be an integer (whole number).',
2528 array(1 => $fieldTitle)
2533 $ruleName = 'money';
2534 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2535 array(1 => $fieldTitle)
2540 $ruleName = 'numeric';
2541 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2542 array(1 => $fieldTitle)
2547 $ruleName = 'wikiURL';
2548 $errorMsg = ts('%1 must be valid Website.',
2549 array(1 => $fieldTitle)
2554 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2556 $funName = "CRM_Utils_Rule::{$ruleName}";
2557 if (is_callable($funName)) {
2558 $valid = call_user_func($funName, $value);
2561 $errors[$key] = $errorMsg;
2570 * Is this field a multi record field.
2572 * @param int $customId
2576 public static function isMultiRecordField($customId) {
2577 $isMultipleWithGid = FALSE;
2578 if (!is_numeric($customId)) {
2579 $customId = self
::getKeyID($customId);
2581 if (is_numeric($customId)) {
2582 $sql = "SELECT cg.id cgId
2583 FROM civicrm_custom_group cg
2584 INNER JOIN civicrm_custom_field cf
2585 ON cg.id = cf.custom_group_id
2586 WHERE cf.id = %1 AND cg.is_multiple = 1";
2587 $params[1] = [$customId, 'Integer'];
2588 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2589 if ($dao->fetch()) {
2591 $isMultipleWithGid = $dao->cgId
;
2596 return $isMultipleWithGid;
2600 * Does this field type have any select options?
2602 * @param array $field
2606 public static function hasOptions($field) {
2607 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2608 $field = (array) $field;
2609 // This will include boolean fields with Yes/No options.
2610 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2613 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2614 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2615 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2618 if (strpos($field['html_type'], 'Select') !== FALSE) {
2621 return !empty($field['option_group_id']);
2625 * Does this field store a serialized string?
2627 * @param CRM_Core_DAO_CustomField|array $field
2631 public static function isSerialized($field) {
2632 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2633 $html_type = is_object($field) ?
$field->html_type
: $field['html_type'];
2634 // APIv3 has a "legacy" mode where it returns old-style html_type of "Multi-Select"
2635 // If anyone is using this function in conjunction with legacy api output, we'll accomodate:
2636 if ($html_type === 'CheckBox' ||
strpos($html_type, 'Multi') !== FALSE) {
2639 // Otherwise this is the new standard as of 5.27
2640 return is_object($field) ?
!empty($field->serialize
) : !empty($field['serialize']);
2644 * Get api entity for this field
2648 public function getEntity() {
2649 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2650 return in_array($entity, ['Individual', 'Household', 'Organization']) ?
'Contact' : $entity;
2654 * Set pseudoconstant properties for field metadata.
2656 * @param array $field
2657 * @param string|null $optionGroupName
2659 private static function getOptionsForField(&$field, $optionGroupName) {
2660 if ($optionGroupName) {
2661 $field['pseudoconstant'] = [
2662 'optionGroupName' => $optionGroupName,
2663 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2666 elseif ($field['data_type'] == 'Boolean') {
2667 $field['pseudoconstant'] = [
2668 'callback' => 'CRM_Core_SelectValues::boolean',
2671 elseif ($field['data_type'] == 'Country') {
2672 $field['pseudoconstant'] = [
2673 'table' => 'civicrm_country',
2674 'keyColumn' => 'id',
2675 'labelColumn' => 'name',
2676 'nameColumn' => 'iso_code',
2679 elseif ($field['data_type'] == 'StateProvince') {
2680 $field['pseudoconstant'] = [
2681 'table' => 'civicrm_state_province',
2682 'keyColumn' => 'id',
2683 'labelColumn' => 'name',
2689 * @param CRM_Core_DAO_CustomField $field
2690 * @param 'add|modify|delete' $operation
2694 protected static function prepareCreateParams($field, $operation) {
2695 $tableName = CRM_Core_DAO
::getFieldValue(
2696 'CRM_Core_DAO_CustomGroup',
2697 $field->custom_group_id
,
2702 'table_name' => $tableName,
2703 'operation' => $operation,
2704 'name' => $field->column_name
,
2705 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2709 'required' => $field->is_required
,
2710 'searchable' => $field->is_searchable
,
2713 // For adding/dropping FK constraints
2714 $params['fkName'] = CRM_Core_BAO_SchemaHandler
::getIndexName($tableName, $field->column_name
);
2717 'Country' => 'civicrm_country',
2718 'StateProvince' => 'civicrm_state_province',
2719 'ContactReference' => 'civicrm_contact',
2720 'File' => 'civicrm_file',
2722 if (isset($fkFields[$field->data_type
])) {
2723 // Serialized fields store value-separated strings which are incompatible with FK constraints
2724 if (!$field->serialize
) {
2725 $params['fk_table_name'] = $fkFields[$field->data_type
];
2726 $params['fk_field_name'] = 'id';
2727 $params['fk_attributes'] = 'ON DELETE SET NULL';
2730 if ($field->serialize
) {
2731 $params['type'] = 'varchar(255)';
2733 if (isset($field->default_value
)) {
2734 $params['default'] = "'{$field->default_value}'";