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_' . CRM_Core_Session
::getLoggedInContactID() . '_' : '_0_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) {
370 if (is_array($customDataType)) {
372 foreach ($customDataType as $dataType) {
373 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
374 if (in_array($dataType, ['Individual', 'Household', 'Organization'])) {
375 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
378 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
380 $value = $value ?
$value . ", {$val}" : $val;
384 $extends = "AND $cgTable.extends IN ( $value ) ";
388 if (!empty($customDataType) && empty($extends)) {
389 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
390 self
::$_importFields[$cacheKey] = [];
391 return self
::$_importFields[$cacheKey];
395 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
397 // Temporary hack - in 5.27 a new field is added to civicrm_custom_field. There is a high
398 // risk this function is called before the upgrade page can be reached and if
399 // so it will potentially result in fatal error.
400 $serializeField = CRM_Core_BAO_Domain
::isDBVersionAtLeast('5.27.alpha1') ?
"custom_field.serialize," : '';
402 $query = "SELECT custom_field.id, custom_field.label,
404 custom_field.data_type,
405 custom_field.html_type,
406 custom_field.default_value,
407 custom_field.options_per_line, custom_field.text_length,
408 custom_field.custom_group_id,
409 custom_field.is_required,
410 custom_field.column_name,
411 $cgTable.extends, custom_field.is_search_range,
412 $cgTable.extends_entity_column_value,
413 $cgTable.extends_entity_column_id,
414 custom_field.is_view,
415 custom_field.option_group_id,
416 custom_field.date_format,
417 custom_field.time_format,
418 $cgTable.is_multiple,
421 og.name as option_group_name
422 FROM civicrm_custom_field custom_field
424 ON custom_field.custom_group_id = $cgTable.id
425 LEFT JOIN civicrm_option_group og
426 ON custom_field.option_group_id = og.id
430 $query .= " AND custom_field.is_active = 1 AND $cgTable.is_active = 1 ";
434 $query .= " AND $cgTable.style = 'Inline' ";
437 //get the custom fields for specific type in
438 //combination with fields those support any type.
439 if (!empty($customDataSubType)) {
441 foreach ($customDataSubType as $subtype) {
442 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($subtype, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
;
443 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
446 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
448 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
451 if ($customDataSubName) {
452 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
455 // also get the permission stuff here
456 if ($checkPermission) {
457 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
462 $permissionClause = '(1)';
465 $query .= " $extends AND $permissionClause
466 ORDER BY $cgTable.weight, $cgTable.title,
467 custom_field.weight, custom_field.label";
469 $dao = CRM_Core_DAO
::executeQuery($query);
472 while (($dao->fetch()) != NULL) {
473 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
474 $fields[$dao->id
]['id'] = $dao->id
;
475 $fields[$dao->id
]['label'] = $dao->label
;
476 // This seems broken, but not in a new way.
477 $fields[$dao->id
]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
478 // To support the consolidation of various functions & their expectations.
479 $fields[$dao->id
]['title'] = $dao->label
;
480 $fields[$dao->id
]['custom_field_id'] = $dao->id
;
481 $fields[$dao->id
]['groupTitle'] = $dao->title
;
482 $fields[$dao->id
]['data_type'] = $dao->data_type
;
483 $fields[$dao->id
]['name'] = 'custom_' . $dao->id
;
484 $fields[$dao->id
]['type'] = CRM_Utils_Array
::value($dao->data_type
, self
::dataToType());
485 $fields[$dao->id
]['html_type'] = $dao->html_type
;
486 $fields[$dao->id
]['default_value'] = $dao->default_value
;
487 $fields[$dao->id
]['text_length'] = $dao->text_length
;
488 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
489 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
490 $fields[$dao->id
]['extends'] = $dao->extends;
491 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
492 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
493 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
494 $fields[$dao->id
]['is_view'] = $dao->is_view
;
495 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
496 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
497 $fields[$dao->id
]['date_format'] = $dao->date_format
;
498 $fields[$dao->id
]['time_format'] = $dao->time_format
;
499 $fields[$dao->id
]['is_required'] = $dao->is_required
;
500 $fields[$dao->id
]['table_name'] = $dao->table_name
;
501 $fields[$dao->id
]['column_name'] = $dao->column_name
;
502 $fields[$dao->id
]['serialize'] = $serializeField ?
$dao->serialize
: (int) self
::isSerialized($dao);
503 $fields[$dao->id
]['where'] = $dao->table_name
. '.' . $dao->column_name
;
504 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
505 $fields[$dao->id
]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery
::$extendsMap) ? CRM_Core_BAO_CustomQuery
::$extendsMap[$dao->extends] : '';
506 if (in_array($dao->extends, CRM_Contact_BAO_ContactType
::subTypes())) {
507 // if $extends is a subtype, refer contact table
508 $fields[$dao->id
]['extends_table'] = 'civicrm_contact';
510 // Search table is used by query object searches..
511 $fields[$dao->id
]['search_table'] = ($fields[$dao->id
]['extends_table'] == 'civicrm_contact') ?
'contact_a' : $fields[$dao->id
]['extends_table'];
512 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
515 Civi
::cache('fields')->set("custom importableFields $cacheKey", $fields);
517 self
::$_importFields[$cacheKey] = $fields;
520 return self
::$_importFields[$cacheKey];
524 * Return the field ids and names (with groups) for import purpose.
526 * @param int|string $contactType Contact type
527 * @param bool $showAll
528 * If true returns all fields (includes disabled fields).
529 * @param bool $onlyParent
530 * Return fields ONLY related to basic types.
531 * @param bool $search
532 * When called from search and multiple records need to be returned.
533 * @param bool $checkPermission
534 * If false, do not include permissioning clause.
536 * @param bool $withMultiple
540 public static function getFieldsForImport(
541 $contactType = 'Individual',
545 $checkPermission = TRUE,
546 $withMultiple = FALSE
548 // Note: there are situations when we want getFieldsForImport() return fields related
549 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
550 $fields = &self
::getFields($contactType,
560 $importableFields = [];
561 foreach ($fields as $id => $values) {
562 // for now we should not allow multiple fields in profile / export etc, hence unsetting
564 (!empty($values['is_multiple']) && !$withMultiple)
568 if (!empty($values['text_length'])) {
569 $values['maxlength'] = (int) $values['text_length'];
572 /* generate the key for the fields array */
575 $importableFields[$key] = $values;
576 $importableFields[$key]['import'] = 1;
579 return $importableFields;
583 * Get the field id from an import key.
593 public static function getKeyID($key, $all = FALSE) {
595 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
602 CRM_Utils_Array
::value(2, $match),
606 return $all ?
[NULL, NULL] : NULL;
610 * Use the cache to get all values of a specific custom field.
612 * @param int $fieldID
613 * The custom field ID.
615 * @return CRM_Core_BAO_CustomField
617 * @throws CRM_Core_Exception
619 public static function getFieldObject($fieldID) {
620 $field = new CRM_Core_BAO_CustomField();
622 // check if we can get the field values from the system cache
623 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
624 $cache = CRM_Utils_Cache
::singleton();
625 $fieldValues = $cache->get($cacheKey);
626 if (empty($fieldValues)) {
627 $field->id
= $fieldID;
628 if (!$field->find(TRUE)) {
629 throw new CRM_Core_Exception('Cannot find Custom Field');
633 CRM_Core_DAO
::storeValues($field, $fieldValues);
635 $cache->set($cacheKey, $fieldValues);
638 $field->copyValues($fieldValues);
645 * Add a custom field to an existing form.
647 * @param CRM_Core_Form $qf
648 * Form object (reference).
649 * @param string $elementName
650 * Name of the custom field.
651 * @param int $fieldId
652 * @param bool $useRequired
653 * True if required else false.
654 * @param bool $search
655 * True if used for search else false.
656 * @param string $label
657 * Label for custom field.
658 * @return \HTML_QuickForm_Element|null
659 * @throws \CiviCRM_API3_Exception
661 public static function addQuickFormElement(
662 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
664 $field = self
::getFieldObject($fieldId);
665 $widget = $field->html_type
;
667 $customFieldAttributes = [];
669 if (!isset($label)) {
670 $label = $field->label
;
673 // DAO stores attributes as a string, but it's hard to manipulate and
674 // CRM_Core_Form::add() wants them as an array.
675 $fieldAttributes = self
::attributesFromString($field->attributes
);
677 // Custom field HTML should indicate group+field name
678 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
679 $fieldAttributes['data-crm-custom'] = $groupName . ':' . $field->name
;
681 // Fixed for Issue CRM-2183
682 if ($widget == 'TextArea' && $search) {
686 $placeholder = $search ?
ts('- any %1 -', [1 => $label]) : ts('- select %1 -', [1 => $label]);
688 if (in_array($widget, [
693 $options = $field->getOptions($search ?
'search' : 'create');
695 // Consolidate widget types to simplify the below switch statement
700 // Search field is always multi-select
701 if ($search ||
(self
::isSerialized($field) && $widget === 'Select')) {
702 $fieldAttributes['class'] = ltrim(($fieldAttributes['class'] ??
'') . ' huge');
703 $fieldAttributes['multiple'] = 'multiple';
704 $fieldAttributes['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 && $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 $fieldAttributes = array_merge($fieldAttributes, $customFieldAttributes);
719 $rangeDataTypes = ['Int', 'Float', 'Money'];
721 // at some point in time we might want to split the below into small functions
726 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
727 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $fieldAttributes);
728 $qf->add('text', $elementName . '_to', ts('To'), $fieldAttributes);
731 if ($field->text_length
) {
732 $fieldAttributes['maxlength'] = $field->text_length
;
733 if ($field->text_length
< 20) {
734 $fieldAttributes['size'] = $field->text_length
;
737 $element = $qf->add('text', $elementName, $label,
739 $useRequired && !$search
745 $fieldAttributes['rows'] = $field->note_rows ??
4;
746 $fieldAttributes['cols'] = $field->note_columns ??
60;
748 if ($field->text_length
) {
749 $fieldAttributes['maxlength'] = $field->text_length
;
751 $element = $qf->add('textarea',
755 $useRequired && !$search
760 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
761 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
762 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
765 'date' => $field->date_format
,
766 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
767 //CRM-18487 - max date should be the last date of the year.
768 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
769 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
771 if ($field->is_search_range
&& $search) {
772 $qf->add('datepicker', $elementName . '_from', $label, $fieldAttributes +
array('placeholder' => ts('From')), FALSE, $params);
773 $qf->add('datepicker', $elementName . '_to', NULL, $fieldAttributes +
array('placeholder' => ts('To')), FALSE, $params);
776 $element = $qf->add('datepicker', $elementName, $label, $fieldAttributes, $useRequired && !$search, $params);
781 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
782 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $fieldAttributes);
783 $qf->add('text', $elementName . '_to', ts('To'), $fieldAttributes);
786 $fieldAttributes = array_merge($fieldAttributes, $customFieldAttributes);
787 if ($search ||
empty($useRequired)) {
788 $fieldAttributes['allowClear'] = TRUE;
790 $qf->addRadio($elementName, $label, $options, $fieldAttributes, NULL, $useRequired);
794 // For all select elements
796 $fieldAttributes['class'] = ltrim(($fieldAttributes['class'] ??
'') . ' crm-select2');
797 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
798 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $fieldAttributes);
799 $qf->add('text', $elementName . '_to', ts('To'), $fieldAttributes);
802 if (empty($fieldAttributes['multiple'])) {
803 $options = ['' => $placeholder] +
$options;
805 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $fieldAttributes);
807 // Add and/or option for fields that store multiple values
808 if ($search && self
::isSerialized($field)) {
809 $qf->addRadio($elementName . '_operator', '', [
812 ], [], NULL, FALSE, [
813 'or' => ['title' => ts('Results may contain any of the selected options')],
814 'and' => ['title' => ts('Results must have all of the selected options')],
816 $qf->setDefaults([$elementName . '_operator' => 'or']);
823 foreach ($options as $v => $l) {
824 // TODO: I'm not sure if this is supposed to exclude whatever might be
825 // in $field->attributes (available in array format as
826 // $fieldAttributes). Leaving as-is for now.
827 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
830 $group = $element = $qf->addGroup($check, $elementName, $label);
831 $optionEditKey = 'data-option-edit-path';
832 if (isset($customFieldAttributes[$optionEditKey])) {
833 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
836 if ($useRequired && !$search) {
837 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
842 // we should not build upload file in search mode
847 strtolower($field->html_type
),
851 $useRequired && !$search
853 $qf->addUploadElement($elementName);
856 case 'RichTextEditor':
857 $fieldAttributes['rows'] = $field->note_rows
;
858 $fieldAttributes['cols'] = $field->note_columns
;
859 if ($field->text_length
) {
860 $fieldAttributes['maxlength'] = $field->text_length
;
862 $element = $qf->add('wysiwyg', $elementName, $label, $fieldAttributes, $useRequired && !$search);
865 case 'Autocomplete-Select':
866 static $customUrls = [];
867 if ($field->data_type
== 'ContactReference') {
868 // break if contact does not have permission to access ContactReference
869 if (!CRM_Core_Permission
::check('access contact reference fields')) {
872 $fieldAttributes['class'] = ltrim(($fieldAttributes['class'] ??
'') . ' crm-form-contact-reference huge');
873 $fieldAttributes['data-api-entity'] = 'Contact';
874 $element = $qf->add('text', $elementName, $label, $fieldAttributes, $useRequired && !$search);
876 $urlParams = "context=customfield&id={$field->id}";
877 $idOfelement = $elementName;
878 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
879 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
880 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
881 // rather than layering on more hacks.
882 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
883 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') +
1)), 0, -1);
885 $customUrls[$idOfelement] = CRM_Utils_System
::url('civicrm/ajax/contactref',
892 // FIXME: This won't work with customFieldOptions hook
893 $fieldAttributes +
= [
894 'entity' => 'OptionValue',
895 'placeholder' => $placeholder,
896 'multiple' => $search ?
TRUE : !empty($field->serialize
),
898 'params' => ['option_group_id' => $field->option_group_id
, 'is_active' => 1],
901 $element = $qf->addEntityRef($elementName, $label, $fieldAttributes, $useRequired && !$search);
904 $qf->assign('customUrls', $customUrls);
908 switch ($field->data_type
) {
910 // integers will have numeric rule applied to them.
911 if ($field->is_search_range
&& $search) {
912 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', [1 => $label]), 'integer');
913 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', [1 => $label]), 'integer');
915 elseif ($widget == 'Text') {
916 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', [1 => $label]), 'integer');
921 if ($field->is_search_range
&& $search) {
922 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', [1 => $label]), 'numeric');
923 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', [1 => $label]), 'numeric');
925 elseif ($widget == 'Text') {
926 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', [1 => $label]), 'numeric');
931 if ($field->is_search_range
&& $search) {
932 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
933 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
935 elseif ($widget == 'Text') {
936 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
941 $element->setAttribute('class', "url");
942 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
945 if ($field->is_view
&& !$search) {
946 $qf->freeze($elementName);
952 * Take a string of HTML element attributes and turn it into an associative
955 * @param string $attrString
956 * The attributes as a string, e.g. `rows=3 cols=40`.
959 * The attributes as an array, e.g. `['rows' => 3, 'cols' => 40]`.
961 public static function attributesFromString($attrString) {
963 foreach (explode(' ', $attrString) as $at) {
964 if (strpos($at, '=')) {
965 list($k, $v) = explode('=', $at);
966 $attributes[$k] = trim($v, ' "');
973 * Delete the Custom Field.
975 * @param object $field
978 public static function deleteField($field) {
979 CRM_Utils_System
::flushCache();
981 // first delete the custom option group and values associated with this field
982 if ($field->option_group_id
) {
983 //check if option group is related to any other field, if
984 //not delete the option group and related option values
985 self
::checkOptionGroup($field->option_group_id
);
988 // next drop the column from the custom value table
989 self
::createField($field, 'delete');
992 CRM_Core_BAO_UFField
::delUFField($field->id
);
993 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
995 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
999 * @param string|int|array|null $value
1000 * @param CRM_Core_BAO_CustomField|int|array|string $field
1001 * @param int $entityId
1005 * @throws \CRM_Core_Exception
1007 public static function displayValue($value, $field, $entityId = NULL) {
1008 $field = is_array($field) ?
$field['id'] : $field;
1009 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1012 throw new CRM_Core_Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1015 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1016 $field = self
::getFieldObject($fieldId);
1019 $fieldInfo = ['options' => $field->getOptions()] +
(array) $field;
1021 $displayValue = self
::formatDisplayValue($value, $fieldInfo, $entityId);
1023 // Call hook to alter display value.
1024 CRM_Utils_Hook
::alterCustomFieldDisplayValue($displayValue, $value, $entityId, $fieldInfo);
1026 return $displayValue;
1030 * Lower-level logic for rendering a custom field value
1032 * @param string|array $value
1033 * @param array $field
1034 * @param int|null $entityId
1038 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1040 if (self
::isSerialized($field) && !is_array($value)) {
1041 $value = CRM_Utils_Array
::explodePadded($value);
1044 if ($field['html_type'] == 'CheckBox' && $value) {
1045 $value = CRM_Utils_Array
::convertCheckboxFormatToArray($value);
1048 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1050 switch ($field['html_type']) {
1053 case 'Autocomplete-Select':
1056 if ($field['data_type'] == 'ContactReference' && $value) {
1057 if (is_numeric($value)) {
1058 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1064 elseif (is_array($value)) {
1066 foreach ($value as $key => $val) {
1067 $v[] = $field['options'][$val] ??
NULL;
1069 $display = implode(', ', $v);
1072 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1073 // For float type (see Number and Money) $value would be decimal like
1074 // 1.00 (because it is stored in db as decimal), while options array
1075 // key would be integer like 1. In this case expression on line above
1076 // would return empty string (default value), despite the fact that
1077 // matching option exists in the array.
1078 // In such cases we could just get intval($value) and fetch matching
1079 // option again, but this would not work if key is float like 5.6.
1080 // So we need to truncate trailing zeros to make it work as expected.
1081 if ($display === '' && strpos($value, '.') !== FALSE) {
1082 // Use round() to truncate trailing zeros, e.g:
1083 // 10.00 -> 10, 10.60 -> 10.6, 10.69 -> 10.69.
1084 $value = (string) round($value, 5);
1085 $display = $field['options'][$value] ??
'';
1091 $customFormat = NULL;
1093 // FIXME: Are there any legitimate reasons why $value would be an array?
1094 // Or should we throw an exception here if it is?
1095 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1097 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1098 $format = $field['date_format'] ??
NULL;
1101 if (array_key_exists($format, $actualPHPFormats)) {
1102 $customTimeFormat = (array) $actualPHPFormats[$format];
1103 switch (CRM_Utils_Array
::value('time_format', $field)) {
1105 $customTimeFormat[] = 'g:iA';
1109 $customTimeFormat[] = 'G:i';
1113 //If time is not selected remove time from value.
1114 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1116 $customFormat = implode(" ", $customTimeFormat);
1119 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1123 // In the context of displaying a profile, show file/image
1126 if (CRM_Utils_Rule
::positiveInteger($value)) {
1130 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1132 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1134 $display = $url['file_url'];
1138 // In other contexts show a paperclip icon
1139 if (CRM_Utils_Rule
::integer($value)) {
1140 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1142 $file_description = '';
1144 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1146 catch (CiviCRM_API3_Exception
$dontcare) {
1150 $display = "{$icons[$value]}{$file_description}";
1153 //CRM-18396, if filename is passed instead
1161 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1165 $display = nl2br($display);
1169 if ($field['data_type'] == 'Money' && isset($value)) {
1170 // $value can also be an array(while using IN operator from search builder or api).
1171 foreach ((array) $value as $val) {
1172 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1174 $display = implode(', ', $disp);
1182 * Set default values for custom data used in profile.
1184 * @param int $customFieldId
1186 * @param string $elementName
1187 * Custom field name.
1188 * @param array $defaults
1189 * Associated array of fields.
1190 * @param int $contactId
1194 * @param mixed $value
1195 * If passed - dont fetch value from db,.
1196 * just format the given value
1198 public static function setProfileDefaults(
1206 //get the type of custom field
1207 $customField = new CRM_Core_BAO_CustomField();
1208 $customField->id
= $customFieldId;
1209 $customField->find(TRUE);
1212 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1213 $value = $customField->default_value
;
1217 if (!isset($value)) {
1218 $info = self
::getTableColumnGroup($customFieldId);
1219 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1220 $result = CRM_Core_DAO
::executeQuery($query);
1221 if ($result->fetch()) {
1222 $value = $result->value
;
1226 if ($customField->data_type
== 'Country') {
1228 $config = CRM_Core_Config
::singleton();
1229 if ($config->defaultContactCountry
) {
1230 $value = CRM_Core_BAO_Country
::defaultContactCountry();
1236 //set defaults if mode is registration
1237 if (!trim($value) &&
1239 (!in_array($mode, [CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
]))
1241 $value = $customField->default_value
;
1244 if ($customField->data_type
== 'Money' && isset($value)) {
1245 $value = number_format($value, 2);
1247 if (self
::isSerialized($customField) && $value) {
1248 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1249 $defaults[$elementName] = [];
1250 $checkedValue = CRM_Utils_Array
::explodePadded($value);
1251 foreach ($customOption as $val) {
1252 if (in_array($val['value'], $checkedValue)) {
1253 if ($customField->html_type
== 'CheckBox') {
1254 $defaults[$elementName][$val['value']] = 1;
1257 $defaults[$elementName][$val['value']] = $val['value'];
1263 $defaults[$elementName] = $value;
1270 * @param int $contactID
1272 * @param int $fileID
1273 * @param bool $absolute
1275 * @param string $multiRecordWhereClause
1279 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1282 $params = ['id' => $cfID];
1284 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1285 $columnName = $defaults['column_name'];
1287 //table name of custom data
1288 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1289 $defaults['custom_group_id'],
1293 //query to fetch id from civicrm_file
1294 if ($multiRecordWhereClause) {
1295 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1298 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1300 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1305 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1310 $result['file_id'] = $fileID;
1312 if ($fileType == 'image/jpeg' ||
1313 $fileType == 'image/pjpeg' ||
1314 $fileType == 'image/gif' ||
1315 $fileType == 'image/x-png' ||
1316 $fileType == 'image/png'
1318 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1323 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1324 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1325 $url = CRM_Utils_System
::url('civicrm/file',
1326 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1327 $absolute, NULL, TRUE, TRUE
1329 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1331 // for non image files
1333 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1337 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1338 $url = CRM_Utils_System
::url('civicrm/file',
1339 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1340 $absolute, NULL, TRUE, TRUE
1342 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1350 * Format custom fields before inserting.
1352 * @param int $customFieldId
1354 * @param array $customFormatted
1356 * @param mixed $value
1357 * Value of custom field.
1358 * @param string $customFieldExtend
1359 * Custom field extends.
1360 * @param int $customValueId
1361 * Custom option value id.
1362 * @param int $entityId
1363 * Entity id (contribution, membership...).
1364 * @param bool $inline
1365 * Consider inline custom groups only.
1366 * @param bool $checkPermission
1367 * If false, do not include permissioning clause.
1368 * @param bool $includeViewOnly
1369 * If true, fields marked 'View Only' are included. Required for APIv3.
1371 * @return array|NULL
1372 * formatted custom field array
1374 public static function formatCustomField(
1375 $customFieldId, &$customFormatted, $value,
1376 $customFieldExtend, $customValueId = NULL,
1379 $checkPermission = TRUE,
1380 $includeViewOnly = FALSE
1382 //get the custom fields for the entity
1383 //subtype and basic type
1384 $customDataSubType = NULL;
1385 if ($customFieldExtend) {
1386 // This is the case when getFieldsForImport() requires fields
1387 // of subtype and its parent.CRM-5143
1388 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1389 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1390 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1391 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1392 if (is_array($customFieldExtend)) {
1393 $customFieldExtend = array_unique(array_values($customFieldExtend));
1398 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1408 if (!array_key_exists($customFieldId, $customFields)) {
1412 // return if field is a 'code' field
1413 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1417 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1419 if (!$customValueId &&
1420 // we always create new entites for is_multiple unless specified
1421 !$customFields[$customFieldId]['is_multiple'] &&
1427 WHERE entity_id={$entityId}";
1429 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1432 //fix checkbox, now check box always submits values
1433 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1435 // Note that only during merge this is not an array, and you can directly use value
1436 if (is_array($value)) {
1437 $selectedValues = [];
1438 foreach ($value as $selId => $val) {
1440 $selectedValues[] = $selId;
1443 if (!empty($selectedValues)) {
1444 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1446 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1454 elseif (self
::isSerialized($customFields[$customFieldId])) {
1455 // Select2 v3 returns a comma-separated string.
1456 if ($customFields[$customFieldId]['html_type'] == 'Autocomplete-Select' && is_string($value)) {
1457 $value = explode(',', $value);
1460 $value = $value ? CRM_Utils_Array
::implodePadded($value) : '';
1463 if (self
::isSerialized($customFields[$customFieldId]) &&
1464 $customFields[$customFieldId]['data_type'] == 'String' &&
1465 !empty($customFields[$customFieldId]['text_length']) &&
1468 // lets make sure that value is less than the length, else we'll
1469 // be losing some data, CRM-7481
1470 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1471 // need to do a few things here
1473 // 1. lets find a new length
1474 $newLength = $customFields[$customFieldId]['text_length'];
1475 $minLength = strlen($value);
1476 while ($newLength < $minLength) {
1477 $newLength = $newLength * 2;
1480 // set the custom field meta data to have a length larger than value
1481 // alter the custom value table column to match this length
1482 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1487 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1488 if (!CRM_Utils_System
::isNull($value)) {
1489 $format = $customFields[$customFieldId]['date_format'];
1490 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1495 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1496 $customFields[$customFieldId]['data_type'] == 'Money'
1502 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1503 $value = CRM_Utils_Rule
::cleanMoney($value);
1507 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1508 $customFields[$customFieldId]['data_type'] == 'Country'
1518 if ($customFields[$customFieldId]['data_type'] == 'File') {
1519 if (empty($value)) {
1523 $config = CRM_Core_Config
::singleton();
1525 // If we are already passing the file id as a value then retrieve and set the file data
1526 if (CRM_Utils_Rule
::integer($value)) {
1527 $fileDAO = new CRM_Core_DAO_File();
1528 $fileDAO->id
= $value;
1529 $fileDAO->find(TRUE);
1532 $fName = $fileDAO->uri
;
1533 $mimeType = $fileDAO->mime_type
;
1537 $fName = $value['name'];
1538 $mimeType = $value['type'];
1541 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1543 // rename this file to go into the secure directory only if
1544 // user has uploaded new file not existing verfied on the basis of $fileID
1545 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1546 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1549 if ($customValueId && empty($fileID)) {
1554 $params = [1 => [$customValueId, 'Integer']];
1555 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1558 $fileDAO = new CRM_Core_DAO_File();
1561 $fileDAO->id
= $fileID;
1564 $fileDAO->uri
= $filename;
1565 $fileDAO->mime_type
= $mimeType;
1566 $fileDAO->upload_date
= date('YmdHis');
1568 $fileID = $fileDAO->id
;
1572 if (!is_array($customFormatted)) {
1573 $customFormatted = [];
1576 if (!array_key_exists($customFieldId, $customFormatted)) {
1577 $customFormatted[$customFieldId] = [];
1581 if ($customValueId) {
1582 $index = $customValueId;
1585 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1586 $customFormatted[$customFieldId][$index] = [];
1588 $customFormatted[$customFieldId][$index] = [
1589 'id' => $customValueId > 0 ?
$customValueId : NULL,
1591 'type' => $customFields[$customFieldId]['data_type'],
1592 'custom_field_id' => $customFieldId,
1593 'custom_group_id' => $groupID,
1594 'table_name' => $tableName,
1595 'column_name' => $columnName,
1596 'file_id' => $fileID,
1597 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1600 //we need to sort so that custom fields are created in the order of entry
1601 krsort($customFormatted[$customFieldId]);
1602 return $customFormatted;
1606 * Get default custom table schema.
1608 * @param array $params
1612 public static function defaultCustomTableSchema($params) {
1613 // add the id and extends_id
1614 $collation = CRM_Core_BAO_SchemaHandler
::getInUseCollation();
1615 $characterSet = 'utf8';
1616 if (stripos($collation, 'utf8mb4') !== FALSE) {
1617 $characterSet = 'utf8mb4';
1620 'name' => $params['name'],
1621 'is_multiple' => $params['is_multiple'],
1622 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET {$characterSet} COLLATE {$collation}",
1626 'type' => 'int unsigned',
1629 'attributes' => 'AUTO_INCREMENT',
1630 'comment' => 'Default MySQL primary key',
1633 'name' => 'entity_id',
1634 'type' => 'int unsigned',
1636 'comment' => 'Table that this extends',
1637 'fk_table_name' => $params['extends_name'],
1638 'fk_field_name' => 'id',
1639 'fk_attributes' => 'ON DELETE CASCADE',
1644 // If on MySQL 5.6 include ROW_FORMAT=DYNAMIC to fix unit tests
1645 $databaseVersion = CRM_Utils_SQL
::getDatabaseVersion();
1646 if (version_compare($databaseVersion, '5.7', '<') && version_compare($databaseVersion, '5.6', '>=')) {
1647 $table['attributes'] = $table['attributes'] . ' ROW_FORMAT=DYNAMIC';
1650 if (!$params['is_multiple']) {
1651 $table['indexes'] = [
1654 'field_name_1' => 'entity_id',
1662 * Create custom field.
1664 * @param CRM_Core_DAO_CustomField $field
1665 * @param string $operation
1667 public static function createField($field, $operation) {
1668 $sql = str_repeat(' ', 8);
1669 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1670 $sql .= "ALTER TABLE " . $tableName;
1671 $sql .= self
::getAlterFieldSQL($field, $operation);
1673 // CRM-7007: do not i18n-rewrite this query
1674 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1676 $config = CRM_Core_Config
::singleton();
1677 if ($config->logging
) {
1678 // CRM-16717 not sure why this was originally limited to add.
1679 // For example custom tables can have field length changes - which need to flow through to logging.
1680 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1681 if ($operation === 'add' ||
$operation === 'modify') {
1682 $logging = new CRM_Logging_Schema();
1683 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name
]]);
1687 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
1691 * @param CRM_Core_DAO_CustomField $field
1692 * @param string $operation
1696 public static function getAlterFieldSQL($field, $operation) {
1697 $indexExist = $operation === 'add' ?
FALSE : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $field->id
, 'is_searchable');
1698 $params = self
::prepareCreateParams($field, $operation);
1699 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1700 // a function only used by Custom Field creation...
1701 $params['required'] = FALSE;
1702 return CRM_Core_BAO_SchemaHandler
::getFieldAlterSQL($params, $indexExist);
1706 * Reformat existing values for a field when changing its serialize attribute
1708 * @param CRM_Core_DAO_CustomField $field
1709 * @throws CRM_Core_Exception
1711 private static function alterSerialize($field) {
1712 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1713 $col = $field->column_name
;
1714 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
1715 if ($field->serialize
) {
1716 $sql = "UPDATE `$table` SET `$col` = CONCAT('$sp', `$col`, '$sp') WHERE `$col` IS NOT NULL AND `$col` NOT LIKE '$sp%' AND `$col` != ''";
1719 $sql = "UPDATE `$table` SET `$col` = SUBSTRING_INDEX(SUBSTRING(`$col`, 2), '$sp', 1) WHERE `$col` LIKE '$sp%'";
1721 CRM_Core_DAO
::executeQuery($sql);
1725 * Determine whether it would be safe to move a field.
1727 * @param int $fieldID
1728 * FK to civicrm_custom_field.
1729 * @param int $newGroupID
1730 * FK to civicrm_custom_group.
1733 * array(string) or TRUE
1735 public static function _moveFieldValidate($fieldID, $newGroupID) {
1738 $field = new CRM_Core_DAO_CustomField();
1739 $field->id
= $fieldID;
1740 if (!$field->find(TRUE)) {
1741 $errors['fieldID'] = 'Invalid ID for custom field';
1745 $oldGroup = new CRM_Core_DAO_CustomGroup();
1746 $oldGroup->id
= $field->custom_group_id
;
1747 if (!$oldGroup->find(TRUE)) {
1748 $errors['fieldID'] = 'Invalid ID for old custom group';
1752 $newGroup = new CRM_Core_DAO_CustomGroup();
1753 $newGroup->id
= $newGroupID;
1754 if (!$newGroup->find(TRUE)) {
1755 $errors['newGroupID'] = 'Invalid ID for new custom group';
1761 FROM civicrm_custom_field a
1762 INNER JOIN civicrm_custom_field b
1764 AND a.label = b.label
1765 AND b.custom_group_id = %2
1768 1 => [$field->id
, 'Integer'],
1769 2 => [$newGroup->id
, 'Integer'],
1771 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1773 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1776 $tableName = $oldGroup->table_name
;
1777 $columnName = $field->column_name
;
1782 WHERE $columnName is not null
1784 $count = CRM_Core_DAO
::singleValueQuery($query);
1788 FROM civicrm_custom_group
1789 WHERE id IN ( %1, %2 )
1792 1 => [$oldGroup->id
, 'Integer'],
1793 2 => [$newGroup->id
, 'Integer'],
1796 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1798 while ($dao->fetch()) {
1799 $extends[] = $dao->extends;
1801 if ($extends[0] != $extends[1]) {
1802 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1806 return empty($errors) ?
TRUE : $errors;
1810 * Move a custom data field from one group (table) to another.
1812 * @param int $fieldID
1813 * FK to civicrm_custom_field.
1814 * @param int $newGroupID
1815 * FK to civicrm_custom_group.
1817 * @throws CRM_Core_Exception
1819 public static function moveField($fieldID, $newGroupID) {
1820 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1821 if (TRUE !== $validation) {
1822 throw new CRM_Core_Exception(implode(' ', $validation));
1824 $field = new CRM_Core_DAO_CustomField();
1825 $field->id
= $fieldID;
1828 $newGroup = new CRM_Core_DAO_CustomGroup();
1829 $newGroup->id
= $newGroupID;
1830 $newGroup->find(TRUE);
1832 $oldGroup = new CRM_Core_DAO_CustomGroup();
1833 $oldGroup->id
= $field->custom_group_id
;
1834 $oldGroup->find(TRUE);
1837 $add->custom_group_id
= $newGroup->id
;
1838 self
::createField($add, 'add');
1840 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, `{$field->column_name}`)
1841 SELECT entity_id, `{$field->column_name}` FROM {$oldGroup->table_name}
1842 ON DUPLICATE KEY UPDATE `{$field->column_name}` = {$oldGroup->table_name}.`{$field->column_name}`
1844 CRM_Core_DAO
::executeQuery($sql);
1847 $del->custom_group_id
= $oldGroup->id
;
1848 self
::createField($del, 'delete');
1852 CRM_Utils_System
::flushCache();
1856 * Create an option value for a custom field option group ID.
1858 * @param array $params
1859 * @param string $value
1860 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1861 * @param string $index
1862 * @param string $dataType
1864 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $index, $dataType) {
1865 if (strlen(trim($value))) {
1866 $optionValue = new CRM_Core_DAO_OptionValue();
1867 $optionValue->option_group_id
= $optionGroup->id
;
1868 $optionValue->label
= $params['option_label'][$index];
1869 $optionValue->name
= $params['option_name'][$index] ?? CRM_Utils_String
::titleToVar($params['option_label'][$index]);
1870 switch ($dataType) {
1872 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1876 $optionValue->value
= intval($value);
1880 $optionValue->value
= floatval($value);
1884 $optionValue->value
= trim($value);
1887 $optionValue->weight
= $params['option_weight'][$index];
1888 $optionValue->is_active
= $params['option_status'][$index] ??
FALSE;
1889 $optionValue->description
= $params['option_description'][$index] ??
NULL;
1890 $optionValue->color
= $params['option_color'][$index] ??
NULL;
1891 $optionValue->icon
= $params['option_icon'][$index] ??
NULL;
1892 $optionValue->save();
1897 * Prepare for the create operation.
1899 * Munge params, create the option values if needed.
1901 * This could be called by a single create or a batchCreate.
1903 * @param array $params
1907 protected static function prepareCreate($params) {
1908 $op = empty($params['id']) ?
'create' : 'edit';
1909 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1910 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1911 if ($op === 'create') {
1912 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1913 if (!isset($params['column_name'])) {
1914 // if add mode & column_name not present, calculate it.
1915 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1917 if (!isset($params['name'])) {
1918 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1922 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'column_name');
1925 $htmlType = $params['html_type'] ??
NULL;
1926 $dataType = $params['data_type'] ??
NULL;
1928 if ($htmlType === 'Select Date' && empty($params['date_format'])) {
1929 $params['date_format'] = Civi
::settings()->get('dateInputFormat');
1932 // Checkboxes are always serialized in current schema
1933 if ($htmlType == 'CheckBox') {
1934 $params['serialize'] = CRM_Core_DAO
::SERIALIZE_SEPARATOR_BOOKEND
;
1937 if (!empty($params['serialize'])) {
1938 if (isset($params['default_checkbox_option'])) {
1940 foreach (array_keys($params['default_checkbox_option']) as $k => $v) {
1941 if ($params['option_value'][$v]) {
1942 $defaultArray[] = $params['option_value'][$v];
1946 if (!empty($defaultArray)) {
1947 // also add the separator before and after the value per new convention (CRM-1604)
1948 $params['default_value'] = CRM_Utils_Array
::implodePadded($defaultArray);
1952 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])) {
1953 $params['default_value'] = $params['option_value'][$params['default_option']];
1958 // create any option group & values if required
1959 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1960 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)) {
1961 //CRM-16659: if option_value then create an option group for this custom field.
1962 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
1963 // first create an option group for this custom group
1964 $optionGroup = new CRM_Core_DAO_OptionGroup();
1965 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
1966 $optionGroup->title
= $params['label'];
1967 $optionGroup->is_active
= 1;
1968 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1969 $optionGroup->is_reserved
= 0;
1970 $optionGroup->data_type
= $dataType;
1971 $optionGroup->save();
1972 $params['option_group_id'] = $optionGroup->id
;
1973 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1974 foreach ($params['option_value'] as $k => $v) {
1975 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1981 // check for orphan option groups
1982 if (!empty($params['option_group_id'])) {
1983 if (!empty($params['id'])) {
1984 self
::fixOptionGroups($params['id'], $params['option_group_id']);
1987 // if we do not have a default value
1988 // retrieve it from one of the other custom fields which use this option group
1989 if (empty($params['default_value'])) {
1990 //don't insert only value separator as default value, CRM-4579
1991 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'], !empty($params['serialize']));
1993 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultValue))) {
1994 $params['default_value'] = $defaultValue;
1999 // Set default textarea attributes
2000 if ($op == 'create' && !isset($params['attributes']) && $htmlType == 'TextArea') {
2001 $params['attributes'] = 'rows=4, cols=60';
2007 * Create database entry for custom field and related option groups.
2009 * @param array $params
2011 * @return CRM_Core_DAO_CustomField
2013 protected static function createCustomFieldRecord($params) {
2014 $transaction = new CRM_Core_Transaction();
2015 $params = self
::prepareCreate($params);
2017 $alterSerialize = isset($params['serialize']) && !empty($params['id'])
2018 && ($params['serialize'] != CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'serialize'));
2020 $customField = new CRM_Core_DAO_CustomField();
2021 $customField->copyValues($params);
2022 $customField->save();
2024 //create/drop the index when we toggle the is_searchable flag
2025 $op = empty($params['id']) ?
'add' : 'modify';
2026 if ($op !== 'modify') {
2027 if ($params['is_append_field_id_to_column_name']) {
2028 $params['column_name'] .= "_{$customField->id}";
2030 $customField->column_name
= $params['column_name'];
2031 $customField->save();
2034 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
2035 $transaction->commit();
2037 // make sure all values are present in the object for further processing
2038 $customField->find(TRUE);
2040 if ($alterSerialize) {
2041 self
::alterSerialize($customField);
2044 return $customField;
2048 * Move custom data from one contact to another.
2050 * This is currently the start of a refactoring. The theory is each
2051 * entity could have a 'move' function with a DAO default one to fall back on.
2053 * At the moment this only does a small part of the process - ie deleting a file field that
2054 * is about to be overwritten. However, the goal is the whole process around the move for
2055 * custom data should be in here.
2057 * This is currently called by the merge class but it makes sense that api could
2058 * expose move actions as moving (e.g) contributions feels like a common
2059 * ask that should be handled by the form layer.
2061 * @param int $oldContactID
2062 * @param int $newContactID
2063 * @param int[] $fieldIDs
2064 * Optional list field ids to move.
2066 * @throws \CiviCRM_API3_Exception
2067 * @throws \Exception
2069 public function move($oldContactID, $newContactID, $fieldIDs) {
2070 if (empty($fieldIDs)) {
2073 $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'];
2075 foreach ($fieldIDs as $fieldID) {
2076 $return[] = 'custom_' . $fieldID;
2078 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2079 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2081 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2082 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2083 $fieldTypesNotHandledInMergeAttempt = ['File'];
2084 foreach ($fields as $field) {
2085 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2086 if ($field['data_type'] === 'File' && !$isMultiple) {
2087 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2088 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2090 if (!empty($oldContact['custom_' . $field['id']])) {
2091 CRM_Core_DAO
::executeQuery("
2092 UPDATE civicrm_entity_file
2093 SET entity_id = $newContactID
2094 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2098 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2099 CRM_Core_DAO
::executeQuery(
2100 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, `{$field['column_name']}`)
2101 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2102 ON DUPLICATE KEY UPDATE
2103 `{$field['column_name']}` = {$oldContact['custom_' . $field['id']]}
2110 * Get the database table name and column name for a custom field.
2112 * @param int $fieldID
2113 * The fieldID of the custom field.
2114 * @param bool $force
2115 * Force the sql to be run again (primarily used for tests).
2118 * fatal is fieldID does not exists, else array of tableName, columnName
2119 * @throws \CRM_Core_Exception
2121 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2122 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2123 $cache = CRM_Utils_Cache
::singleton();
2124 $fieldValues = $cache->get($cacheKey);
2125 if (empty($fieldValues) ||
$force) {
2127 SELECT cg.table_name, cf.column_name, cg.id
2128 FROM civicrm_custom_group cg,
2129 civicrm_custom_field cf
2130 WHERE cf.custom_group_id = cg.id
2132 $params = [1 => [$fieldID, 'Integer']];
2133 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2135 if (!$dao->fetch()) {
2136 throw new CRM_Core_Exception("Cannot find table and column information for Custom Field " . $fieldID);
2138 $fieldValues = [$dao->table_name
, $dao->column_name
, $dao->id
];
2139 $cache->set($cacheKey, $fieldValues);
2141 return $fieldValues;
2145 * Get custom option groups.
2147 * @deprecated Use the API OptionGroup.get
2149 * @param array $includeFieldIds
2150 * Ids of custom fields for which option groups must be included.
2152 * Currently this is required in the cases where option groups are to be included
2153 * for inactive fields : CRM-5369
2157 public static function customOptionGroup($includeFieldIds = NULL) {
2158 static $customOptionGroup = NULL;
2160 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2161 if ($cacheKey == 'force') {
2162 $customOptionGroup[$cacheKey] = NULL;
2165 if (empty($customOptionGroup[$cacheKey])) {
2166 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2168 //support for single as well as array format.
2169 if (!empty($includeFieldIds)) {
2170 if (is_array($includeFieldIds)) {
2171 $includeFieldIds = implode(',', $includeFieldIds);
2173 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2177 SELECT g.id, g.title
2178 FROM civicrm_option_group g
2179 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2180 WHERE {$whereClause}";
2182 $dao = CRM_Core_DAO
::executeQuery($query);
2183 while ($dao->fetch()) {
2184 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2188 return $customOptionGroup[$cacheKey];
2192 * Get defaults for new entity.
2196 public static function getDefaults() {
2198 'is_required' => FALSE,
2199 'is_searchable' => FALSE,
2200 'in_selector' => FALSE,
2201 'is_search_range' => FALSE,
2202 //CRM-15792 - Custom field gets disabled if is_active not set
2203 // this would ideally be a mysql default.
2204 'is_active' => TRUE,
2210 * Fix orphan groups.
2212 * @param int $customFieldId
2214 * @param int $optionGroupId
2217 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2218 // check if option group belongs to any custom Field else delete
2219 // get the current option group
2220 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2224 // get the updated option group
2225 // if both are same return
2226 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2230 // check if option group is related to any other field
2231 self
::checkOptionGroup($currentOptionGroupId);
2235 * Check if option group is related to more than one custom field.
2237 * @param int $optionGroupId
2240 public static function checkOptionGroup($optionGroupId) {
2243 FROM civicrm_custom_field
2244 WHERE option_group_id = {$optionGroupId}";
2246 $count = CRM_Core_DAO
::singleValueQuery($query);
2249 //delete the option group
2250 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2255 * Get option group default.
2257 * @param int $optionGroupId
2258 * @param bool $serialize
2260 * @return null|string
2262 public static function getOptionGroupDefault($optionGroupId, $serialize) {
2264 SELECT default_value, serialize
2265 FROM civicrm_custom_field
2266 WHERE option_group_id = {$optionGroupId}
2267 AND default_value IS NOT NULL";
2269 $dao = CRM_Core_DAO
::executeQuery($query);
2270 while ($dao->fetch()) {
2271 if ($dao->serialize
== $serialize) {
2272 return $dao->default_value
;
2274 $defaultValue = $dao->default_value
;
2277 // Convert serialization
2278 if (isset($defaultValue) && $serialize) {
2279 return CRM_Utils_Array
::implodePadded([$defaultValue]);
2281 elseif (isset($defaultValue)) {
2282 return CRM_Utils_Array
::explodePadded($defaultValue)[0];
2288 * Post process function.
2290 * @param array $params
2291 * @param int $entityID
2292 * @param string $customFieldExtends
2293 * @param bool $inline
2294 * @param bool $checkPermissions
2298 public static function postProcess(
2301 $customFieldExtends,
2303 $checkPermissions = TRUE
2307 foreach ($params as $key => $value) {
2308 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2310 // for autocomplete transfer hidden value instead of label
2311 if ($params[$key] && isset($params[$key . '_id'])) {
2312 $value = $params[$key . '_id'];
2315 // we need to append time with date
2316 if ($params[$key] && isset($params[$key . '_time'])) {
2317 $value .= ' ' . $params[$key . '_time'];
2320 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2323 $customFieldExtends,
2324 $customFieldInfo[1],
2335 * Get custom field ID from field/group name/title.
2337 * @param string $fieldName Field name or label
2338 * @param string|null $groupName (Optional) Group name or label
2339 * @param bool $fullString Whether to return "custom_123" or "123"
2341 * @return string|int|null
2342 * @throws \CiviCRM_API3_Exception
2344 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2345 $cacheKey = $groupName . '.' . $fieldName;
2346 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2347 $customFieldParams = [
2348 'name' => $fieldName,
2349 'label' => $fieldName,
2350 'options' => ['or' => [["name", "label"]]],
2354 $customFieldParams['custom_group_id.name'] = $groupName;
2355 $customFieldParams['custom_group_id.title'] = $groupName;
2356 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2359 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2361 if (empty($field['id'])) {
2362 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2363 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2366 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2367 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2372 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2374 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2378 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2384 public static function getNameFromID($ids) {
2385 if (is_array($ids)) {
2386 $ids = implode(',', $ids);
2389 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2390 FROM civicrm_custom_field f
2391 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2392 WHERE f.id IN ($ids)";
2394 $dao = CRM_Core_DAO
::executeQuery($sql);
2396 while ($dao->fetch()) {
2397 $result[$dao->id
] = [
2398 'field_name' => $dao->field_name
,
2399 'field_label' => $dao->field_label
,
2400 'group_name' => $dao->group_name
,
2401 'group_title' => $dao->group_title
,
2408 * Validate custom data.
2410 * @param array $params
2411 * Custom data submitted.
2412 * ie array( 'custom_1' => 'validate me' );
2415 * validation errors.
2417 public static function validateCustomData($params) {
2419 if (!is_array($params) ||
empty($params)) {
2423 //pick up profile fields.
2424 $profileFields = [];
2425 $ufGroupId = $params['ufGroupId'] ??
NULL;
2427 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2429 CRM_Core_Action
::VIEW
2433 //lets start w/ params.
2434 foreach ($params as $key => $value) {
2435 $customFieldID = self
::getKeyID($key);
2436 if (!$customFieldID) {
2440 //load the structural info for given field.
2441 $field = new CRM_Core_DAO_CustomField();
2442 $field->id
= $customFieldID;
2443 if (!$field->find(TRUE)) {
2446 $dataType = $field->data_type
;
2448 $profileField = CRM_Utils_Array
::value($key, $profileFields, []);
2449 $fieldTitle = $profileField['title'] ??
NULL;
2450 $isRequired = $profileField['is_required'] ??
NULL;
2452 $fieldTitle = $field->label
;
2455 //no need to validate.
2456 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2460 //lets validate first for required field.
2461 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2462 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
2466 //now time to take care of custom field form rules.
2467 $ruleName = $errorMsg = NULL;
2468 switch ($dataType) {
2470 $ruleName = 'integer';
2471 $errorMsg = ts('%1 must be an integer (whole number).',
2472 array(1 => $fieldTitle)
2477 $ruleName = 'money';
2478 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2479 array(1 => $fieldTitle)
2484 $ruleName = 'numeric';
2485 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2486 array(1 => $fieldTitle)
2491 $ruleName = 'wikiURL';
2492 $errorMsg = ts('%1 must be valid Website.',
2493 array(1 => $fieldTitle)
2498 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2500 $funName = "CRM_Utils_Rule::{$ruleName}";
2501 if (is_callable($funName)) {
2502 $valid = call_user_func($funName, $value);
2505 $errors[$key] = $errorMsg;
2514 * Is this field a multi record field.
2516 * @param int $customId
2520 public static function isMultiRecordField($customId) {
2521 $isMultipleWithGid = FALSE;
2522 if (!is_numeric($customId)) {
2523 $customId = self
::getKeyID($customId);
2525 if (is_numeric($customId)) {
2526 $sql = "SELECT cg.id cgId
2527 FROM civicrm_custom_group cg
2528 INNER JOIN civicrm_custom_field cf
2529 ON cg.id = cf.custom_group_id
2530 WHERE cf.id = %1 AND cg.is_multiple = 1";
2531 $params[1] = [$customId, 'Integer'];
2532 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2533 if ($dao->fetch()) {
2535 $isMultipleWithGid = $dao->cgId
;
2540 return $isMultipleWithGid;
2544 * Does this field type have any select options?
2546 * @param array $field
2550 public static function hasOptions($field) {
2551 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2552 $field = (array) $field;
2553 // This will include boolean fields with Yes/No options.
2554 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2557 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2558 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2559 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2562 if (strpos($field['html_type'], 'Select') !== FALSE) {
2565 return !empty($field['option_group_id']);
2569 * Does this field store a serialized string?
2571 * @param CRM_Core_DAO_CustomField|array $field
2575 public static function isSerialized($field) {
2576 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2577 $html_type = is_object($field) ?
$field->html_type
: $field['html_type'];
2578 // APIv3 has a "legacy" mode where it returns old-style html_type of "Multi-Select"
2579 // If anyone is using this function in conjunction with legacy api output, we'll accomodate:
2580 if ($html_type === 'CheckBox' ||
strpos($html_type, 'Multi') !== FALSE) {
2583 // Otherwise this is the new standard as of 5.27
2584 return is_object($field) ?
!empty($field->serialize
) : !empty($field['serialize']);
2588 * Get api entity for this field
2592 public function getEntity() {
2593 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2594 return in_array($entity, ['Individual', 'Household', 'Organization']) ?
'Contact' : $entity;
2598 * Set pseudoconstant properties for field metadata.
2600 * @param array $field
2601 * @param string|null $optionGroupName
2603 private static function getOptionsForField(&$field, $optionGroupName) {
2604 if ($optionGroupName) {
2605 $field['pseudoconstant'] = [
2606 'optionGroupName' => $optionGroupName,
2607 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2610 elseif ($field['data_type'] == 'Boolean') {
2611 $field['pseudoconstant'] = [
2612 'callback' => 'CRM_Core_SelectValues::boolean',
2615 elseif ($field['data_type'] == 'Country') {
2616 $field['pseudoconstant'] = [
2617 'table' => 'civicrm_country',
2618 'keyColumn' => 'id',
2619 'labelColumn' => 'name',
2620 'nameColumn' => 'iso_code',
2623 elseif ($field['data_type'] == 'StateProvince') {
2624 $field['pseudoconstant'] = [
2625 'table' => 'civicrm_state_province',
2626 'keyColumn' => 'id',
2627 'labelColumn' => 'name',
2633 * @param CRM_Core_DAO_CustomField $field
2634 * @param 'add|modify' $operation
2638 protected static function prepareCreateParams($field, $operation) {
2639 $tableName = CRM_Core_DAO
::getFieldValue(
2640 'CRM_Core_DAO_CustomGroup',
2641 $field->custom_group_id
,
2646 'table_name' => $tableName,
2647 'operation' => $operation,
2648 'name' => $field->column_name
,
2649 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2653 'required' => $field->is_required
,
2654 'searchable' => $field->is_searchable
,
2657 if ($operation == 'delete') {
2658 $fkName = "{$tableName}_{$field->column_name}";
2659 if (strlen($fkName) >= 48) {
2660 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2662 $params['fkName'] = $fkName;
2664 if ($field->data_type
== 'Country' && !self
::isSerialized($field)) {
2665 $params['fk_table_name'] = 'civicrm_country';
2666 $params['fk_field_name'] = 'id';
2667 $params['fk_attributes'] = 'ON DELETE SET NULL';
2669 elseif ($field->data_type
== 'StateProvince' && !self
::isSerialized($field)) {
2670 $params['fk_table_name'] = 'civicrm_state_province';
2671 $params['fk_field_name'] = 'id';
2672 $params['fk_attributes'] = 'ON DELETE SET NULL';
2674 elseif ($field->data_type
== 'StateProvince' ||
$field->data_type
== 'Country') {
2675 $params['type'] = 'varchar(255)';
2677 elseif ($field->data_type
== 'File') {
2678 $params['fk_table_name'] = 'civicrm_file';
2679 $params['fk_field_name'] = 'id';
2680 $params['fk_attributes'] = 'ON DELETE SET NULL';
2682 elseif ($field->data_type
== 'ContactReference') {
2683 $params['fk_table_name'] = 'civicrm_contact';
2684 $params['fk_field_name'] = 'id';
2685 $params['fk_attributes'] = 'ON DELETE SET NULL';
2687 if (isset($field->default_value
)) {
2688 $params['default'] = "'{$field->default_value}'";