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 * 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);
248 public static function buildOptions($fieldName, $context = NULL, $props = []) {
249 $options = parent
::buildOptions($fieldName, $context, $props);
250 // This provides legacy support for APIv3, allowing no-longer-existent html types
251 if ($fieldName == 'html_type' && isset($props['version']) && $props['version'] == 3) {
252 $options['Multi-Select'] = 'Multi-Select';
253 $options['Select Country'] = 'Select Country';
254 $options['Multi-Select Country'] = 'Multi-Select Country';
255 $options['Select State/Province'] = 'Select State/Province';
256 $options['Multi-Select State/Province'] = 'Multi-Select State/Province';
262 * Store and return an array of all active custom fields.
264 * @param string $customDataType
265 * Type of Custom Data; 'ANY' is a synonym for "all contact data types".
266 * @param bool $showAll
267 * If true returns all fields (includes disabled fields).
268 * @param bool $inline
269 * If true returns all inline fields (includes disabled fields).
270 * @param int $customDataSubType
271 * Custom Data sub type value.
272 * @param int $customDataSubName
273 * Custom Data sub name value.
274 * @param bool $onlyParent
275 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
276 * @param bool $onlySubType
277 * Return only custom data for subtype.
278 * @param bool $checkPermission
279 * If false, do not include permissioning clause.
282 * an array of active custom fields.
283 * @throws \CRM_Core_Exception
285 public static function &getFields(
286 $customDataType = 'Individual',
289 $customDataSubType = NULL,
290 $customDataSubName = NULL,
292 $onlySubType = FALSE,
293 $checkPermission = TRUE
295 if (empty($customDataType)) {
296 $customDataType = ['Contact', 'Individual', 'Organization', 'Household'];
298 if ($customDataType === 'ANY') {
299 // NULL should have been respected but the line above broke that.
300 // boo for us not having enough unit tests back them.
301 $customDataType = NULL;
303 if ($customDataType && !is_array($customDataType)) {
305 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
306 // This is the case when getFieldsForImport() requires fields
307 // limited strictly to a subtype.
308 $customDataSubType = $customDataType;
309 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
313 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
314 // this makes the method flexible to support retrieving fields
315 // for multiple extends value.
316 $customDataType = [$customDataType];
320 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
322 if (is_array($customDataType)) {
323 $cacheKey = implode('_', $customDataType);
326 $cacheKey = $customDataType;
329 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
330 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
331 $cacheKey .= $showAll ?
'_1' : '_0';
332 $cacheKey .= $inline ?
'_1_' : '_0_';
333 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
334 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
335 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
336 $cacheKey .= '_' . CRM_Core_Config
::domainID() . '_';
338 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
340 // also get the permission stuff here
341 if ($checkPermission) {
342 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
347 $permissionClause = '(1)';
350 // lets md5 permission clause and take first 8 characters
351 $cacheKey .= substr(md5($permissionClause), 0, 8);
353 if (strlen($cacheKey) > 40) {
354 $cacheKey = md5($cacheKey);
357 if (!self
::$_importFields ||
358 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
360 if (!self
::$_importFields) {
361 self
::$_importFields = [];
364 // check if we can retrieve from database cache
365 $fields = Civi
::Cache('fields')->get("custom importableFields $cacheKey");
367 if ($fields === NULL) {
368 $cfTable = self
::getTableName();
371 if (is_array($customDataType)) {
373 foreach ($customDataType as $dataType) {
374 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
375 if (in_array($dataType, ['Individual', 'Household', 'Organization'])) {
376 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
379 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
381 $value = $value ?
$value . ", {$val}" : $val;
385 $extends = "AND $cgTable.extends IN ( $value ) ";
389 if (!empty($customDataType) && empty($extends)) {
390 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
391 self
::$_importFields[$cacheKey] = [];
392 return self
::$_importFields[$cacheKey];
396 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
398 // Temporary hack - in 5.27 a new field is added to civicrm_custom_field. There is a high
399 // risk this function is called before the upgrade page can be reached and if
400 // so it will potentially result in fatal error.
401 $serializeField = CRM_Core_BAO_Domain
::isDBVersionAtLeast('5.27.alpha1') ?
"$cfTable.serialize," : '';
403 $query = "SELECT $cfTable.id, $cfTable.label,
407 $cfTable.default_value,
408 $cfTable.options_per_line, $cfTable.text_length,
409 $cfTable.custom_group_id,
410 $cfTable.is_required,
411 $cfTable.column_name,
412 $cgTable.extends, $cfTable.is_search_range,
413 $cgTable.extends_entity_column_value,
414 $cgTable.extends_entity_column_id,
416 $cfTable.option_group_id,
417 $cfTable.date_format,
418 $cfTable.time_format,
419 $cgTable.is_multiple,
422 og.name as option_group_name
425 ON $cfTable.custom_group_id = $cgTable.id
426 LEFT JOIN civicrm_option_group og
427 ON $cfTable.option_group_id = og.id
431 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
435 $query .= " AND $cgTable.style = 'Inline' ";
438 //get the custom fields for specific type in
439 //combination with fields those support any type.
440 if (!empty($customDataSubType)) {
442 foreach ($customDataSubType as $subtype) {
443 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($subtype, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
;
444 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
447 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
449 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
452 if ($customDataSubName) {
453 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
456 // also get the permission stuff here
457 if ($checkPermission) {
458 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
463 $permissionClause = '(1)';
466 $query .= " $extends AND $permissionClause
467 ORDER BY $cgTable.weight, $cgTable.title,
468 $cfTable.weight, $cfTable.label";
470 $dao = CRM_Core_DAO
::executeQuery($query);
473 while (($dao->fetch()) != NULL) {
474 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
475 $fields[$dao->id
]['id'] = $dao->id
;
476 $fields[$dao->id
]['label'] = $dao->label
;
477 // This seems broken, but not in a new way.
478 $fields[$dao->id
]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
479 // To support the consolidation of various functions & their expectations.
480 $fields[$dao->id
]['title'] = $dao->label
;
481 $fields[$dao->id
]['custom_field_id'] = $dao->id
;
482 $fields[$dao->id
]['groupTitle'] = $dao->title
;
483 $fields[$dao->id
]['data_type'] = $dao->data_type
;
484 $fields[$dao->id
]['name'] = 'custom_' . $dao->id
;
485 $fields[$dao->id
]['type'] = CRM_Utils_Array
::value($dao->data_type
, self
::dataToType());
486 $fields[$dao->id
]['html_type'] = $dao->html_type
;
487 $fields[$dao->id
]['default_value'] = $dao->default_value
;
488 $fields[$dao->id
]['text_length'] = $dao->text_length
;
489 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
490 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
491 $fields[$dao->id
]['extends'] = $dao->extends;
492 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
493 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
494 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
495 $fields[$dao->id
]['is_view'] = $dao->is_view
;
496 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
497 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
498 $fields[$dao->id
]['date_format'] = $dao->date_format
;
499 $fields[$dao->id
]['time_format'] = $dao->time_format
;
500 $fields[$dao->id
]['is_required'] = $dao->is_required
;
501 $fields[$dao->id
]['table_name'] = $dao->table_name
;
502 $fields[$dao->id
]['column_name'] = $dao->column_name
;
503 $fields[$dao->id
]['serialize'] = $serializeField ?
$dao->serialize
: (int) self
::isSerialized($dao);
504 $fields[$dao->id
]['where'] = $dao->table_name
. '.' . $dao->column_name
;
505 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
506 $fields[$dao->id
]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery
::$extendsMap) ? CRM_Core_BAO_CustomQuery
::$extendsMap[$dao->extends] : '';
507 if (in_array($dao->extends, CRM_Contact_BAO_ContactType
::subTypes())) {
508 // if $extends is a subtype, refer contact table
509 $fields[$dao->id
]['extends_table'] = 'civicrm_contact';
511 // Search table is used by query object searches..
512 $fields[$dao->id
]['search_table'] = ($fields[$dao->id
]['extends_table'] == 'civicrm_contact') ?
'contact_a' : $fields[$dao->id
]['extends_table'];
513 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
516 Civi
::cache('fields')->set("custom importableFields $cacheKey", $fields);
518 self
::$_importFields[$cacheKey] = $fields;
521 return self
::$_importFields[$cacheKey];
525 * Return the field ids and names (with groups) for import purpose.
527 * @param int|string $contactType Contact type
528 * @param bool $showAll
529 * If true returns all fields (includes disabled fields).
530 * @param bool $onlyParent
531 * Return fields ONLY related to basic types.
532 * @param bool $search
533 * When called from search and multiple records need to be returned.
534 * @param bool $checkPermission
535 * If false, do not include permissioning clause.
537 * @param bool $withMultiple
541 public static function getFieldsForImport(
542 $contactType = 'Individual',
546 $checkPermission = TRUE,
547 $withMultiple = FALSE
549 // Note: there are situations when we want getFieldsForImport() return fields related
550 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
551 $fields = &self
::getFields($contactType,
561 $importableFields = [];
562 foreach ($fields as $id => $values) {
563 // for now we should not allow multiple fields in profile / export etc, hence unsetting
565 (!empty($values['is_multiple']) && !$withMultiple)
569 if (!empty($values['text_length'])) {
570 $values['maxlength'] = (int) $values['text_length'];
573 /* generate the key for the fields array */
576 $importableFields[$key] = $values;
577 $importableFields[$key]['import'] = 1;
580 return $importableFields;
584 * Get the field id from an import key.
594 public static function getKeyID($key, $all = FALSE) {
596 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
603 CRM_Utils_Array
::value(2, $match),
607 return $all ?
[NULL, NULL] : NULL;
611 * Use the cache to get all values of a specific custom field.
613 * @param int $fieldID
614 * The custom field ID.
616 * @return CRM_Core_BAO_CustomField
618 * @throws CRM_Core_Exception
620 public static function getFieldObject($fieldID) {
621 $field = new CRM_Core_BAO_CustomField();
623 // check if we can get the field values from the system cache
624 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
625 $cache = CRM_Utils_Cache
::singleton();
626 $fieldValues = $cache->get($cacheKey);
627 if (empty($fieldValues)) {
628 $field->id
= $fieldID;
629 if (!$field->find(TRUE)) {
630 throw new CRM_Core_Exception('Cannot find Custom Field');
634 CRM_Core_DAO
::storeValues($field, $fieldValues);
636 $cache->set($cacheKey, $fieldValues);
639 $field->copyValues($fieldValues);
646 * Add a custom field to an existing form.
648 * @param CRM_Core_Form $qf
649 * Form object (reference).
650 * @param string $elementName
651 * Name of the custom field.
652 * @param int $fieldId
653 * @param bool $useRequired
654 * True if required else false.
655 * @param bool $search
656 * True if used for search else false.
657 * @param string $label
658 * Label for custom field.
659 * @return \HTML_QuickForm_Element|null
660 * @throws \CiviCRM_API3_Exception
662 public static function addQuickFormElement(
663 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
665 $field = self
::getFieldObject($fieldId);
666 $widget = $field->html_type
;
668 $customFieldAttributes = [];
670 // Custom field HTML should indicate group+field name
671 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
672 $dataCrmCustomVal = $groupName . ':' . $field->name
;
673 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
674 $field->attributes
.= $dataCrmCustomAttr;
676 // Fixed for Issue CRM-2183
677 if ($widget == 'TextArea' && $search) {
681 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
683 $isSelect = (in_array($widget, [
690 $options = $field->getOptions($search ?
'search' : 'create');
692 // Consolidate widget types to simplify the below switch statement
693 if ($search ||
(strpos($widget, 'Select') !== FALSE)) {
697 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
698 $selectAttributes = ['class' => 'crm-select2'];
700 // Search field is always multi-select
701 if ($search ||
(self
::isSerialized($field) && $widget === 'Select')) {
702 $selectAttributes['class'] .= ' huge';
703 $selectAttributes['multiple'] = 'multiple';
704 $selectAttributes['placeholder'] = $placeholder;
707 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
708 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
709 if ($field->option_group_id
&& !$search && $isSelect && $canEditOptions) {
710 $customFieldAttributes +
= [
711 'data-api-entity' => $field->getEntity(),
712 'data-api-field' => 'custom_' . $field->id
,
713 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
715 $selectAttributes +
= $customFieldAttributes;
719 $rangeDataTypes = ['Int', 'Float', 'Money'];
721 if (!isset($label)) {
722 $label = $field->label
;
725 // at some point in time we might want to split the below into small functions
730 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
731 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
732 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
735 if ($field->text_length
) {
736 $field->attributes
.= ' maxlength=' . $field->text_length
;
737 if ($field->text_length
< 20) {
738 $field->attributes
.= ' size=' . $field->text_length
;
741 $element = $qf->add('text', $elementName, $label,
743 $useRequired && !$search
749 $attributes = $dataCrmCustomAttr;
750 if ($field->note_rows
) {
751 $attributes .= 'rows=' . $field->note_rows
;
754 $attributes .= 'rows=4';
756 if ($field->note_columns
) {
757 $attributes .= ' cols=' . $field->note_columns
;
760 $attributes .= ' cols=60';
762 if ($field->text_length
) {
763 $attributes .= ' maxlength=' . $field->text_length
;
765 $element = $qf->add('textarea',
769 $useRequired && !$search
774 $attr = ['data-crm-custom' => $dataCrmCustomVal];
775 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
776 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
777 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
780 'date' => $field->date_format
,
781 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
782 //CRM-18487 - max date should be the last date of the year.
783 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
784 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
786 if ($field->is_search_range
&& $search) {
787 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
788 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
791 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
796 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
797 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
798 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
801 parse_str($field->attributes
, $radioAttributes);
802 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
803 if ($search ||
empty($useRequired)) {
804 $radioAttributes['allowClear'] = TRUE;
806 $qf->addRadio($elementName, $label, $options, $radioAttributes, NULL, $useRequired);
810 // For all select elements
812 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
813 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
814 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
817 if (empty($selectAttributes['multiple'])) {
818 $options = ['' => $placeholder] +
$options;
820 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
822 // Add and/or option for fields that store multiple values
823 if ($search && self
::isSerialized($field)) {
824 $qf->addRadio($elementName . '_operator', '', [
827 ], [], NULL, FALSE, [
828 'or' => ['title' => ts('Results may contain any of the selected options')],
829 'and' => ['title' => ts('Results must have all of the selected options')],
831 $qf->setDefaults([$elementName . '_operator' => 'or']);
838 foreach ($options as $v => $l) {
839 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
842 $group = $element = $qf->addGroup($check, $elementName, $label);
843 $optionEditKey = 'data-option-edit-path';
844 if (isset($customFieldAttributes[$optionEditKey])) {
845 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
848 if ($useRequired && !$search) {
849 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
854 // we should not build upload file in search mode
859 strtolower($field->html_type
),
863 $useRequired && !$search
865 $qf->addUploadElement($elementName);
868 case 'RichTextEditor':
870 'rows' => $field->note_rows
,
871 'cols' => $field->note_columns
,
872 'data-crm-custom' => $dataCrmCustomVal,
874 if ($field->text_length
) {
875 $attributes['maxlength'] = $field->text_length
;
877 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
880 case 'Autocomplete-Select':
881 static $customUrls = [];
882 // Fixme: why is this a string in the first place??
884 if ($field->attributes
) {
885 foreach (explode(' ', $field->attributes
) as $at) {
886 if (strpos($at, '=')) {
887 list($k, $v) = explode('=', $at);
888 $attributes[$k] = trim($v, ' "');
892 if ($field->data_type
== 'ContactReference') {
893 // break if contact does not have permission to access ContactReference
894 if (!CRM_Core_Permission
::check('access contact reference fields')) {
897 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
898 $attributes['data-api-entity'] = 'Contact';
899 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
901 $urlParams = "context=customfield&id={$field->id}";
902 $idOfelement = $elementName;
903 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
904 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
905 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
906 // rather than layering on more hacks.
907 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
908 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') +
1)), 0, -1);
910 $customUrls[$idOfelement] = CRM_Utils_System
::url('civicrm/ajax/contactref',
917 // FIXME: This won't work with customFieldOptions hook
919 'entity' => 'OptionValue',
920 'placeholder' => $placeholder,
921 'multiple' => $search ?
TRUE : !empty($field->serialize
),
923 'params' => ['option_group_id' => $field->option_group_id
, 'is_active' => 1],
926 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
929 $qf->assign('customUrls', $customUrls);
933 switch ($field->data_type
) {
935 // integers will have numeric rule applied to them.
936 if ($field->is_search_range
&& $search) {
937 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', [1 => $label]), 'integer');
938 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', [1 => $label]), 'integer');
940 elseif ($widget == 'Text') {
941 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', [1 => $label]), 'integer');
946 if ($field->is_search_range
&& $search) {
947 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', [1 => $label]), 'numeric');
948 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', [1 => $label]), 'numeric');
950 elseif ($widget == 'Text') {
951 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', [1 => $label]), 'numeric');
956 if ($field->is_search_range
&& $search) {
957 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
958 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
960 elseif ($widget == 'Text') {
961 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
966 $element->setAttribute('class', "url");
967 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
970 if ($field->is_view
&& !$search) {
971 $qf->freeze($elementName);
977 * Delete the Custom Field.
979 * @param object $field
982 public static function deleteField($field) {
983 CRM_Utils_System
::flushCache();
985 // first delete the custom option group and values associated with this field
986 if ($field->option_group_id
) {
987 //check if option group is related to any other field, if
988 //not delete the option group and related option values
989 self
::checkOptionGroup($field->option_group_id
);
992 // next drop the column from the custom value table
993 self
::createField($field, 'delete');
996 CRM_Core_BAO_UFField
::delUFField($field->id
);
997 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
999 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
1003 * @param string|int|array|null $value
1004 * @param CRM_Core_BAO_CustomField|int|array|string $field
1005 * @param int $entityId
1009 * @throws \CRM_Core_Exception
1011 public static function displayValue($value, $field, $entityId = NULL) {
1012 $field = is_array($field) ?
$field['id'] : $field;
1013 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1016 throw new CRM_Core_Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1019 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1020 $field = self
::getFieldObject($fieldId);
1023 $fieldInfo = ['options' => $field->getOptions()] +
(array) $field;
1025 $displayValue = self
::formatDisplayValue($value, $fieldInfo, $entityId);
1027 // Call hook to alter display value.
1028 CRM_Utils_Hook
::alterCustomFieldDisplayValue($displayValue, $value, $entityId, $fieldInfo);
1030 return $displayValue;
1034 * Lower-level logic for rendering a custom field value
1036 * @param string|array $value
1037 * @param array $field
1038 * @param int|null $entityId
1042 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1044 if (self
::isSerialized($field) && !is_array($value)) {
1045 $value = CRM_Utils_Array
::explodePadded($value);
1048 if ($field['html_type'] == 'CheckBox' && $value) {
1049 $value = CRM_Utils_Array
::convertCheckboxFormatToArray($value);
1052 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1054 switch ($field['html_type']) {
1057 case 'Autocomplete-Select':
1060 if ($field['data_type'] == 'ContactReference' && $value) {
1061 if (is_numeric($value)) {
1062 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1068 elseif (is_array($value)) {
1070 foreach ($value as $key => $val) {
1071 $v[] = $field['options'][$val] ??
NULL;
1073 $display = implode(', ', $v);
1076 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1077 // For float type (see Number and Money) $value would be decimal like
1078 // 1.00 (because it is stored in db as decimal), while options array
1079 // key would be integer like 1. In this case expression on line above
1080 // would return empty string (default value), despite the fact that
1081 // matching option exists in the array.
1082 // In such cases we could just get intval($value) and fetch matching
1083 // option again, but this would not work if key is float like 5.6.
1084 // So we need to truncate trailing zeros to make it work as expected.
1085 if ($display === '' && strpos($value, '.') !== FALSE) {
1086 // Use round() to truncate trailing zeros, e.g:
1087 // 10.00 -> 10, 10.60 -> 10.6, 10.69 -> 10.69.
1088 $value = (string) round($value, 5);
1089 $display = $field['options'][$value] ??
'';
1095 $customFormat = NULL;
1097 // FIXME: Are there any legitimate reasons why $value would be an array?
1098 // Or should we throw an exception here if it is?
1099 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1101 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1102 $format = $field['date_format'] ??
NULL;
1105 if (array_key_exists($format, $actualPHPFormats)) {
1106 $customTimeFormat = (array) $actualPHPFormats[$format];
1107 switch (CRM_Utils_Array
::value('time_format', $field)) {
1109 $customTimeFormat[] = 'g:iA';
1113 $customTimeFormat[] = 'G:i';
1117 //If time is not selected remove time from value.
1118 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1120 $customFormat = implode(" ", $customTimeFormat);
1123 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1127 // In the context of displaying a profile, show file/image
1130 if (CRM_Utils_Rule
::positiveInteger($value)) {
1134 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1136 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1138 $display = $url['file_url'];
1142 // In other contexts show a paperclip icon
1143 if (CRM_Utils_Rule
::integer($value)) {
1144 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1146 $file_description = '';
1148 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1150 catch (CiviCRM_API3_Exception
$dontcare) {
1154 $display = "{$icons[$value]}{$file_description}";
1157 //CRM-18396, if filename is passed instead
1165 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1169 $display = nl2br($display);
1173 if ($field['data_type'] == 'Money' && isset($value)) {
1174 // $value can also be an array(while using IN operator from search builder or api).
1175 foreach ((array) $value as $val) {
1176 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1178 $display = implode(', ', $disp);
1186 * Set default values for custom data used in profile.
1188 * @param int $customFieldId
1190 * @param string $elementName
1191 * Custom field name.
1192 * @param array $defaults
1193 * Associated array of fields.
1194 * @param int $contactId
1198 * @param mixed $value
1199 * If passed - dont fetch value from db,.
1200 * just format the given value
1202 public static function setProfileDefaults(
1210 //get the type of custom field
1211 $customField = new CRM_Core_BAO_CustomField();
1212 $customField->id
= $customFieldId;
1213 $customField->find(TRUE);
1216 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1217 $value = $customField->default_value
;
1221 if (!isset($value)) {
1222 $info = self
::getTableColumnGroup($customFieldId);
1223 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1224 $result = CRM_Core_DAO
::executeQuery($query);
1225 if ($result->fetch()) {
1226 $value = $result->value
;
1230 if ($customField->data_type
== 'Country') {
1232 $config = CRM_Core_Config
::singleton();
1233 if ($config->defaultContactCountry
) {
1234 $value = CRM_Core_BAO_Country
::defaultContactCountry();
1240 //set defaults if mode is registration
1241 if (!trim($value) &&
1243 (!in_array($mode, [CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
]))
1245 $value = $customField->default_value
;
1248 if ($customField->data_type
== 'Money' && isset($value)) {
1249 $value = number_format($value, 2);
1251 if (self
::isSerialized($customField) && $value) {
1252 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1253 $defaults[$elementName] = [];
1254 $checkedValue = CRM_Utils_Array
::explodePadded($value);
1255 foreach ($customOption as $val) {
1256 if (in_array($val['value'], $checkedValue)) {
1257 if ($customField->html_type
== 'CheckBox') {
1258 $defaults[$elementName][$val['value']] = 1;
1261 $defaults[$elementName][$val['value']] = $val['value'];
1267 $defaults[$elementName] = $value;
1274 * @param int $contactID
1276 * @param int $fileID
1277 * @param bool $absolute
1279 * @param string $multiRecordWhereClause
1283 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1286 $params = ['id' => $cfID];
1288 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1289 $columnName = $defaults['column_name'];
1291 //table name of custom data
1292 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1293 $defaults['custom_group_id'],
1297 //query to fetch id from civicrm_file
1298 if ($multiRecordWhereClause) {
1299 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1302 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1304 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1309 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1314 $result['file_id'] = $fileID;
1316 if ($fileType == 'image/jpeg' ||
1317 $fileType == 'image/pjpeg' ||
1318 $fileType == 'image/gif' ||
1319 $fileType == 'image/x-png' ||
1320 $fileType == 'image/png'
1322 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1327 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1328 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1329 $url = CRM_Utils_System
::url('civicrm/file',
1330 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1331 $absolute, NULL, TRUE, TRUE
1333 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1335 // for non image files
1337 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1341 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1342 $url = CRM_Utils_System
::url('civicrm/file',
1343 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1344 $absolute, NULL, TRUE, TRUE
1346 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1354 * Format custom fields before inserting.
1356 * @param int $customFieldId
1358 * @param array $customFormatted
1360 * @param mixed $value
1361 * Value of custom field.
1362 * @param string $customFieldExtend
1363 * Custom field extends.
1364 * @param int $customValueId
1365 * Custom option value id.
1366 * @param int $entityId
1367 * Entity id (contribution, membership...).
1368 * @param bool $inline
1369 * Consider inline custom groups only.
1370 * @param bool $checkPermission
1371 * If false, do not include permissioning clause.
1372 * @param bool $includeViewOnly
1373 * If true, fields marked 'View Only' are included. Required for APIv3.
1375 * @return array|NULL
1376 * formatted custom field array
1378 public static function formatCustomField(
1379 $customFieldId, &$customFormatted, $value,
1380 $customFieldExtend, $customValueId = NULL,
1383 $checkPermission = TRUE,
1384 $includeViewOnly = FALSE
1386 //get the custom fields for the entity
1387 //subtype and basic type
1388 $customDataSubType = NULL;
1389 if ($customFieldExtend) {
1390 // This is the case when getFieldsForImport() requires fields
1391 // of subtype and its parent.CRM-5143
1392 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1393 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1394 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1395 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1396 if (is_array($customFieldExtend)) {
1397 $customFieldExtend = array_unique(array_values($customFieldExtend));
1402 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1412 if (!array_key_exists($customFieldId, $customFields)) {
1416 // return if field is a 'code' field
1417 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1421 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1423 if (!$customValueId &&
1424 // we always create new entites for is_multiple unless specified
1425 !$customFields[$customFieldId]['is_multiple'] &&
1431 WHERE entity_id={$entityId}";
1433 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1436 //fix checkbox, now check box always submits values
1437 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1439 // Note that only during merge this is not an array, and you can directly use value
1440 if (is_array($value)) {
1441 $selectedValues = [];
1442 foreach ($value as $selId => $val) {
1444 $selectedValues[] = $selId;
1447 if (!empty($selectedValues)) {
1448 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1450 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1458 elseif (self
::isSerialized($customFields[$customFieldId])) {
1459 // Select2 v3 returns a comma-separated string.
1460 if ($customFields[$customFieldId]['html_type'] == 'Autocomplete-Select' && is_string($value)) {
1461 $value = explode(',', $value);
1464 $value = $value ? CRM_Utils_Array
::implodePadded($value) : '';
1467 if (self
::isSerialized($customFields[$customFieldId]) &&
1468 $customFields[$customFieldId]['data_type'] == 'String' &&
1469 !empty($customFields[$customFieldId]['text_length']) &&
1472 // lets make sure that value is less than the length, else we'll
1473 // be losing some data, CRM-7481
1474 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1475 // need to do a few things here
1477 // 1. lets find a new length
1478 $newLength = $customFields[$customFieldId]['text_length'];
1479 $minLength = strlen($value);
1480 while ($newLength < $minLength) {
1481 $newLength = $newLength * 2;
1484 // set the custom field meta data to have a length larger than value
1485 // alter the custom value table column to match this length
1486 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1491 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1492 if (!CRM_Utils_System
::isNull($value)) {
1493 $format = $customFields[$customFieldId]['date_format'];
1494 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1499 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1500 $customFields[$customFieldId]['data_type'] == 'Money'
1506 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1507 $value = CRM_Utils_Rule
::cleanMoney($value);
1511 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1512 $customFields[$customFieldId]['data_type'] == 'Country'
1522 if ($customFields[$customFieldId]['data_type'] == 'File') {
1523 if (empty($value)) {
1527 $config = CRM_Core_Config
::singleton();
1529 // If we are already passing the file id as a value then retrieve and set the file data
1530 if (CRM_Utils_Rule
::integer($value)) {
1531 $fileDAO = new CRM_Core_DAO_File();
1532 $fileDAO->id
= $value;
1533 $fileDAO->find(TRUE);
1536 $fName = $fileDAO->uri
;
1537 $mimeType = $fileDAO->mime_type
;
1541 $fName = $value['name'];
1542 $mimeType = $value['type'];
1545 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1547 // rename this file to go into the secure directory only if
1548 // user has uploaded new file not existing verfied on the basis of $fileID
1549 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1550 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1553 if ($customValueId && empty($fileID)) {
1558 $params = [1 => [$customValueId, 'Integer']];
1559 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1562 $fileDAO = new CRM_Core_DAO_File();
1565 $fileDAO->id
= $fileID;
1568 $fileDAO->uri
= $filename;
1569 $fileDAO->mime_type
= $mimeType;
1570 $fileDAO->upload_date
= date('YmdHis');
1572 $fileID = $fileDAO->id
;
1576 if (!is_array($customFormatted)) {
1577 $customFormatted = [];
1580 if (!array_key_exists($customFieldId, $customFormatted)) {
1581 $customFormatted[$customFieldId] = [];
1585 if ($customValueId) {
1586 $index = $customValueId;
1589 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1590 $customFormatted[$customFieldId][$index] = [];
1592 $customFormatted[$customFieldId][$index] = [
1593 'id' => $customValueId > 0 ?
$customValueId : NULL,
1595 'type' => $customFields[$customFieldId]['data_type'],
1596 'custom_field_id' => $customFieldId,
1597 'custom_group_id' => $groupID,
1598 'table_name' => $tableName,
1599 'column_name' => $columnName,
1600 'file_id' => $fileID,
1601 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1604 //we need to sort so that custom fields are created in the order of entry
1605 krsort($customFormatted[$customFieldId]);
1606 return $customFormatted;
1610 * Get default custom table schema.
1612 * @param array $params
1616 public static function defaultCustomTableSchema($params) {
1617 // add the id and extends_id
1619 'name' => $params['name'],
1620 'is_multiple' => $params['is_multiple'],
1621 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1625 'type' => 'int unsigned',
1628 'attributes' => 'AUTO_INCREMENT',
1629 'comment' => 'Default MySQL primary key',
1632 'name' => 'entity_id',
1633 'type' => 'int unsigned',
1635 'comment' => 'Table that this extends',
1636 'fk_table_name' => $params['extends_name'],
1637 'fk_field_name' => 'id',
1638 'fk_attributes' => 'ON DELETE CASCADE',
1643 // If on MySQL 5.6 include ROW_FORMAT=DYNAMIC to fix unit tests
1644 $databaseVersion = CRM_Utils_SQL
::getDatabaseVersion();
1645 if (version_compare($databaseVersion, '5.7', '<') && version_compare($databaseVersion, '5.6', '>=')) {
1646 $table['attributes'] = $table['attributes'] . ' ROW_FORMAT=DYNAMIC';
1649 if (!$params['is_multiple']) {
1650 $table['indexes'] = [
1653 'field_name_1' => 'entity_id',
1661 * Create custom field.
1663 * @param CRM_Core_DAO_CustomField $field
1664 * @param string $operation
1666 public static function createField($field, $operation) {
1667 $sql = str_repeat(' ', 8);
1668 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1669 $sql .= "ALTER TABLE " . $tableName;
1670 $sql .= self
::getAlterFieldSQL($field, $operation);
1672 // CRM-7007: do not i18n-rewrite this query
1673 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1675 $config = CRM_Core_Config
::singleton();
1676 if ($config->logging
) {
1677 // CRM-16717 not sure why this was originally limited to add.
1678 // For example custom tables can have field length changes - which need to flow through to logging.
1679 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1680 if ($operation === 'add' ||
$operation === 'modify') {
1681 $logging = new CRM_Logging_Schema();
1682 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name
]]);
1686 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
1690 * @param CRM_Core_DAO_CustomField $field
1691 * @param string $operation
1695 public static function getAlterFieldSQL($field, $operation) {
1696 $indexExist = $operation === 'add' ?
FALSE : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $field->id
, 'is_searchable');
1697 $params = self
::prepareCreateParams($field, $operation);
1698 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1699 // a function only used by Custom Field creation...
1700 $params['required'] = FALSE;
1701 return CRM_Core_BAO_SchemaHandler
::getFieldAlterSQL($params, $indexExist);
1705 * Reformat existing values for a field when changing its serialize attribute
1707 * @param CRM_Core_DAO_CustomField $field
1708 * @throws CRM_Core_Exception
1710 private static function alterSerialize($field) {
1711 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1712 $col = $field->column_name
;
1713 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
1714 if ($field->serialize
) {
1715 $sql = "UPDATE `$table` SET `$col` = CONCAT('$sp', `$col`, '$sp') WHERE `$col` IS NOT NULL AND `$col` NOT LIKE '$sp%' AND `$col` != ''";
1718 $sql = "UPDATE `$table` SET `$col` = SUBSTRING_INDEX(SUBSTRING(`$col`, 2), '$sp', 1) WHERE `$col` LIKE '$sp%'";
1720 CRM_Core_DAO
::executeQuery($sql);
1724 * Determine whether it would be safe to move a field.
1726 * @param int $fieldID
1727 * FK to civicrm_custom_field.
1728 * @param int $newGroupID
1729 * FK to civicrm_custom_group.
1732 * array(string) or TRUE
1734 public static function _moveFieldValidate($fieldID, $newGroupID) {
1737 $field = new CRM_Core_DAO_CustomField();
1738 $field->id
= $fieldID;
1739 if (!$field->find(TRUE)) {
1740 $errors['fieldID'] = 'Invalid ID for custom field';
1744 $oldGroup = new CRM_Core_DAO_CustomGroup();
1745 $oldGroup->id
= $field->custom_group_id
;
1746 if (!$oldGroup->find(TRUE)) {
1747 $errors['fieldID'] = 'Invalid ID for old custom group';
1751 $newGroup = new CRM_Core_DAO_CustomGroup();
1752 $newGroup->id
= $newGroupID;
1753 if (!$newGroup->find(TRUE)) {
1754 $errors['newGroupID'] = 'Invalid ID for new custom group';
1760 FROM civicrm_custom_field a
1761 INNER JOIN civicrm_custom_field b
1763 AND a.label = b.label
1764 AND b.custom_group_id = %2
1767 1 => [$field->id
, 'Integer'],
1768 2 => [$newGroup->id
, 'Integer'],
1770 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1772 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1775 $tableName = $oldGroup->table_name
;
1776 $columnName = $field->column_name
;
1781 WHERE $columnName is not null
1783 $count = CRM_Core_DAO
::singleValueQuery($query);
1787 FROM civicrm_custom_group
1788 WHERE id IN ( %1, %2 )
1791 1 => [$oldGroup->id
, 'Integer'],
1792 2 => [$newGroup->id
, 'Integer'],
1795 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1797 while ($dao->fetch()) {
1798 $extends[] = $dao->extends;
1800 if ($extends[0] != $extends[1]) {
1801 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1805 return empty($errors) ?
TRUE : $errors;
1809 * Move a custom data field from one group (table) to another.
1811 * @param int $fieldID
1812 * FK to civicrm_custom_field.
1813 * @param int $newGroupID
1814 * FK to civicrm_custom_group.
1816 * @throws CRM_Core_Exception
1818 public static function moveField($fieldID, $newGroupID) {
1819 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1820 if (TRUE !== $validation) {
1821 throw new CRM_Core_Exception(implode(' ', $validation));
1823 $field = new CRM_Core_DAO_CustomField();
1824 $field->id
= $fieldID;
1827 $newGroup = new CRM_Core_DAO_CustomGroup();
1828 $newGroup->id
= $newGroupID;
1829 $newGroup->find(TRUE);
1831 $oldGroup = new CRM_Core_DAO_CustomGroup();
1832 $oldGroup->id
= $field->custom_group_id
;
1833 $oldGroup->find(TRUE);
1836 $add->custom_group_id
= $newGroup->id
;
1837 self
::createField($add, 'add');
1839 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, `{$field->column_name}`)
1840 SELECT entity_id, `{$field->column_name}` FROM {$oldGroup->table_name}
1841 ON DUPLICATE KEY UPDATE `{$field->column_name}` = {$oldGroup->table_name}.`{$field->column_name}`
1843 CRM_Core_DAO
::executeQuery($sql);
1846 $del->custom_group_id
= $oldGroup->id
;
1847 self
::createField($del, 'delete');
1851 CRM_Utils_System
::flushCache();
1855 * Create an option value for a custom field option group ID.
1857 * @param array $params
1858 * @param string $value
1859 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1860 * @param string $index
1861 * @param string $dataType
1863 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $index, $dataType) {
1864 if (strlen(trim($value))) {
1865 $optionValue = new CRM_Core_DAO_OptionValue();
1866 $optionValue->option_group_id
= $optionGroup->id
;
1867 $optionValue->label
= $params['option_label'][$index];
1868 $optionValue->name
= $params['option_name'][$index] ?? CRM_Utils_String
::titleToVar($params['option_label'][$index]);
1869 switch ($dataType) {
1871 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1875 $optionValue->value
= intval($value);
1879 $optionValue->value
= floatval($value);
1883 $optionValue->value
= trim($value);
1886 $optionValue->weight
= $params['option_weight'][$index];
1887 $optionValue->is_active
= $params['option_status'][$index] ??
FALSE;
1888 $optionValue->description
= $params['option_description'][$index] ??
NULL;
1889 $optionValue->color
= $params['option_color'][$index] ??
NULL;
1890 $optionValue->icon
= $params['option_icon'][$index] ??
NULL;
1891 $optionValue->save();
1896 * Prepare for the create operation.
1898 * Munge params, create the option values if needed.
1900 * This could be called by a single create or a batchCreate.
1902 * @param array $params
1906 protected static function prepareCreate($params) {
1907 $op = empty($params['id']) ?
'create' : 'edit';
1908 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1909 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1910 if ($op === 'create') {
1911 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1912 if (!isset($params['column_name'])) {
1913 // if add mode & column_name not present, calculate it.
1914 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1916 if (!isset($params['name'])) {
1917 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1921 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'column_name');
1924 $htmlType = $params['html_type'] ??
NULL;
1925 $dataType = $params['data_type'] ??
NULL;
1927 if ($htmlType === 'Select Date' && empty($params['date_format'])) {
1928 $params['date_format'] = Civi
::settings()->get('dateInputFormat');
1931 // Checkboxes are always serialized in current schema
1932 if ($htmlType == 'CheckBox') {
1933 $params['serialize'] = CRM_Core_DAO
::SERIALIZE_SEPARATOR_BOOKEND
;
1936 if (!empty($params['serialize'])) {
1937 if (isset($params['default_checkbox_option'])) {
1939 foreach (array_keys($params['default_checkbox_option']) as $k => $v) {
1940 if ($params['option_value'][$v]) {
1941 $defaultArray[] = $params['option_value'][$v];
1945 if (!empty($defaultArray)) {
1946 // also add the separator before and after the value per new convention (CRM-1604)
1947 $params['default_value'] = CRM_Utils_Array
::implodePadded($defaultArray);
1951 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])) {
1952 $params['default_value'] = $params['option_value'][$params['default_option']];
1957 // create any option group & values if required
1958 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1959 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)) {
1960 //CRM-16659: if option_value then create an option group for this custom field.
1961 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
1962 // first create an option group for this custom group
1963 $optionGroup = new CRM_Core_DAO_OptionGroup();
1964 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
1965 $optionGroup->title
= $params['label'];
1966 $optionGroup->is_active
= 1;
1967 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1968 $optionGroup->is_reserved
= 0;
1969 $optionGroup->data_type
= $dataType;
1970 $optionGroup->save();
1971 $params['option_group_id'] = $optionGroup->id
;
1972 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1973 foreach ($params['option_value'] as $k => $v) {
1974 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1980 // check for orphan option groups
1981 if (!empty($params['option_group_id'])) {
1982 if (!empty($params['id'])) {
1983 self
::fixOptionGroups($params['id'], $params['option_group_id']);
1986 // if we do not have a default value
1987 // retrieve it from one of the other custom fields which use this option group
1988 if (empty($params['default_value'])) {
1989 //don't insert only value separator as default value, CRM-4579
1990 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'], !empty($params['serialize']));
1992 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultValue))) {
1993 $params['default_value'] = $defaultValue;
1998 // Set default textarea attributes
1999 if ($op == 'create' && !isset($params['attributes']) && $htmlType == 'TextArea') {
2000 $params['attributes'] = 'rows=4, cols=60';
2006 * Create database entry for custom field and related option groups.
2008 * @param array $params
2010 * @return CRM_Core_DAO_CustomField
2012 protected static function createCustomFieldRecord($params) {
2013 $transaction = new CRM_Core_Transaction();
2014 $params = self
::prepareCreate($params);
2016 $alterSerialize = isset($params['serialize']) && !empty($params['id'])
2017 && ($params['serialize'] != CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'serialize'));
2019 $customField = new CRM_Core_DAO_CustomField();
2020 $customField->copyValues($params);
2021 $customField->save();
2023 //create/drop the index when we toggle the is_searchable flag
2024 $op = empty($params['id']) ?
'add' : 'modify';
2025 if ($op !== 'modify') {
2026 if ($params['is_append_field_id_to_column_name']) {
2027 $params['column_name'] .= "_{$customField->id}";
2029 $customField->column_name
= $params['column_name'];
2030 $customField->save();
2033 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
2034 $transaction->commit();
2036 // make sure all values are present in the object for further processing
2037 $customField->find(TRUE);
2039 if ($alterSerialize) {
2040 self
::alterSerialize($customField);
2043 return $customField;
2047 * Move custom data from one contact to another.
2049 * This is currently the start of a refactoring. The theory is each
2050 * entity could have a 'move' function with a DAO default one to fall back on.
2052 * At the moment this only does a small part of the process - ie deleting a file field that
2053 * is about to be overwritten. However, the goal is the whole process around the move for
2054 * custom data should be in here.
2056 * This is currently called by the merge class but it makes sense that api could
2057 * expose move actions as moving (e.g) contributions feels like a common
2058 * ask that should be handled by the form layer.
2060 * @param int $oldContactID
2061 * @param int $newContactID
2062 * @param int[] $fieldIDs
2063 * Optional list field ids to move.
2065 * @throws \CiviCRM_API3_Exception
2066 * @throws \Exception
2068 public function move($oldContactID, $newContactID, $fieldIDs) {
2069 if (empty($fieldIDs)) {
2072 $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'];
2074 foreach ($fieldIDs as $fieldID) {
2075 $return[] = 'custom_' . $fieldID;
2077 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2078 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2080 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2081 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2082 $fieldTypesNotHandledInMergeAttempt = ['File'];
2083 foreach ($fields as $field) {
2084 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2085 if ($field['data_type'] === 'File' && !$isMultiple) {
2086 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2087 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2089 if (!empty($oldContact['custom_' . $field['id']])) {
2090 CRM_Core_DAO
::executeQuery("
2091 UPDATE civicrm_entity_file
2092 SET entity_id = $newContactID
2093 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2097 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2098 CRM_Core_DAO
::executeQuery(
2099 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, `{$field['column_name']}`)
2100 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2101 ON DUPLICATE KEY UPDATE
2102 `{$field['column_name']}` = {$oldContact['custom_' . $field['id']]}
2109 * Get the database table name and column name for a custom field.
2111 * @param int $fieldID
2112 * The fieldID of the custom field.
2113 * @param bool $force
2114 * Force the sql to be run again (primarily used for tests).
2117 * fatal is fieldID does not exists, else array of tableName, columnName
2118 * @throws \CRM_Core_Exception
2120 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2121 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2122 $cache = CRM_Utils_Cache
::singleton();
2123 $fieldValues = $cache->get($cacheKey);
2124 if (empty($fieldValues) ||
$force) {
2126 SELECT cg.table_name, cf.column_name, cg.id
2127 FROM civicrm_custom_group cg,
2128 civicrm_custom_field cf
2129 WHERE cf.custom_group_id = cg.id
2131 $params = [1 => [$fieldID, 'Integer']];
2132 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2134 if (!$dao->fetch()) {
2135 throw new CRM_Core_Exception("Cannot find table and column information for Custom Field " . $fieldID);
2137 $fieldValues = [$dao->table_name
, $dao->column_name
, $dao->id
];
2138 $cache->set($cacheKey, $fieldValues);
2140 return $fieldValues;
2144 * Get custom option groups.
2146 * @deprecated Use the API OptionGroup.get
2148 * @param array $includeFieldIds
2149 * Ids of custom fields for which option groups must be included.
2151 * Currently this is required in the cases where option groups are to be included
2152 * for inactive fields : CRM-5369
2156 public static function customOptionGroup($includeFieldIds = NULL) {
2157 static $customOptionGroup = NULL;
2159 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2160 if ($cacheKey == 'force') {
2161 $customOptionGroup[$cacheKey] = NULL;
2164 if (empty($customOptionGroup[$cacheKey])) {
2165 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2167 //support for single as well as array format.
2168 if (!empty($includeFieldIds)) {
2169 if (is_array($includeFieldIds)) {
2170 $includeFieldIds = implode(',', $includeFieldIds);
2172 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2176 SELECT g.id, g.title
2177 FROM civicrm_option_group g
2178 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2179 WHERE {$whereClause}";
2181 $dao = CRM_Core_DAO
::executeQuery($query);
2182 while ($dao->fetch()) {
2183 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2187 return $customOptionGroup[$cacheKey];
2191 * Get defaults for new entity.
2195 public static function getDefaults() {
2197 'is_required' => FALSE,
2198 'is_searchable' => FALSE,
2199 'in_selector' => FALSE,
2200 'is_search_range' => FALSE,
2201 //CRM-15792 - Custom field gets disabled if is_active not set
2202 // this would ideally be a mysql default.
2203 'is_active' => TRUE,
2209 * Fix orphan groups.
2211 * @param int $customFieldId
2213 * @param int $optionGroupId
2216 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2217 // check if option group belongs to any custom Field else delete
2218 // get the current option group
2219 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2223 // get the updated option group
2224 // if both are same return
2225 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2229 // check if option group is related to any other field
2230 self
::checkOptionGroup($currentOptionGroupId);
2234 * Check if option group is related to more than one custom field.
2236 * @param int $optionGroupId
2239 public static function checkOptionGroup($optionGroupId) {
2242 FROM civicrm_custom_field
2243 WHERE option_group_id = {$optionGroupId}";
2245 $count = CRM_Core_DAO
::singleValueQuery($query);
2248 //delete the option group
2249 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2254 * Get option group default.
2256 * @param int $optionGroupId
2257 * @param bool $serialize
2259 * @return null|string
2261 public static function getOptionGroupDefault($optionGroupId, $serialize) {
2263 SELECT default_value, serialize
2264 FROM civicrm_custom_field
2265 WHERE option_group_id = {$optionGroupId}
2266 AND default_value IS NOT NULL";
2268 $dao = CRM_Core_DAO
::executeQuery($query);
2269 while ($dao->fetch()) {
2270 if ($dao->serialize
== $serialize) {
2271 return $dao->default_value
;
2273 $defaultValue = $dao->default_value
;
2276 // Convert serialization
2277 if (isset($defaultValue) && $serialize) {
2278 return CRM_Utils_Array
::implodePadded([$defaultValue]);
2280 elseif (isset($defaultValue)) {
2281 return CRM_Utils_Array
::explodePadded($defaultValue)[0];
2287 * Post process function.
2289 * @param array $params
2290 * @param int $entityID
2291 * @param string $customFieldExtends
2292 * @param bool $inline
2293 * @param bool $checkPermissions
2297 public static function postProcess(
2300 $customFieldExtends,
2302 $checkPermissions = TRUE
2306 foreach ($params as $key => $value) {
2307 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2309 // for autocomplete transfer hidden value instead of label
2310 if ($params[$key] && isset($params[$key . '_id'])) {
2311 $value = $params[$key . '_id'];
2314 // we need to append time with date
2315 if ($params[$key] && isset($params[$key . '_time'])) {
2316 $value .= ' ' . $params[$key . '_time'];
2319 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2322 $customFieldExtends,
2323 $customFieldInfo[1],
2334 * Get custom field ID from field/group name/title.
2336 * @param string $fieldName Field name or label
2337 * @param string|null $groupName (Optional) Group name or label
2338 * @param bool $fullString Whether to return "custom_123" or "123"
2340 * @return string|int|null
2341 * @throws \CiviCRM_API3_Exception
2343 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2344 $cacheKey = $groupName . '.' . $fieldName;
2345 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2346 $customFieldParams = [
2347 'name' => $fieldName,
2348 'label' => $fieldName,
2349 'options' => ['or' => [["name", "label"]]],
2353 $customFieldParams['custom_group_id.name'] = $groupName;
2354 $customFieldParams['custom_group_id.title'] = $groupName;
2355 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2358 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2360 if (empty($field['id'])) {
2361 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2362 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2365 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2366 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2371 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2373 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2377 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2383 public static function getNameFromID($ids) {
2384 if (is_array($ids)) {
2385 $ids = implode(',', $ids);
2388 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2389 FROM civicrm_custom_field f
2390 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2391 WHERE f.id IN ($ids)";
2393 $dao = CRM_Core_DAO
::executeQuery($sql);
2395 while ($dao->fetch()) {
2396 $result[$dao->id
] = [
2397 'field_name' => $dao->field_name
,
2398 'field_label' => $dao->field_label
,
2399 'group_name' => $dao->group_name
,
2400 'group_title' => $dao->group_title
,
2407 * Validate custom data.
2409 * @param array $params
2410 * Custom data submitted.
2411 * ie array( 'custom_1' => 'validate me' );
2414 * validation errors.
2416 public static function validateCustomData($params) {
2418 if (!is_array($params) ||
empty($params)) {
2422 //pick up profile fields.
2423 $profileFields = [];
2424 $ufGroupId = $params['ufGroupId'] ??
NULL;
2426 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2428 CRM_Core_Action
::VIEW
2432 //lets start w/ params.
2433 foreach ($params as $key => $value) {
2434 $customFieldID = self
::getKeyID($key);
2435 if (!$customFieldID) {
2439 //load the structural info for given field.
2440 $field = new CRM_Core_DAO_CustomField();
2441 $field->id
= $customFieldID;
2442 if (!$field->find(TRUE)) {
2445 $dataType = $field->data_type
;
2447 $profileField = CRM_Utils_Array
::value($key, $profileFields, []);
2448 $fieldTitle = $profileField['title'] ??
NULL;
2449 $isRequired = $profileField['is_required'] ??
NULL;
2451 $fieldTitle = $field->label
;
2454 //no need to validate.
2455 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2459 //lets validate first for required field.
2460 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2461 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
2465 //now time to take care of custom field form rules.
2466 $ruleName = $errorMsg = NULL;
2467 switch ($dataType) {
2469 $ruleName = 'integer';
2470 $errorMsg = ts('%1 must be an integer (whole number).',
2471 array(1 => $fieldTitle)
2476 $ruleName = 'money';
2477 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2478 array(1 => $fieldTitle)
2483 $ruleName = 'numeric';
2484 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2485 array(1 => $fieldTitle)
2490 $ruleName = 'wikiURL';
2491 $errorMsg = ts('%1 must be valid Website.',
2492 array(1 => $fieldTitle)
2497 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2499 $funName = "CRM_Utils_Rule::{$ruleName}";
2500 if (is_callable($funName)) {
2501 $valid = call_user_func($funName, $value);
2504 $errors[$key] = $errorMsg;
2513 * Is this field a multi record field.
2515 * @param int $customId
2519 public static function isMultiRecordField($customId) {
2520 $isMultipleWithGid = FALSE;
2521 if (!is_numeric($customId)) {
2522 $customId = self
::getKeyID($customId);
2524 if (is_numeric($customId)) {
2525 $sql = "SELECT cg.id cgId
2526 FROM civicrm_custom_group cg
2527 INNER JOIN civicrm_custom_field cf
2528 ON cg.id = cf.custom_group_id
2529 WHERE cf.id = %1 AND cg.is_multiple = 1";
2530 $params[1] = [$customId, 'Integer'];
2531 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2532 if ($dao->fetch()) {
2534 $isMultipleWithGid = $dao->cgId
;
2539 return $isMultipleWithGid;
2543 * Does this field type have any select options?
2545 * @param array $field
2549 public static function hasOptions($field) {
2550 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2551 $field = (array) $field;
2552 // This will include boolean fields with Yes/No options.
2553 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2556 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2557 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2558 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2561 if (strpos($field['html_type'], 'Select') !== FALSE) {
2564 return !empty($field['option_group_id']);
2568 * Does this field store a serialized string?
2570 * @param CRM_Core_DAO_CustomField|array $field
2574 public static function isSerialized($field) {
2575 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2576 $html_type = is_object($field) ?
$field->html_type
: $field['html_type'];
2577 // APIv3 has a "legacy" mode where it returns old-style html_type of "Multi-Select"
2578 // If anyone is using this function in conjunction with legacy api output, we'll accomodate:
2579 if ($html_type === 'CheckBox' ||
strpos($html_type, 'Multi') !== FALSE) {
2582 // Otherwise this is the new standard as of 5.27
2583 return is_object($field) ?
!empty($field->serialize
) : !empty($field['serialize']);
2587 * Get api entity for this field
2591 public function getEntity() {
2592 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2593 return in_array($entity, ['Individual', 'Household', 'Organization']) ?
'Contact' : $entity;
2597 * Set pseudoconstant properties for field metadata.
2599 * @param array $field
2600 * @param string|null $optionGroupName
2602 private static function getOptionsForField(&$field, $optionGroupName) {
2603 if ($optionGroupName) {
2604 $field['pseudoconstant'] = [
2605 'optionGroupName' => $optionGroupName,
2606 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2609 elseif ($field['data_type'] == 'Boolean') {
2610 $field['pseudoconstant'] = [
2611 'callback' => 'CRM_Core_SelectValues::boolean',
2614 elseif ($field['data_type'] == 'Country') {
2615 $field['pseudoconstant'] = [
2616 'table' => 'civicrm_country',
2617 'keyColumn' => 'id',
2618 'labelColumn' => 'name',
2619 'nameColumn' => 'iso_code',
2622 elseif ($field['data_type'] == 'StateProvince') {
2623 $field['pseudoconstant'] = [
2624 'table' => 'civicrm_state_province',
2625 'keyColumn' => 'id',
2626 'labelColumn' => 'name',
2632 * @param CRM_Core_DAO_CustomField $field
2633 * @param 'add|modify' $operation
2637 protected static function prepareCreateParams($field, $operation) {
2638 $tableName = CRM_Core_DAO
::getFieldValue(
2639 'CRM_Core_DAO_CustomGroup',
2640 $field->custom_group_id
,
2645 'table_name' => $tableName,
2646 'operation' => $operation,
2647 'name' => $field->column_name
,
2648 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2652 'required' => $field->is_required
,
2653 'searchable' => $field->is_searchable
,
2656 if ($operation == 'delete') {
2657 $fkName = "{$tableName}_{$field->column_name}";
2658 if (strlen($fkName) >= 48) {
2659 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2661 $params['fkName'] = $fkName;
2663 if ($field->data_type
== 'Country' && !self
::isSerialized($field)) {
2664 $params['fk_table_name'] = 'civicrm_country';
2665 $params['fk_field_name'] = 'id';
2666 $params['fk_attributes'] = 'ON DELETE SET NULL';
2668 elseif ($field->data_type
== 'StateProvince' && !self
::isSerialized($field)) {
2669 $params['fk_table_name'] = 'civicrm_state_province';
2670 $params['fk_field_name'] = 'id';
2671 $params['fk_attributes'] = 'ON DELETE SET NULL';
2673 elseif ($field->data_type
== 'StateProvince' ||
$field->data_type
== 'Country') {
2674 $params['type'] = 'varchar(255)';
2676 elseif ($field->data_type
== 'File') {
2677 $params['fk_table_name'] = 'civicrm_file';
2678 $params['fk_field_name'] = 'id';
2679 $params['fk_attributes'] = 'ON DELETE SET NULL';
2681 elseif ($field->data_type
== 'ContactReference') {
2682 $params['fk_table_name'] = 'civicrm_contact';
2683 $params['fk_field_name'] = 'id';
2684 $params['fk_attributes'] = 'ON DELETE SET NULL';
2686 if (isset($field->default_value
)) {
2687 $params['default'] = "'{$field->default_value}'";