3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Business objects for managing custom data fields.
21 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
24 * Array to hold (formatted) fields for import
28 public static $_importFields = NULL;
31 * Build and retrieve the list of data types and descriptions.
34 * Data type => Description
36 public static function dataType() {
38 'String' => ts('Alphanumeric'),
39 'Int' => ts('Integer'),
40 'Float' => ts('Number'),
41 'Money' => ts('Money'),
44 'Boolean' => ts('Yes or No'),
45 'StateProvince' => ts('State/Province'),
46 'Country' => ts('Country'),
49 'ContactReference' => ts('Contact Reference'),
54 * Build the map of custom field's data types and there respective Util type
57 * Data data-type => CRM_Utils_Type
59 public static function dataToType() {
61 'String' => CRM_Utils_Type
::T_STRING
,
62 'Int' => CRM_Utils_Type
::T_INT
,
63 'Money' => CRM_Utils_Type
::T_MONEY
,
64 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
65 'Float' => CRM_Utils_Type
::T_FLOAT
,
66 'Date' => CRM_Utils_Type
::T_DATE
,
67 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
68 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
69 'StateProvince' => CRM_Utils_Type
::T_INT
,
70 'File' => CRM_Utils_Type
::T_STRING
,
71 'Link' => CRM_Utils_Type
::T_STRING
,
72 'ContactReference' => CRM_Utils_Type
::T_INT
,
73 'Country' => CRM_Utils_Type
::T_INT
,
78 * Takes an associative array and creates a custom field object.
80 * This function is invoked from within the web form layer and also from the api layer
82 * @param array $params
83 * (reference) an assoc array of name/value pairs.
85 * @return CRM_Core_DAO_CustomField
87 public static function create($params) {
88 $customField = self
::createCustomFieldRecord($params);
89 $op = empty($params['id']) ?
'add' : 'modify';
90 self
::createField($customField, $op);
92 CRM_Utils_Hook
::post(($op === 'add' ?
'create' : 'edit'), 'CustomField', $customField->id
, $customField);
94 CRM_Utils_System
::flushCache();
95 // Flush caches is not aggressive about clearing the specific cache we know we want to clear
96 // so do it manually. Ideally we wouldn't need to clear others...
97 Civi
::cache('metadata')->clear();
103 * Create/ update several fields at once in a mysql efficient way.
105 * https://lab.civicrm.org/dev/core/issues/1093
107 * The intention is that apiv4 would expose any BAO with bulkSave as a new action.
109 * @param array $bulkParams
110 * Array of arrays as would be passed into create
111 * @param array $defaults
112 * Default parameters to be be merged into each of the params.
114 * @throws \CiviCRM_API3_Exception
116 public static function bulkSave($bulkParams, $defaults = []) {
117 $addedColumns = $sql = $tables = $customFields = [];
118 foreach ($bulkParams as $index => $fieldParams) {
119 $params = array_merge($defaults, $fieldParams);
120 $customField = self
::createCustomFieldRecord($params);
121 $fieldSQL = self
::getAlterFieldSQL($customField, empty($params['id']) ?
'add' : 'modify');
122 if (!isset($params['custom_group_id'])) {
123 $params['custom_group_id'] = civicrm_api3('CustomField', 'getvalue', ['id' => $customField->id
, 'return' => 'custom_group_id']);
125 if (!isset($params['table_name'])) {
126 if (!isset($tables[$params['custom_group_id']])) {
127 $tables[$params['custom_group_id']] = civicrm_api3('CustomGroup', 'getvalue', [
128 'id' => $params['custom_group_id'],
129 'return' => 'table_name',
132 $params['table_name'] = $tables[$params['custom_group_id']];
134 $sql[$params['table_name']][] = $fieldSQL;
135 $addedColumns[$params['table_name']][] = $customField->name
;
136 $customFields[$index] = $customField;
139 foreach ($sql as $tableName => $statements) {
140 // CRM-7007: do not i18n-rewrite this query
141 CRM_Core_DAO
::executeQuery("ALTER TABLE $tableName " . implode(', ', $statements), [], TRUE, NULL, FALSE, FALSE);
143 if (CRM_Core_Config
::singleton()->logging
) {
144 $logging = new CRM_Logging_Schema();
145 $logging->fixSchemaDifferencesFor($tableName, ['ADD' => $addedColumns[$tableName]]);
148 Civi
::service('sql_triggers')->rebuild($params['table_name'], TRUE);
150 CRM_Utils_System
::flushCache();
151 foreach ($customFields as $index => $customField) {
152 CRM_Utils_Hook
::post(empty($bulkParams[$index]['id']) ?
'create' : 'edit', 'CustomField', $customField->id
, $customField);
157 * Fetch object based on array of properties.
159 * @param array $params
160 * (reference ) an assoc array of name/value pairs.
161 * @param array $defaults
162 * (reference ) an assoc array to hold the flattened values.
164 * @return CRM_Core_DAO_CustomField
166 public static function retrieve(&$params, &$defaults) {
167 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
171 * Update the is_active flag in the db.
174 * Id of the database record.
175 * @param bool $is_active
176 * Value we want to set the is_active field.
179 * true if we found and updated the object, else false
181 public static function setIsActive($id, $is_active) {
183 CRM_Utils_System
::flushCache();
185 //enable-disable CustomField
186 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
187 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
191 * Get the field title.
199 public static function getTitle($id) {
200 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
204 * @param string $context
207 public function getOptions($context = NULL) {
208 CRM_Core_DAO
::buildOptionsContext($context);
213 $cacheKey = "CRM_Core_BAO_CustomField_getOptions_{$this->id}_$context";
214 $cache = CRM_Utils_Cache
::singleton();
215 $options = $cache->get($cacheKey);
216 if (!isset($options)) {
217 if (!$this->data_type ||
!$this->custom_group_id
) {
221 // This will hold the list of options in format key => label
224 if (!empty($this->option_group_id
)) {
225 $options = CRM_Core_OptionGroup
::valuesByID(
226 $this->option_group_id
, FALSE, FALSE, FALSE, $context == 'validate' ?
'name' : 'label', !($context == 'validate' ||
$context == 'get')
229 elseif ($this->data_type
=== 'StateProvince') {
230 $options = CRM_Core_PseudoConstant
::stateProvince();
232 elseif ($this->data_type
=== 'Country') {
233 $options = $context == 'validate' ? CRM_Core_PseudoConstant
::countryIsoCode() : CRM_Core_PseudoConstant
::country();
235 elseif ($this->data_type
=== 'Boolean') {
236 $options = $context == 'validate' ?
[0, 1] : CRM_Core_SelectValues
::boolean();
238 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
239 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, ['context' => $context]);
240 $cache->set($cacheKey, $options);
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['Multi-Select Country'] = 'Multi-Select Country';
254 $options['Multi-Select State/Province'] = 'Multi-Select State/Province';
260 * Store and return an array of all active custom fields.
262 * @param string $customDataType
263 * Type of Custom Data; 'ANY' is a synonym for "all contact data types".
264 * @param bool $showAll
265 * If true returns all fields (includes disabled fields).
266 * @param bool $inline
267 * If true returns all inline fields (includes disabled fields).
268 * @param int $customDataSubType
269 * Custom Data sub type value.
270 * @param int $customDataSubName
271 * Custom Data sub name value.
272 * @param bool $onlyParent
273 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
274 * @param bool $onlySubType
275 * Return only custom data for subtype.
276 * @param bool $checkPermission
277 * If false, do not include permissioning clause.
280 * an array of active custom fields.
281 * @throws \CRM_Core_Exception
283 public static function &getFields(
284 $customDataType = 'Individual',
287 $customDataSubType = NULL,
288 $customDataSubName = NULL,
290 $onlySubType = FALSE,
291 $checkPermission = TRUE
293 if (empty($customDataType)) {
294 $customDataType = ['Contact', 'Individual', 'Organization', 'Household'];
296 if ($customDataType === 'ANY') {
297 // NULL should have been respected but the line above broke that.
298 // boo for us not having enough unit tests back them.
299 $customDataType = NULL;
301 if ($customDataType && !is_array($customDataType)) {
303 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
304 // This is the case when getFieldsForImport() requires fields
305 // limited strictly to a subtype.
306 $customDataSubType = $customDataType;
307 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
311 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
312 // this makes the method flexible to support retrieving fields
313 // for multiple extends value.
314 $customDataType = [$customDataType];
318 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
320 if (is_array($customDataType)) {
321 $cacheKey = implode('_', $customDataType);
324 $cacheKey = $customDataType;
327 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
328 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
329 $cacheKey .= $showAll ?
'_1' : '_0';
330 $cacheKey .= $inline ?
'_1_' : '_0_';
331 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
332 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
333 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
334 $cacheKey .= '_' . CRM_Core_Config
::domainID() . '_';
336 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
338 // also get the permission stuff here
339 if ($checkPermission) {
340 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
345 $permissionClause = '(1)';
348 // lets md5 permission clause and take first 8 characters
349 $cacheKey .= substr(md5($permissionClause), 0, 8);
351 if (strlen($cacheKey) > 40) {
352 $cacheKey = md5($cacheKey);
355 if (!self
::$_importFields ||
356 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
358 if (!self
::$_importFields) {
359 self
::$_importFields = [];
362 // check if we can retrieve from database cache
363 $fields = Civi
::Cache('fields')->get("custom importableFields $cacheKey");
365 if ($fields === NULL) {
366 $cfTable = self
::getTableName();
369 if (is_array($customDataType)) {
371 foreach ($customDataType as $dataType) {
372 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
373 if (in_array($dataType, ['Individual', 'Household', 'Organization'])) {
374 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
377 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
379 $value = $value ?
$value . ", {$val}" : $val;
383 $extends = "AND $cgTable.extends IN ( $value ) ";
387 if (!empty($customDataType) && empty($extends)) {
388 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
389 self
::$_importFields[$cacheKey] = [];
390 return self
::$_importFields[$cacheKey];
394 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
396 // Temporary hack - in 5.27 a new field is added to civicrm_custom_field. There is a high
397 // risk this function is called before the upgrade page can be reached and if
398 // so it will potentially result in fatal error.
399 $serializeField = CRM_Core_BAO_Domain
::isDBVersionAtLeast('5.27.alpha1') ?
"$cfTable.serialize," : '';
401 $query = "SELECT $cfTable.id, $cfTable.label,
405 $cfTable.default_value,
406 $cfTable.options_per_line, $cfTable.text_length,
407 $cfTable.custom_group_id,
408 $cfTable.is_required,
409 $cfTable.column_name,
410 $cgTable.extends, $cfTable.is_search_range,
411 $cgTable.extends_entity_column_value,
412 $cgTable.extends_entity_column_id,
414 $cfTable.option_group_id,
415 $cfTable.date_format,
416 $cfTable.time_format,
417 $cgTable.is_multiple,
420 og.name as option_group_name
423 ON $cfTable.custom_group_id = $cgTable.id
424 LEFT JOIN civicrm_option_group og
425 ON $cfTable.option_group_id = og.id
429 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
433 $query .= " AND $cgTable.style = 'Inline' ";
436 //get the custom fields for specific type in
437 //combination with fields those support any type.
438 if (!empty($customDataSubType)) {
440 foreach ($customDataSubType as $subtype) {
441 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($subtype, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
;
442 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
445 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
447 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
450 if ($customDataSubName) {
451 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
454 // also get the permission stuff here
455 if ($checkPermission) {
456 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
461 $permissionClause = '(1)';
464 $query .= " $extends AND $permissionClause
465 ORDER BY $cgTable.weight, $cgTable.title,
466 $cfTable.weight, $cfTable.label";
468 $dao = CRM_Core_DAO
::executeQuery($query);
471 while (($dao->fetch()) != NULL) {
472 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
473 $fields[$dao->id
]['id'] = $dao->id
;
474 $fields[$dao->id
]['label'] = $dao->label
;
475 // This seems broken, but not in a new way.
476 $fields[$dao->id
]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
477 // To support the consolidation of various functions & their expectations.
478 $fields[$dao->id
]['title'] = $dao->label
;
479 $fields[$dao->id
]['custom_field_id'] = $dao->id
;
480 $fields[$dao->id
]['groupTitle'] = $dao->title
;
481 $fields[$dao->id
]['data_type'] = $dao->data_type
;
482 $fields[$dao->id
]['name'] = 'custom_' . $dao->id
;
483 $fields[$dao->id
]['type'] = CRM_Utils_Array
::value($dao->data_type
, self
::dataToType());
484 $fields[$dao->id
]['html_type'] = $dao->html_type
;
485 $fields[$dao->id
]['default_value'] = $dao->default_value
;
486 $fields[$dao->id
]['text_length'] = $dao->text_length
;
487 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
488 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
489 $fields[$dao->id
]['extends'] = $dao->extends;
490 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
491 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
492 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
493 $fields[$dao->id
]['is_view'] = $dao->is_view
;
494 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
495 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
496 $fields[$dao->id
]['date_format'] = $dao->date_format
;
497 $fields[$dao->id
]['time_format'] = $dao->time_format
;
498 $fields[$dao->id
]['is_required'] = $dao->is_required
;
499 $fields[$dao->id
]['table_name'] = $dao->table_name
;
500 $fields[$dao->id
]['column_name'] = $dao->column_name
;
501 $fields[$dao->id
]['serialize'] = $serializeField ?
$dao->serialize
: (int) self
::isSerialized($dao);
502 $fields[$dao->id
]['where'] = $dao->table_name
. '.' . $dao->column_name
;
503 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
504 $fields[$dao->id
]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery
::$extendsMap) ? CRM_Core_BAO_CustomQuery
::$extendsMap[$dao->extends] : '';
505 if (in_array($dao->extends, CRM_Contact_BAO_ContactType
::subTypes())) {
506 // if $extends is a subtype, refer contact table
507 $fields[$dao->id
]['extends_table'] = 'civicrm_contact';
509 // Search table is used by query object searches..
510 $fields[$dao->id
]['search_table'] = ($fields[$dao->id
]['extends_table'] == 'civicrm_contact') ?
'contact_a' : $fields[$dao->id
]['extends_table'];
511 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
514 Civi
::cache('fields')->set("custom importableFields $cacheKey", $fields);
516 self
::$_importFields[$cacheKey] = $fields;
519 return self
::$_importFields[$cacheKey];
523 * Return the field ids and names (with groups) for import purpose.
525 * @param int|string $contactType Contact type
526 * @param bool $showAll
527 * If true returns all fields (includes disabled fields).
528 * @param bool $onlyParent
529 * Return fields ONLY related to basic types.
530 * @param bool $search
531 * When called from search and multiple records need to be returned.
532 * @param bool $checkPermission
533 * If false, do not include permissioning clause.
535 * @param bool $withMultiple
539 public static function getFieldsForImport(
540 $contactType = 'Individual',
544 $checkPermission = TRUE,
545 $withMultiple = FALSE
547 // Note: there are situations when we want getFieldsForImport() return fields related
548 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
549 $fields = &self
::getFields($contactType,
559 $importableFields = [];
560 foreach ($fields as $id => $values) {
561 // for now we should not allow multiple fields in profile / export etc, hence unsetting
563 (!empty($values['is_multiple']) && !$withMultiple)
567 if (!empty($values['text_length'])) {
568 $values['maxlength'] = (int) $values['text_length'];
571 /* generate the key for the fields array */
574 $importableFields[$key] = $values;
575 $importableFields[$key]['import'] = 1;
578 return $importableFields;
582 * Get the field id from an import key.
592 public static function getKeyID($key, $all = FALSE) {
594 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
601 CRM_Utils_Array
::value(2, $match),
605 return $all ?
[NULL, NULL] : NULL;
609 * Use the cache to get all values of a specific custom field.
611 * @param int $fieldID
612 * The custom field ID.
614 * @return CRM_Core_BAO_CustomField
616 * @throws CRM_Core_Exception
618 public static function getFieldObject($fieldID) {
619 $field = new CRM_Core_BAO_CustomField();
621 // check if we can get the field values from the system cache
622 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
623 $cache = CRM_Utils_Cache
::singleton();
624 $fieldValues = $cache->get($cacheKey);
625 if (empty($fieldValues)) {
626 $field->id
= $fieldID;
627 if (!$field->find(TRUE)) {
628 throw new CRM_Core_Exception('Cannot find Custom Field');
632 CRM_Core_DAO
::storeValues($field, $fieldValues);
634 $cache->set($cacheKey, $fieldValues);
637 $field->copyValues($fieldValues);
644 * Add a custom field to an existing form.
646 * @param CRM_Core_Form $qf
647 * Form object (reference).
648 * @param string $elementName
649 * Name of the custom field.
650 * @param int $fieldId
651 * @param bool $useRequired
652 * True if required else false.
653 * @param bool $search
654 * True if used for search else false.
655 * @param string $label
656 * Label for custom field.
657 * @return \HTML_QuickForm_Element|null
658 * @throws \CiviCRM_API3_Exception
660 public static function addQuickFormElement(
661 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
663 $field = self
::getFieldObject($fieldId);
664 $widget = $field->html_type
;
666 $customFieldAttributes = [];
668 // Custom field HTML should indicate group+field name
669 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
670 $dataCrmCustomVal = $groupName . ':' . $field->name
;
671 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
672 $field->attributes
.= $dataCrmCustomAttr;
674 // Fixed for Issue CRM-2183
675 if ($widget == 'TextArea' && $search) {
679 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
681 // FIXME: Why are select state/country separate widget types?
682 $isSelect = (in_array($widget, [
684 'Select State/Province',
691 $options = $field->getOptions($search ?
'search' : 'create');
693 // Consolidate widget types to simplify the below switch statement
694 if ($search ||
(strpos($widget, 'Select') !== FALSE)) {
698 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
699 $selectAttributes = ['class' => 'crm-select2'];
701 // Search field is always multi-select
702 if ($search ||
(self
::isSerialized($field) && $widget === 'Select')) {
703 $selectAttributes['class'] .= ' huge';
704 $selectAttributes['multiple'] = 'multiple';
705 $selectAttributes['placeholder'] = $placeholder;
708 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
709 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
710 if ($field->option_group_id
&& !$search && $isSelect && $canEditOptions) {
711 $customFieldAttributes +
= [
712 'data-api-entity' => $field->getEntity(),
713 'data-api-field' => 'custom_' . $field->id
,
714 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
716 $selectAttributes +
= $customFieldAttributes;
720 $rangeDataTypes = ['Int', 'Float', 'Money'];
722 if (!isset($label)) {
723 $label = $field->label
;
726 // at some point in time we might want to split the below into small functions
731 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
732 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
733 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
736 if ($field->text_length
) {
737 $field->attributes
.= ' maxlength=' . $field->text_length
;
738 if ($field->text_length
< 20) {
739 $field->attributes
.= ' size=' . $field->text_length
;
742 $element = $qf->add('text', $elementName, $label,
744 $useRequired && !$search
750 $attributes = $dataCrmCustomAttr;
751 if ($field->note_rows
) {
752 $attributes .= 'rows=' . $field->note_rows
;
755 $attributes .= 'rows=4';
757 if ($field->note_columns
) {
758 $attributes .= ' cols=' . $field->note_columns
;
761 $attributes .= ' cols=60';
763 if ($field->text_length
) {
764 $attributes .= ' maxlength=' . $field->text_length
;
766 $element = $qf->add('textarea',
770 $useRequired && !$search
775 $attr = ['data-crm-custom' => $dataCrmCustomVal];
776 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
777 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
778 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
781 'date' => $field->date_format
,
782 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
783 //CRM-18487 - max date should be the last date of the year.
784 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
785 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
787 if ($field->is_search_range
&& $search) {
788 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
789 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
792 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
797 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
798 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
799 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
802 parse_str($field->attributes
, $radioAttributes);
803 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
804 if ($search ||
empty($useRequired)) {
805 $radioAttributes['allowClear'] = TRUE;
807 $qf->addRadio($elementName, $label, $options, $radioAttributes, NULL, $useRequired);
811 // For all select elements
813 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
814 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
815 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
818 if (empty($selectAttributes['multiple'])) {
819 $options = ['' => $placeholder] +
$options;
821 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
823 // Add and/or option for fields that store multiple values
824 if ($search && self
::isSerialized($field)) {
827 $qf->createElement('radio', NULL, '', ts('Any'), 'or', ['title' => ts('Results may contain any of the selected options')]),
828 $qf->createElement('radio', NULL, '', ts('All'), 'and', ['title' => ts('Results must have all of the selected options')]),
830 $qf->addGroup($operators, $elementName . '_operator');
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,
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':
1059 case 'Select Country':
1060 case 'Select State/Province':
1062 if ($field['data_type'] == 'ContactReference' && $value) {
1063 if (is_numeric($value)) {
1064 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1070 elseif (is_array($value)) {
1072 foreach ($value as $key => $val) {
1073 $v[] = $field['options'][$val] ??
NULL;
1075 $display = implode(', ', $v);
1078 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1079 // For float type (see Number and Money) $value would be decimal like
1080 // 1.00 (because it is stored in db as decimal), while options array
1081 // key would be integer like 1. In this case expression on line above
1082 // would return empty string (default value), despite the fact that
1083 // matching option exists in the array.
1084 // In such cases we could just get intval($value) and fetch matching
1085 // option again, but this would not work if key is float like 5.6.
1086 // So we need to truncate trailing zeros to make it work as expected.
1087 if ($display === '' && strpos($value, '.') !== FALSE) {
1088 // Use round() to truncate trailing zeros, e.g:
1089 // 10.00 -> 10, 10.60 -> 10.6, 10.69 -> 10.69.
1090 $value = (string) round($value, 5);
1091 $display = $field['options'][$value] ??
'';
1097 $customFormat = NULL;
1099 // FIXME: Are there any legitimate reasons why $value would be an array?
1100 // Or should we throw an exception here if it is?
1101 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1103 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1104 $format = $field['date_format'] ??
NULL;
1107 if (array_key_exists($format, $actualPHPFormats)) {
1108 $customTimeFormat = (array) $actualPHPFormats[$format];
1109 switch (CRM_Utils_Array
::value('time_format', $field)) {
1111 $customTimeFormat[] = 'g:iA';
1115 $customTimeFormat[] = 'G:i';
1119 //If time is not selected remove time from value.
1120 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1122 $customFormat = implode(" ", $customTimeFormat);
1125 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1129 // In the context of displaying a profile, show file/image
1132 if (CRM_Utils_Rule
::positiveInteger($value)) {
1136 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1138 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1140 $display = $url['file_url'];
1144 // In other contexts show a paperclip icon
1145 if (CRM_Utils_Rule
::integer($value)) {
1146 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1148 $file_description = '';
1150 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1152 catch (CiviCRM_API3_Exception
$dontcare) {
1156 $display = "{$icons[$value]}{$file_description}";
1159 //CRM-18396, if filename is passed instead
1167 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1171 $display = nl2br($display);
1175 if ($field['data_type'] == 'Money' && isset($value)) {
1176 // $value can also be an array(while using IN operator from search builder or api).
1177 foreach ((array) $value as $val) {
1178 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1180 $display = implode(', ', $disp);
1188 * Set default values for custom data used in profile.
1190 * @param int $customFieldId
1192 * @param string $elementName
1193 * Custom field name.
1194 * @param array $defaults
1195 * Associated array of fields.
1196 * @param int $contactId
1200 * @param mixed $value
1201 * If passed - dont fetch value from db,.
1202 * just format the given value
1204 public static function setProfileDefaults(
1212 //get the type of custom field
1213 $customField = new CRM_Core_BAO_CustomField();
1214 $customField->id
= $customFieldId;
1215 $customField->find(TRUE);
1218 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1219 $value = $customField->default_value
;
1223 if (!isset($value)) {
1224 $info = self
::getTableColumnGroup($customFieldId);
1225 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1226 $result = CRM_Core_DAO
::executeQuery($query);
1227 if ($result->fetch()) {
1228 $value = $result->value
;
1232 if ($customField->data_type
== 'Country') {
1234 $config = CRM_Core_Config
::singleton();
1235 if ($config->defaultContactCountry
) {
1236 $value = CRM_Core_BAO_Country
::defaultContactCountry();
1242 //set defaults if mode is registration
1243 if (!trim($value) &&
1245 (!in_array($mode, [CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
]))
1247 $value = $customField->default_value
;
1250 if ($customField->data_type
== 'Money' && isset($value)) {
1251 $value = number_format($value, 2);
1253 if (self
::isSerialized($customField) && $value) {
1254 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1255 $defaults[$elementName] = [];
1256 $checkedValue = CRM_Utils_Array
::explodePadded($value);
1257 foreach ($customOption as $val) {
1258 if (in_array($val['value'], $checkedValue)) {
1259 if ($customField->html_type
== 'CheckBox') {
1260 $defaults[$elementName][$val['value']] = 1;
1263 $defaults[$elementName][$val['value']] = $val['value'];
1269 $defaults[$elementName] = $value;
1276 * @param int $contactID
1278 * @param int $fileID
1279 * @param bool $absolute
1281 * @param string $multiRecordWhereClause
1285 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1288 $params = ['id' => $cfID];
1290 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1291 $columnName = $defaults['column_name'];
1293 //table name of custom data
1294 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1295 $defaults['custom_group_id'],
1299 //query to fetch id from civicrm_file
1300 if ($multiRecordWhereClause) {
1301 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1304 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1306 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1311 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1316 $result['file_id'] = $fileID;
1318 if ($fileType == 'image/jpeg' ||
1319 $fileType == 'image/pjpeg' ||
1320 $fileType == 'image/gif' ||
1321 $fileType == 'image/x-png' ||
1322 $fileType == 'image/png'
1324 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1329 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1330 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1331 $url = CRM_Utils_System
::url('civicrm/file',
1332 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1333 $absolute, NULL, TRUE, TRUE
1335 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1337 // for non image files
1339 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1343 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1344 $url = CRM_Utils_System
::url('civicrm/file',
1345 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1346 $absolute, NULL, TRUE, TRUE
1348 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1356 * Format custom fields before inserting.
1358 * @param int $customFieldId
1360 * @param array $customFormatted
1362 * @param mixed $value
1363 * Value of custom field.
1364 * @param string $customFieldExtend
1365 * Custom field extends.
1366 * @param int $customValueId
1367 * Custom option value id.
1368 * @param int $entityId
1369 * Entity id (contribution, membership...).
1370 * @param bool $inline
1371 * Consider inline custom groups only.
1372 * @param bool $checkPermission
1373 * If false, do not include permissioning clause.
1374 * @param bool $includeViewOnly
1375 * If true, fields marked 'View Only' are included. Required for APIv3.
1377 * @return array|NULL
1378 * formatted custom field array
1380 public static function formatCustomField(
1381 $customFieldId, &$customFormatted, $value,
1382 $customFieldExtend, $customValueId = NULL,
1385 $checkPermission = TRUE,
1386 $includeViewOnly = FALSE
1388 //get the custom fields for the entity
1389 //subtype and basic type
1390 $customDataSubType = NULL;
1391 if ($customFieldExtend) {
1392 // This is the case when getFieldsForImport() requires fields
1393 // of subtype and its parent.CRM-5143
1394 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1395 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1396 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1397 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1398 if (is_array($customFieldExtend)) {
1399 $customFieldExtend = array_unique(array_values($customFieldExtend));
1404 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1414 if (!array_key_exists($customFieldId, $customFields)) {
1418 // return if field is a 'code' field
1419 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1423 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1425 if (!$customValueId &&
1426 // we always create new entites for is_multiple unless specified
1427 !$customFields[$customFieldId]['is_multiple'] &&
1433 WHERE entity_id={$entityId}";
1435 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1438 //fix checkbox, now check box always submits values
1439 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1441 // Note that only during merge this is not an array, and you can directly use value
1442 if (is_array($value)) {
1443 $selectedValues = [];
1444 foreach ($value as $selId => $val) {
1446 $selectedValues[] = $selId;
1449 if (!empty($selectedValues)) {
1450 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1452 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1460 elseif (self
::isSerialized($customFields[$customFieldId])) {
1461 $value = $value ? CRM_Utils_Array
::implodePadded($value) : '';
1464 if (self
::isSerialized($customFields[$customFieldId]) &&
1465 $customFields[$customFieldId]['data_type'] == 'String' &&
1466 !empty($customFields[$customFieldId]['text_length']) &&
1469 // lets make sure that value is less than the length, else we'll
1470 // be losing some data, CRM-7481
1471 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1472 // need to do a few things here
1474 // 1. lets find a new length
1475 $newLength = $customFields[$customFieldId]['text_length'];
1476 $minLength = strlen($value);
1477 while ($newLength < $minLength) {
1478 $newLength = $newLength * 2;
1481 // set the custom field meta data to have a length larger than value
1482 // alter the custom value table column to match this length
1483 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1488 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1489 if (!CRM_Utils_System
::isNull($value)) {
1490 $format = $customFields[$customFieldId]['date_format'];
1491 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1496 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1497 $customFields[$customFieldId]['data_type'] == 'Money'
1503 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1504 $value = CRM_Utils_Rule
::cleanMoney($value);
1508 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1509 $customFields[$customFieldId]['data_type'] == 'Country'
1519 if ($customFields[$customFieldId]['data_type'] == 'File') {
1520 if (empty($value)) {
1524 $config = CRM_Core_Config
::singleton();
1526 // If we are already passing the file id as a value then retrieve and set the file data
1527 if (CRM_Utils_Rule
::integer($value)) {
1528 $fileDAO = new CRM_Core_DAO_File();
1529 $fileDAO->id
= $value;
1530 $fileDAO->find(TRUE);
1533 $fName = $fileDAO->uri
;
1534 $mimeType = $fileDAO->mime_type
;
1538 $fName = $value['name'];
1539 $mimeType = $value['type'];
1542 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1544 // rename this file to go into the secure directory only if
1545 // user has uploaded new file not existing verfied on the basis of $fileID
1546 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1547 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1550 if ($customValueId && empty($fileID)) {
1555 $params = [1 => [$customValueId, 'Integer']];
1556 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1559 $fileDAO = new CRM_Core_DAO_File();
1562 $fileDAO->id
= $fileID;
1565 $fileDAO->uri
= $filename;
1566 $fileDAO->mime_type
= $mimeType;
1567 $fileDAO->upload_date
= date('YmdHis');
1569 $fileID = $fileDAO->id
;
1573 if (!is_array($customFormatted)) {
1574 $customFormatted = [];
1577 if (!array_key_exists($customFieldId, $customFormatted)) {
1578 $customFormatted[$customFieldId] = [];
1582 if ($customValueId) {
1583 $index = $customValueId;
1586 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1587 $customFormatted[$customFieldId][$index] = [];
1589 $customFormatted[$customFieldId][$index] = [
1590 'id' => $customValueId > 0 ?
$customValueId : NULL,
1592 'type' => $customFields[$customFieldId]['data_type'],
1593 'custom_field_id' => $customFieldId,
1594 'custom_group_id' => $groupID,
1595 'table_name' => $tableName,
1596 'column_name' => $columnName,
1597 'file_id' => $fileID,
1598 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1601 //we need to sort so that custom fields are created in the order of entry
1602 krsort($customFormatted[$customFieldId]);
1603 return $customFormatted;
1607 * Get default custom table schema.
1609 * @param array $params
1613 public static function defaultCustomTableSchema($params) {
1614 // add the id and extends_id
1616 'name' => $params['name'],
1617 'is_multiple' => $params['is_multiple'],
1618 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1622 'type' => 'int unsigned',
1625 'attributes' => 'AUTO_INCREMENT',
1626 'comment' => 'Default MySQL primary key',
1629 'name' => 'entity_id',
1630 'type' => 'int unsigned',
1632 'comment' => 'Table that this extends',
1633 'fk_table_name' => $params['extends_name'],
1634 'fk_field_name' => 'id',
1635 'fk_attributes' => 'ON DELETE CASCADE',
1640 // If on MySQL 5.6 include ROW_FORMAT=DYNAMIC to fix unit tests
1641 $databaseVersion = CRM_Utils_SQL
::getDatabaseVersion();
1642 if (version_compare($databaseVersion, '5.7', '<') && version_compare($databaseVersion, '5.6', '>=')) {
1643 $table['attributes'] = $table['attributes'] . ' ROW_FORMAT=DYNAMIC';
1646 if (!$params['is_multiple']) {
1647 $table['indexes'] = [
1650 'field_name_1' => 'entity_id',
1658 * Create custom field.
1660 * @param CRM_Core_DAO_CustomField $field
1661 * @param string $operation
1663 public static function createField($field, $operation) {
1664 $sql = str_repeat(' ', 8);
1665 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1666 $sql .= "ALTER TABLE " . $tableName;
1667 $sql .= self
::getAlterFieldSQL($field, $operation);
1669 // CRM-7007: do not i18n-rewrite this query
1670 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1672 $config = CRM_Core_Config
::singleton();
1673 if ($config->logging
) {
1674 // CRM-16717 not sure why this was originally limited to add.
1675 // For example custom tables can have field length changes - which need to flow through to logging.
1676 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1677 if ($operation === 'add' ||
$operation === 'modify') {
1678 $logging = new CRM_Logging_Schema();
1679 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name
]]);
1683 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
1687 * @param CRM_Core_DAO_CustomField $field
1688 * @param string $operation
1692 public static function getAlterFieldSQL($field, $operation) {
1693 $indexExist = $operation === 'add' ?
FALSE : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $field->id
, 'is_searchable');
1694 $params = self
::prepareCreateParams($field, $operation);
1695 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1696 // a function only used by Custom Field creation...
1697 $params['required'] = FALSE;
1698 return CRM_Core_BAO_SchemaHandler
::getFieldAlterSQL($params, $indexExist);
1702 * Determine whether it would be safe to move a field.
1704 * @param int $fieldID
1705 * FK to civicrm_custom_field.
1706 * @param int $newGroupID
1707 * FK to civicrm_custom_group.
1710 * array(string) or TRUE
1712 public static function _moveFieldValidate($fieldID, $newGroupID) {
1715 $field = new CRM_Core_DAO_CustomField();
1716 $field->id
= $fieldID;
1717 if (!$field->find(TRUE)) {
1718 $errors['fieldID'] = 'Invalid ID for custom field';
1722 $oldGroup = new CRM_Core_DAO_CustomGroup();
1723 $oldGroup->id
= $field->custom_group_id
;
1724 if (!$oldGroup->find(TRUE)) {
1725 $errors['fieldID'] = 'Invalid ID for old custom group';
1729 $newGroup = new CRM_Core_DAO_CustomGroup();
1730 $newGroup->id
= $newGroupID;
1731 if (!$newGroup->find(TRUE)) {
1732 $errors['newGroupID'] = 'Invalid ID for new custom group';
1738 FROM civicrm_custom_field a
1739 INNER JOIN civicrm_custom_field b
1741 AND a.label = b.label
1742 AND b.custom_group_id = %2
1745 1 => [$field->id
, 'Integer'],
1746 2 => [$newGroup->id
, 'Integer'],
1748 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1750 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1753 $tableName = $oldGroup->table_name
;
1754 $columnName = $field->column_name
;
1759 WHERE $columnName is not null
1761 $count = CRM_Core_DAO
::singleValueQuery($query);
1765 FROM civicrm_custom_group
1766 WHERE id IN ( %1, %2 )
1769 1 => [$oldGroup->id
, 'Integer'],
1770 2 => [$newGroup->id
, 'Integer'],
1773 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1775 while ($dao->fetch()) {
1776 $extends[] = $dao->extends;
1778 if ($extends[0] != $extends[1]) {
1779 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1783 return empty($errors) ?
TRUE : $errors;
1787 * Move a custom data field from one group (table) to another.
1789 * @param int $fieldID
1790 * FK to civicrm_custom_field.
1791 * @param int $newGroupID
1792 * FK to civicrm_custom_group.
1794 * @throws CRM_Core_Exception
1796 public static function moveField($fieldID, $newGroupID) {
1797 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1798 if (TRUE !== $validation) {
1799 throw new CRM_Core_Exception(implode(' ', $validation));
1801 $field = new CRM_Core_DAO_CustomField();
1802 $field->id
= $fieldID;
1805 $newGroup = new CRM_Core_DAO_CustomGroup();
1806 $newGroup->id
= $newGroupID;
1807 $newGroup->find(TRUE);
1809 $oldGroup = new CRM_Core_DAO_CustomGroup();
1810 $oldGroup->id
= $field->custom_group_id
;
1811 $oldGroup->find(TRUE);
1814 $add->custom_group_id
= $newGroup->id
;
1815 self
::createField($add, 'add');
1817 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1818 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1819 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1821 CRM_Core_DAO
::executeQuery($sql);
1824 $del->custom_group_id
= $oldGroup->id
;
1825 self
::createField($del, 'delete');
1829 CRM_Utils_System
::flushCache();
1833 * Create an option value for a custom field option group ID.
1835 * @param array $params
1836 * @param string $value
1837 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1838 * @param string $index
1839 * @param string $dataType
1841 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $index, $dataType) {
1842 if (strlen(trim($value))) {
1843 $optionValue = new CRM_Core_DAO_OptionValue();
1844 $optionValue->option_group_id
= $optionGroup->id
;
1845 $optionValue->label
= $params['option_label'][$index];
1846 $optionValue->name
= $params['option_name'][$index] ?? CRM_Utils_String
::titleToVar($params['option_label'][$index]);
1847 switch ($dataType) {
1849 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1853 $optionValue->value
= intval($value);
1857 $optionValue->value
= floatval($value);
1861 $optionValue->value
= trim($value);
1864 $optionValue->weight
= $params['option_weight'][$index];
1865 $optionValue->is_active
= $params['option_status'][$index] ??
FALSE;
1866 $optionValue->description
= $params['option_description'][$index] ??
NULL;
1867 $optionValue->color
= $params['option_color'][$index] ??
NULL;
1868 $optionValue->icon
= $params['option_icon'][$index] ??
NULL;
1869 $optionValue->save();
1874 * Prepare for the create operation.
1876 * Munge params, create the option values if needed.
1878 * This could be called by a single create or a batchCreate.
1880 * @param array $params
1884 protected static function prepareCreate($params) {
1885 $op = empty($params['id']) ?
'create' : 'edit';
1886 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1887 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1888 if ($op === 'create') {
1889 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1890 if (!isset($params['column_name'])) {
1891 // if add mode & column_name not present, calculate it.
1892 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1894 if (!isset($params['name'])) {
1895 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1899 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'column_name');
1902 $htmlType = $params['html_type'] ??
NULL;
1903 $dataType = $params['data_type'] ??
NULL;
1905 if ($htmlType === 'Select Date' && empty($params['date_format'])) {
1906 $params['date_format'] = Civi
::settings()->get('dateInputFormat');
1909 // Checkboxes are always serialized in current schema
1910 if ($htmlType == 'CheckBox') {
1911 $params['serialize'] = CRM_Core_DAO
::SERIALIZE_SEPARATOR_BOOKEND
;
1914 if (!empty($params['serialize'])) {
1915 if (isset($params['default_checkbox_option'])) {
1917 foreach (array_keys($params['default_checkbox_option']) as $k => $v) {
1918 if ($params['option_value'][$v]) {
1919 $defaultArray[] = $params['option_value'][$v];
1923 if (!empty($defaultArray)) {
1924 // also add the separator before and after the value per new convention (CRM-1604)
1925 $params['default_value'] = CRM_Utils_Array
::implodePadded($defaultArray);
1929 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])) {
1930 $params['default_value'] = $params['option_value'][$params['default_option']];
1935 // create any option group & values if required
1936 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1937 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)) {
1938 //CRM-16659: if option_value then create an option group for this custom field.
1939 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
1940 // first create an option group for this custom group
1941 $optionGroup = new CRM_Core_DAO_OptionGroup();
1942 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
1943 $optionGroup->title
= $params['label'];
1944 $optionGroup->is_active
= 1;
1945 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1946 $optionGroup->is_reserved
= 0;
1947 $optionGroup->data_type
= $dataType;
1948 $optionGroup->save();
1949 $params['option_group_id'] = $optionGroup->id
;
1950 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1951 foreach ($params['option_value'] as $k => $v) {
1952 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1958 // check for orphan option groups
1959 if (!empty($params['option_group_id'])) {
1960 if (!empty($params['id'])) {
1961 self
::fixOptionGroups($params['id'], $params['option_group_id']);
1964 // if we do not have a default value
1965 // retrieve it from one of the other custom fields which use this option group
1966 if (empty($params['default_value'])) {
1967 //don't insert only value separator as default value, CRM-4579
1968 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'], !empty($params['serialize']));
1970 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultValue))) {
1971 $params['default_value'] = $defaultValue;
1976 // Set default textarea attributes
1977 if ($op == 'create' && !isset($params['attributes']) && $htmlType == 'TextArea') {
1978 $params['attributes'] = 'rows=4, cols=60';
1984 * Create database entry for custom field and related option groups.
1986 * @param array $params
1988 * @return CRM_Core_DAO_CustomField
1990 protected static function createCustomFieldRecord($params) {
1991 $transaction = new CRM_Core_Transaction();
1992 $params = self
::prepareCreate($params);
1994 $customField = new CRM_Core_DAO_CustomField();
1995 $customField->copyValues($params);
1996 $customField->save();
1998 //create/drop the index when we toggle the is_searchable flag
1999 $op = empty($params['id']) ?
'add' : 'modify';
2000 if ($op !== 'modify') {
2001 if ($params['is_append_field_id_to_column_name']) {
2002 $params['column_name'] .= "_{$customField->id}";
2004 $customField->column_name
= $params['column_name'];
2005 $customField->save();
2008 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
2009 $transaction->commit();
2011 // make sure all values are present in the object for further processing
2012 $customField->find(TRUE);
2013 return $customField;
2017 * Move custom data from one contact to another.
2019 * This is currently the start of a refactoring. The theory is each
2020 * entity could have a 'move' function with a DAO default one to fall back on.
2022 * At the moment this only does a small part of the process - ie deleting a file field that
2023 * is about to be overwritten. However, the goal is the whole process around the move for
2024 * custom data should be in here.
2026 * This is currently called by the merge class but it makes sense that api could
2027 * expose move actions as moving (e.g) contributions feels like a common
2028 * ask that should be handled by the form layer.
2030 * @param int $oldContactID
2031 * @param int $newContactID
2032 * @param int[] $fieldIDs
2033 * Optional list field ids to move.
2035 * @throws \CiviCRM_API3_Exception
2036 * @throws \Exception
2038 public function move($oldContactID, $newContactID, $fieldIDs) {
2039 if (empty($fieldIDs)) {
2042 $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'];
2044 foreach ($fieldIDs as $fieldID) {
2045 $return[] = 'custom_' . $fieldID;
2047 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2048 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2050 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2051 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2052 $fieldTypesNotHandledInMergeAttempt = ['File'];
2053 foreach ($fields as $field) {
2054 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2055 if ($field['data_type'] === 'File' && !$isMultiple) {
2056 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2057 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2059 if (!empty($oldContact['custom_' . $field['id']])) {
2060 CRM_Core_DAO
::executeQuery("
2061 UPDATE civicrm_entity_file
2062 SET entity_id = $newContactID
2063 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2067 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2068 CRM_Core_DAO
::executeQuery(
2069 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2070 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2071 ON DUPLICATE KEY UPDATE
2072 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2079 * Get the database table name and column name for a custom field.
2081 * @param int $fieldID
2082 * The fieldID of the custom field.
2083 * @param bool $force
2084 * Force the sql to be run again (primarily used for tests).
2087 * fatal is fieldID does not exists, else array of tableName, columnName
2088 * @throws \CRM_Core_Exception
2090 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2091 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2092 $cache = CRM_Utils_Cache
::singleton();
2093 $fieldValues = $cache->get($cacheKey);
2094 if (empty($fieldValues) ||
$force) {
2096 SELECT cg.table_name, cf.column_name, cg.id
2097 FROM civicrm_custom_group cg,
2098 civicrm_custom_field cf
2099 WHERE cf.custom_group_id = cg.id
2101 $params = [1 => [$fieldID, 'Integer']];
2102 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2104 if (!$dao->fetch()) {
2105 throw new CRM_Core_Exception("Cannot find table and column information for Custom Field " . $fieldID);
2107 $fieldValues = [$dao->table_name
, $dao->column_name
, $dao->id
];
2108 $cache->set($cacheKey, $fieldValues);
2110 return $fieldValues;
2114 * Get custom option groups.
2116 * @deprecated Use the API OptionGroup.get
2118 * @param array $includeFieldIds
2119 * Ids of custom fields for which option groups must be included.
2121 * Currently this is required in the cases where option groups are to be included
2122 * for inactive fields : CRM-5369
2126 public static function customOptionGroup($includeFieldIds = NULL) {
2127 static $customOptionGroup = NULL;
2129 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2130 if ($cacheKey == 'force') {
2131 $customOptionGroup[$cacheKey] = NULL;
2134 if (empty($customOptionGroup[$cacheKey])) {
2135 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2137 //support for single as well as array format.
2138 if (!empty($includeFieldIds)) {
2139 if (is_array($includeFieldIds)) {
2140 $includeFieldIds = implode(',', $includeFieldIds);
2142 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2146 SELECT g.id, g.title
2147 FROM civicrm_option_group g
2148 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2149 WHERE {$whereClause}";
2151 $dao = CRM_Core_DAO
::executeQuery($query);
2152 while ($dao->fetch()) {
2153 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2157 return $customOptionGroup[$cacheKey];
2161 * Get defaults for new entity.
2165 public static function getDefaults() {
2167 'is_required' => FALSE,
2168 'is_searchable' => FALSE,
2169 'in_selector' => FALSE,
2170 'is_search_range' => FALSE,
2171 //CRM-15792 - Custom field gets disabled if is_active not set
2172 // this would ideally be a mysql default.
2173 'is_active' => TRUE,
2179 * Fix orphan groups.
2181 * @param int $customFieldId
2183 * @param int $optionGroupId
2186 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2187 // check if option group belongs to any custom Field else delete
2188 // get the current option group
2189 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2193 // get the updated option group
2194 // if both are same return
2195 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2199 // check if option group is related to any other field
2200 self
::checkOptionGroup($currentOptionGroupId);
2204 * Check if option group is related to more than one custom field.
2206 * @param int $optionGroupId
2209 public static function checkOptionGroup($optionGroupId) {
2212 FROM civicrm_custom_field
2213 WHERE option_group_id = {$optionGroupId}";
2215 $count = CRM_Core_DAO
::singleValueQuery($query);
2218 //delete the option group
2219 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2224 * Get option group default.
2226 * @param int $optionGroupId
2227 * @param bool $serialize
2229 * @return null|string
2231 public static function getOptionGroupDefault($optionGroupId, $serialize) {
2233 SELECT default_value, serialize
2234 FROM civicrm_custom_field
2235 WHERE option_group_id = {$optionGroupId}
2236 AND default_value IS NOT NULL";
2238 $dao = CRM_Core_DAO
::executeQuery($query);
2239 while ($dao->fetch()) {
2240 if ($dao->serialize
== $serialize) {
2241 return $dao->default_value
;
2243 $defaultValue = $dao->default_value
;
2246 // Convert serialization
2247 if (isset($defaultValue) && $serialize) {
2248 return CRM_Utils_Array
::implodePadded([$defaultValue]);
2250 elseif (isset($defaultValue)) {
2251 return CRM_Utils_Array
::explodePadded($defaultValue)[0];
2257 * Post process function.
2259 * @param array $params
2260 * @param int $entityID
2261 * @param string $customFieldExtends
2262 * @param bool $inline
2263 * @param bool $checkPermissions
2267 public static function postProcess(
2270 $customFieldExtends,
2272 $checkPermissions = TRUE
2276 foreach ($params as $key => $value) {
2277 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2279 // for autocomplete transfer hidden value instead of label
2280 if ($params[$key] && isset($params[$key . '_id'])) {
2281 $value = $params[$key . '_id'];
2284 // we need to append time with date
2285 if ($params[$key] && isset($params[$key . '_time'])) {
2286 $value .= ' ' . $params[$key . '_time'];
2289 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2292 $customFieldExtends,
2293 $customFieldInfo[1],
2304 * Get custom field ID from field/group name/title.
2306 * @param string $fieldName Field name or label
2307 * @param string|null $groupName (Optional) Group name or label
2308 * @param bool $fullString Whether to return "custom_123" or "123"
2310 * @return string|int|null
2311 * @throws \CiviCRM_API3_Exception
2313 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2314 $cacheKey = $groupName . '.' . $fieldName;
2315 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2316 $customFieldParams = [
2317 'name' => $fieldName,
2318 'label' => $fieldName,
2319 'options' => ['or' => [["name", "label"]]],
2323 $customFieldParams['custom_group_id.name'] = $groupName;
2324 $customFieldParams['custom_group_id.title'] = $groupName;
2325 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2328 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2330 if (empty($field['id'])) {
2331 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2332 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2335 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2336 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2341 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2343 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2347 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2353 public static function getNameFromID($ids) {
2354 if (is_array($ids)) {
2355 $ids = implode(',', $ids);
2358 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2359 FROM civicrm_custom_field f
2360 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2361 WHERE f.id IN ($ids)";
2363 $dao = CRM_Core_DAO
::executeQuery($sql);
2365 while ($dao->fetch()) {
2366 $result[$dao->id
] = [
2367 'field_name' => $dao->field_name
,
2368 'field_label' => $dao->field_label
,
2369 'group_name' => $dao->group_name
,
2370 'group_title' => $dao->group_title
,
2377 * Validate custom data.
2379 * @param array $params
2380 * Custom data submitted.
2381 * ie array( 'custom_1' => 'validate me' );
2384 * validation errors.
2386 public static function validateCustomData($params) {
2388 if (!is_array($params) ||
empty($params)) {
2392 //pick up profile fields.
2393 $profileFields = [];
2394 $ufGroupId = $params['ufGroupId'] ??
NULL;
2396 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2398 CRM_Core_Action
::VIEW
2402 //lets start w/ params.
2403 foreach ($params as $key => $value) {
2404 $customFieldID = self
::getKeyID($key);
2405 if (!$customFieldID) {
2409 //load the structural info for given field.
2410 $field = new CRM_Core_DAO_CustomField();
2411 $field->id
= $customFieldID;
2412 if (!$field->find(TRUE)) {
2415 $dataType = $field->data_type
;
2417 $profileField = CRM_Utils_Array
::value($key, $profileFields, []);
2418 $fieldTitle = $profileField['title'] ??
NULL;
2419 $isRequired = $profileField['is_required'] ??
NULL;
2421 $fieldTitle = $field->label
;
2424 //no need to validate.
2425 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2429 //lets validate first for required field.
2430 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2431 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
2435 //now time to take care of custom field form rules.
2436 $ruleName = $errorMsg = NULL;
2437 switch ($dataType) {
2439 $ruleName = 'integer';
2440 $errorMsg = ts('%1 must be an integer (whole number).',
2441 array(1 => $fieldTitle)
2446 $ruleName = 'money';
2447 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2448 array(1 => $fieldTitle)
2453 $ruleName = 'numeric';
2454 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2455 array(1 => $fieldTitle)
2460 $ruleName = 'wikiURL';
2461 $errorMsg = ts('%1 must be valid Website.',
2462 array(1 => $fieldTitle)
2467 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2469 $funName = "CRM_Utils_Rule::{$ruleName}";
2470 if (is_callable($funName)) {
2471 $valid = call_user_func($funName, $value);
2474 $errors[$key] = $errorMsg;
2483 * Is this field a multi record field.
2485 * @param int $customId
2489 public static function isMultiRecordField($customId) {
2490 $isMultipleWithGid = FALSE;
2491 if (!is_numeric($customId)) {
2492 $customId = self
::getKeyID($customId);
2494 if (is_numeric($customId)) {
2495 $sql = "SELECT cg.id cgId
2496 FROM civicrm_custom_group cg
2497 INNER JOIN civicrm_custom_field cf
2498 ON cg.id = cf.custom_group_id
2499 WHERE cf.id = %1 AND cg.is_multiple = 1";
2500 $params[1] = [$customId, 'Integer'];
2501 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2502 if ($dao->fetch()) {
2504 $isMultipleWithGid = $dao->cgId
;
2509 return $isMultipleWithGid;
2513 * Does this field type have any select options?
2515 * @param array $field
2519 public static function hasOptions($field) {
2520 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2521 $field = (array) $field;
2522 // This will include boolean fields with Yes/No options.
2523 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2526 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2527 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2528 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2531 if (strpos($field['html_type'], 'Select') !== FALSE) {
2534 return !empty($field['option_group_id']);
2538 * Does this field store a serialized string?
2540 * @param CRM_Core_DAO_CustomField|array $field
2544 public static function isSerialized($field) {
2545 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2546 $html_type = is_object($field) ?
$field->html_type
: $field['html_type'];
2547 // APIv3 has a "legacy" mode where it returns old-style html_type of "Multi-Select"
2548 // If anyone is using this function in conjunction with legacy api output, we'll accomodate:
2549 if ($html_type === 'CheckBox' ||
strpos($html_type, 'Multi') !== FALSE) {
2552 // Otherwise this is the new standard as of 5.27
2553 return is_object($field) ?
!empty($field->serialize
) : !empty($field['serialize']);
2557 * Get api entity for this field
2561 public function getEntity() {
2562 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2563 return in_array($entity, ['Individual', 'Household', 'Organization']) ?
'Contact' : $entity;
2567 * Set pseudoconstant properties for field metadata.
2569 * @param array $field
2570 * @param string|null $optionGroupName
2572 private static function getOptionsForField(&$field, $optionGroupName) {
2573 if ($optionGroupName) {
2574 $field['pseudoconstant'] = [
2575 'optionGroupName' => $optionGroupName,
2576 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2579 elseif ($field['data_type'] == 'Boolean') {
2580 $field['pseudoconstant'] = [
2581 'callback' => 'CRM_Core_SelectValues::boolean',
2584 elseif ($field['data_type'] == 'Country') {
2585 $field['pseudoconstant'] = [
2586 'table' => 'civicrm_country',
2587 'keyColumn' => 'id',
2588 'labelColumn' => 'name',
2589 'nameColumn' => 'iso_code',
2592 elseif ($field['data_type'] == 'StateProvince') {
2593 $field['pseudoconstant'] = [
2594 'table' => 'civicrm_state_province',
2595 'keyColumn' => 'id',
2596 'labelColumn' => 'name',
2602 * @param CRM_Core_DAO_CustomField $field
2603 * @param 'add|modify' $operation
2607 protected static function prepareCreateParams($field, $operation) {
2608 $tableName = CRM_Core_DAO
::getFieldValue(
2609 'CRM_Core_DAO_CustomGroup',
2610 $field->custom_group_id
,
2615 'table_name' => $tableName,
2616 'operation' => $operation,
2617 'name' => $field->column_name
,
2618 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2622 'required' => $field->is_required
,
2623 'searchable' => $field->is_searchable
,
2626 if ($operation == 'delete') {
2627 $fkName = "{$tableName}_{$field->column_name}";
2628 if (strlen($fkName) >= 48) {
2629 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2631 $params['fkName'] = $fkName;
2633 if ($field->data_type
== 'Country' && !self
::isSerialized($field)) {
2634 $params['fk_table_name'] = 'civicrm_country';
2635 $params['fk_field_name'] = 'id';
2636 $params['fk_attributes'] = 'ON DELETE SET NULL';
2638 elseif ($field->data_type
== 'StateProvince' && !self
::isSerialized($field)) {
2639 $params['fk_table_name'] = 'civicrm_state_province';
2640 $params['fk_field_name'] = 'id';
2641 $params['fk_attributes'] = 'ON DELETE SET NULL';
2643 elseif ($field->data_type
== 'StateProvince' ||
$field->data_type
== 'Country') {
2644 $params['type'] = 'varchar(255)';
2646 elseif ($field->data_type
== 'File') {
2647 $params['fk_table_name'] = 'civicrm_file';
2648 $params['fk_field_name'] = 'id';
2649 $params['fk_attributes'] = 'ON DELETE SET NULL';
2651 elseif ($field->data_type
== 'ContactReference') {
2652 $params['fk_table_name'] = 'civicrm_contact';
2653 $params['fk_field_name'] = 'id';
2654 $params['fk_attributes'] = 'ON DELETE SET NULL';
2656 if (isset($field->default_value
)) {
2657 $params['default'] = "'{$field->default_value}'";