3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Business objects for managing custom data fields.
21 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
24 * Array to hold (formatted) fields for import
28 public static $_importFields = NULL;
31 * Build and retrieve the list of data types and descriptions.
34 * Data type => Description
36 public static function dataType() {
38 'String' => ts('Alphanumeric'),
39 'Int' => ts('Integer'),
40 'Float' => ts('Number'),
41 'Money' => ts('Money'),
44 'Boolean' => ts('Yes or No'),
45 'StateProvince' => ts('State/Province'),
46 'Country' => ts('Country'),
49 'ContactReference' => ts('Contact Reference'),
54 * Build the map of custom field's data types and there respective Util type
57 * Data data-type => CRM_Utils_Type
59 public static function dataToType() {
61 'String' => CRM_Utils_Type
::T_STRING
,
62 'Int' => CRM_Utils_Type
::T_INT
,
63 'Money' => CRM_Utils_Type
::T_MONEY
,
64 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
65 'Float' => CRM_Utils_Type
::T_FLOAT
,
66 'Date' => CRM_Utils_Type
::T_DATE
,
67 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
68 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
69 'StateProvince' => CRM_Utils_Type
::T_INT
,
70 'File' => CRM_Utils_Type
::T_STRING
,
71 'Link' => CRM_Utils_Type
::T_STRING
,
72 'ContactReference' => CRM_Utils_Type
::T_INT
,
73 'Country' => CRM_Utils_Type
::T_INT
,
78 * Takes an associative array and creates a custom field object.
80 * This function is invoked from within the web form layer and also from the api layer
82 * @param array $params
83 * (reference) an assoc array of name/value pairs.
85 * @return CRM_Core_DAO_CustomField
87 public static function create($params) {
88 $customField = self
::createCustomFieldRecord($params);
89 $op = empty($params['id']) ?
'add' : 'modify';
90 self
::createField($customField, $op);
92 CRM_Utils_Hook
::post(($op === 'add' ?
'create' : 'edit'), 'CustomField', $customField->id
, $customField);
94 CRM_Utils_System
::flushCache();
95 // Flush caches is not aggressive about clearing the specific cache we know we want to clear
96 // so do it manually. Ideally we wouldn't need to clear others...
97 Civi
::cache('metadata')->clear();
103 * Create/ update several fields at once in a mysql efficient way.
105 * https://lab.civicrm.org/dev/core/issues/1093
107 * The intention is that apiv4 would expose any BAO with bulkSave as a new action.
109 * @param array $bulkParams
110 * Array of arrays as would be passed into create
111 * @param array $defaults
112 * Default parameters to be be merged into each of the params.
114 * @throws \CiviCRM_API3_Exception
116 public static function bulkSave($bulkParams, $defaults = []) {
117 $addedColumns = $sql = $tables = $customFields = [];
118 foreach ($bulkParams as $index => $fieldParams) {
119 $params = array_merge($defaults, $fieldParams);
120 $customField = self
::createCustomFieldRecord($params);
121 $fieldSQL = self
::getAlterFieldSQL($customField, empty($params['id']) ?
'add' : 'modify');
122 if (!isset($params['custom_group_id'])) {
123 $params['custom_group_id'] = civicrm_api3('CustomField', 'getvalue', ['id' => $customField->id
, 'return' => 'custom_group_id']);
125 if (!isset($params['table_name'])) {
126 if (!isset($tables[$params['custom_group_id']])) {
127 $tables[$params['custom_group_id']] = civicrm_api3('CustomGroup', 'getvalue', [
128 'id' => $params['custom_group_id'],
129 'return' => 'table_name',
132 $params['table_name'] = $tables[$params['custom_group_id']];
134 $sql[$params['table_name']][] = $fieldSQL;
135 $addedColumns[$params['table_name']][] = $customField->name
;
136 $customFields[$index] = $customField;
139 foreach ($sql as $tableName => $statements) {
140 // CRM-7007: do not i18n-rewrite this query
141 CRM_Core_DAO
::executeQuery("ALTER TABLE $tableName " . implode(', ', $statements), [], TRUE, NULL, FALSE, FALSE);
143 if (CRM_Core_Config
::singleton()->logging
) {
144 $logging = new CRM_Logging_Schema();
145 $logging->fixSchemaDifferencesFor($tableName, ['ADD' => $addedColumns[$tableName]]);
148 Civi
::service('sql_triggers')->rebuild($params['table_name'], TRUE);
150 CRM_Utils_System
::flushCache();
151 foreach ($customFields as $index => $customField) {
152 CRM_Utils_Hook
::post(empty($bulkParams[$index]['id']) ?
'create' : 'edit', 'CustomField', $customField->id
, $customField);
157 * Fetch object based on array of properties.
159 * @param array $params
160 * An assoc array of name/value pairs.
161 * @param array $defaults
162 * (reference ) an assoc array to hold the flattened values.
164 * @return CRM_Core_DAO_CustomField
166 public static function retrieve($params, &$defaults) {
167 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
171 * Update the is_active flag in the db.
174 * Id of the database record.
175 * @param bool $is_active
176 * Value we want to set the is_active field.
179 * true if we found and updated the object, else false
181 public static function setIsActive($id, $is_active) {
183 CRM_Utils_System
::flushCache();
185 //enable-disable CustomField
186 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
187 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
191 * Get the field title.
199 public static function getTitle($id) {
200 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
204 * @param string $context
207 public function getOptions($context = NULL) {
208 CRM_Core_DAO
::buildOptionsContext($context);
213 $cacheKey = "CRM_Core_BAO_CustomField_getOptions_{$this->id}_$context";
214 $cache = CRM_Utils_Cache
::singleton();
215 $options = $cache->get($cacheKey);
216 if (!isset($options)) {
217 if (!$this->data_type ||
!$this->custom_group_id
) {
221 // This will hold the list of options in format key => label
224 if (!empty($this->option_group_id
)) {
225 $options = CRM_Core_OptionGroup
::valuesByID(
226 $this->option_group_id
, FALSE, FALSE, FALSE, $context == 'validate' ?
'name' : 'label', !($context == 'validate' ||
$context == 'get')
229 elseif ($this->data_type
=== 'StateProvince') {
230 $options = CRM_Core_PseudoConstant
::stateProvince();
232 elseif ($this->data_type
=== 'Country') {
233 $options = $context == 'validate' ? CRM_Core_PseudoConstant
::countryIsoCode() : CRM_Core_PseudoConstant
::country();
235 elseif ($this->data_type
=== 'Boolean') {
236 $options = $context == 'validate' ?
[0, 1] : CRM_Core_SelectValues
::boolean();
238 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
239 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, ['context' => $context]);
240 $cache->set($cacheKey, $options);
248 public static function buildOptions($fieldName, $context = NULL, $props = []) {
249 $options = parent
::buildOptions($fieldName, $context, $props);
250 // This provides legacy support for APIv3, allowing no-longer-existent html types
251 if ($fieldName == 'html_type' && isset($props['version']) && $props['version'] == 3) {
252 $options['Multi-Select'] = 'Multi-Select';
253 $options['Select Country'] = 'Select Country';
254 $options['Multi-Select Country'] = 'Multi-Select Country';
255 $options['Select State/Province'] = 'Select State/Province';
256 $options['Multi-Select State/Province'] = 'Multi-Select State/Province';
262 * Store and return an array of all active custom fields.
264 * @param string $customDataType
265 * Type of Custom Data; 'ANY' is a synonym for "all contact data types".
266 * @param bool $showAll
267 * If true returns all fields (includes disabled fields).
268 * @param bool $inline
269 * If true returns all inline fields (includes disabled fields).
270 * @param int $customDataSubType
271 * Custom Data sub type value.
272 * @param int $customDataSubName
273 * Custom Data sub name value.
274 * @param bool $onlyParent
275 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
276 * @param bool $onlySubType
277 * Return only custom data for subtype.
278 * @param bool $checkPermission
279 * If false, do not include permissioning clause.
282 * an array of active custom fields.
283 * @throws \CRM_Core_Exception
285 public static function &getFields(
286 $customDataType = 'Individual',
289 $customDataSubType = NULL,
290 $customDataSubName = NULL,
292 $onlySubType = FALSE,
293 $checkPermission = TRUE
295 if (empty($customDataType)) {
296 $customDataType = ['Contact', 'Individual', 'Organization', 'Household'];
298 if ($customDataType === 'ANY') {
299 // NULL should have been respected but the line above broke that.
300 // boo for us not having enough unit tests back them.
301 $customDataType = NULL;
303 if ($customDataType && !is_array($customDataType)) {
305 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
306 // This is the case when getFieldsForImport() requires fields
307 // limited strictly to a subtype.
308 $customDataSubType = $customDataType;
309 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
313 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
314 // this makes the method flexible to support retrieving fields
315 // for multiple extends value.
316 $customDataType = [$customDataType];
320 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
322 if (is_array($customDataType)) {
323 $cacheKey = implode('_', $customDataType);
326 $cacheKey = $customDataType;
329 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
330 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
331 $cacheKey .= $showAll ?
'_1' : '_0';
332 $cacheKey .= $inline ?
'_1_' : '_0_';
333 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
334 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
335 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
336 $cacheKey .= '_' . CRM_Core_Config
::domainID() . '_';
338 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
340 // also get the permission stuff here
341 if ($checkPermission) {
342 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
347 $permissionClause = '(1)';
350 // lets md5 permission clause and take first 8 characters
351 $cacheKey .= substr(md5($permissionClause), 0, 8);
353 if (strlen($cacheKey) > 40) {
354 $cacheKey = md5($cacheKey);
357 if (!self
::$_importFields ||
358 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
360 if (!self
::$_importFields) {
361 self
::$_importFields = [];
364 // check if we can retrieve from database cache
365 $fields = Civi
::Cache('fields')->get("custom importableFields $cacheKey");
367 if ($fields === NULL) {
368 $cfTable = self
::getTableName();
371 if (is_array($customDataType)) {
373 foreach ($customDataType as $dataType) {
374 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
375 if (in_array($dataType, ['Individual', 'Household', 'Organization'])) {
376 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
379 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
381 $value = $value ?
$value . ", {$val}" : $val;
385 $extends = "AND $cgTable.extends IN ( $value ) ";
389 if (!empty($customDataType) && empty($extends)) {
390 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
391 self
::$_importFields[$cacheKey] = [];
392 return self
::$_importFields[$cacheKey];
396 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
398 // Temporary hack - in 5.27 a new field is added to civicrm_custom_field. There is a high
399 // risk this function is called before the upgrade page can be reached and if
400 // so it will potentially result in fatal error.
401 $serializeField = CRM_Core_BAO_Domain
::isDBVersionAtLeast('5.27.alpha1') ?
"$cfTable.serialize," : '';
403 $query = "SELECT $cfTable.id, $cfTable.label,
407 $cfTable.default_value,
408 $cfTable.options_per_line, $cfTable.text_length,
409 $cfTable.custom_group_id,
410 $cfTable.is_required,
411 $cfTable.column_name,
412 $cgTable.extends, $cfTable.is_search_range,
413 $cgTable.extends_entity_column_value,
414 $cgTable.extends_entity_column_id,
416 $cfTable.option_group_id,
417 $cfTable.date_format,
418 $cfTable.time_format,
419 $cgTable.is_multiple,
422 og.name as option_group_name
425 ON $cfTable.custom_group_id = $cgTable.id
426 LEFT JOIN civicrm_option_group og
427 ON $cfTable.option_group_id = og.id
431 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
435 $query .= " AND $cgTable.style = 'Inline' ";
438 //get the custom fields for specific type in
439 //combination with fields those support any type.
440 if (!empty($customDataSubType)) {
442 foreach ($customDataSubType as $subtype) {
443 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($subtype, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
;
444 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
447 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
449 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
452 if ($customDataSubName) {
453 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
456 // also get the permission stuff here
457 if ($checkPermission) {
458 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
463 $permissionClause = '(1)';
466 $query .= " $extends AND $permissionClause
467 ORDER BY $cgTable.weight, $cgTable.title,
468 $cfTable.weight, $cfTable.label";
470 $dao = CRM_Core_DAO
::executeQuery($query);
473 while (($dao->fetch()) != NULL) {
474 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
475 $fields[$dao->id
]['id'] = $dao->id
;
476 $fields[$dao->id
]['label'] = $dao->label
;
477 // This seems broken, but not in a new way.
478 $fields[$dao->id
]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
479 // To support the consolidation of various functions & their expectations.
480 $fields[$dao->id
]['title'] = $dao->label
;
481 $fields[$dao->id
]['custom_field_id'] = $dao->id
;
482 $fields[$dao->id
]['groupTitle'] = $dao->title
;
483 $fields[$dao->id
]['data_type'] = $dao->data_type
;
484 $fields[$dao->id
]['name'] = 'custom_' . $dao->id
;
485 $fields[$dao->id
]['type'] = CRM_Utils_Array
::value($dao->data_type
, self
::dataToType());
486 $fields[$dao->id
]['html_type'] = $dao->html_type
;
487 $fields[$dao->id
]['default_value'] = $dao->default_value
;
488 $fields[$dao->id
]['text_length'] = $dao->text_length
;
489 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
490 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
491 $fields[$dao->id
]['extends'] = $dao->extends;
492 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
493 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
494 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
495 $fields[$dao->id
]['is_view'] = $dao->is_view
;
496 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
497 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
498 $fields[$dao->id
]['date_format'] = $dao->date_format
;
499 $fields[$dao->id
]['time_format'] = $dao->time_format
;
500 $fields[$dao->id
]['is_required'] = $dao->is_required
;
501 $fields[$dao->id
]['table_name'] = $dao->table_name
;
502 $fields[$dao->id
]['column_name'] = $dao->column_name
;
503 $fields[$dao->id
]['serialize'] = $serializeField ?
$dao->serialize
: (int) self
::isSerialized($dao);
504 $fields[$dao->id
]['where'] = $dao->table_name
. '.' . $dao->column_name
;
505 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
506 $fields[$dao->id
]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery
::$extendsMap) ? CRM_Core_BAO_CustomQuery
::$extendsMap[$dao->extends] : '';
507 if (in_array($dao->extends, CRM_Contact_BAO_ContactType
::subTypes())) {
508 // if $extends is a subtype, refer contact table
509 $fields[$dao->id
]['extends_table'] = 'civicrm_contact';
511 // Search table is used by query object searches..
512 $fields[$dao->id
]['search_table'] = ($fields[$dao->id
]['extends_table'] == 'civicrm_contact') ?
'contact_a' : $fields[$dao->id
]['extends_table'];
513 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
516 Civi
::cache('fields')->set("custom importableFields $cacheKey", $fields);
518 self
::$_importFields[$cacheKey] = $fields;
521 return self
::$_importFields[$cacheKey];
525 * Return the field ids and names (with groups) for import purpose.
527 * @param int|string $contactType Contact type
528 * @param bool $showAll
529 * If true returns all fields (includes disabled fields).
530 * @param bool $onlyParent
531 * Return fields ONLY related to basic types.
532 * @param bool $search
533 * When called from search and multiple records need to be returned.
534 * @param bool $checkPermission
535 * If false, do not include permissioning clause.
537 * @param bool $withMultiple
541 public static function getFieldsForImport(
542 $contactType = 'Individual',
546 $checkPermission = TRUE,
547 $withMultiple = FALSE
549 // Note: there are situations when we want getFieldsForImport() return fields related
550 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
551 $fields = &self
::getFields($contactType,
561 $importableFields = [];
562 foreach ($fields as $id => $values) {
563 // for now we should not allow multiple fields in profile / export etc, hence unsetting
565 (!empty($values['is_multiple']) && !$withMultiple)
569 if (!empty($values['text_length'])) {
570 $values['maxlength'] = (int) $values['text_length'];
573 /* generate the key for the fields array */
576 $importableFields[$key] = $values;
577 $importableFields[$key]['import'] = 1;
580 return $importableFields;
584 * Get the field id from an import key.
594 public static function getKeyID($key, $all = FALSE) {
596 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
603 CRM_Utils_Array
::value(2, $match),
607 return $all ?
[NULL, NULL] : NULL;
611 * Use the cache to get all values of a specific custom field.
613 * @param int $fieldID
614 * The custom field ID.
616 * @return CRM_Core_BAO_CustomField
618 * @throws CRM_Core_Exception
620 public static function getFieldObject($fieldID) {
621 $field = new CRM_Core_BAO_CustomField();
623 // check if we can get the field values from the system cache
624 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
625 $cache = CRM_Utils_Cache
::singleton();
626 $fieldValues = $cache->get($cacheKey);
627 if (empty($fieldValues)) {
628 $field->id
= $fieldID;
629 if (!$field->find(TRUE)) {
630 throw new CRM_Core_Exception('Cannot find Custom Field');
634 CRM_Core_DAO
::storeValues($field, $fieldValues);
636 $cache->set($cacheKey, $fieldValues);
639 $field->copyValues($fieldValues);
646 * Add a custom field to an existing form.
648 * @param CRM_Core_Form $qf
649 * Form object (reference).
650 * @param string $elementName
651 * Name of the custom field.
652 * @param int $fieldId
653 * @param bool $useRequired
654 * True if required else false.
655 * @param bool $search
656 * True if used for search else false.
657 * @param string $label
658 * Label for custom field.
659 * @return \HTML_QuickForm_Element|null
660 * @throws \CiviCRM_API3_Exception
662 public static function addQuickFormElement(
663 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
665 $field = self
::getFieldObject($fieldId);
666 $widget = $field->html_type
;
668 $customFieldAttributes = [];
670 if (!isset($label)) {
671 $label = $field->label
;
674 // DAO stores attributes as a string, but it's hard to manipulate and
675 // CRM_Core_Form::add() wants them as an array.
676 $fieldAttributes = self
::attributesFromString($field->attributes
);
678 // Custom field HTML should indicate group+field name
679 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
680 $fieldAttributes['data-crm-custom'] = $groupName . ':' . $field->name
;
682 // Fixed for Issue CRM-2183
683 if ($widget == 'TextArea' && $search) {
687 $placeholder = $search ?
ts('- any %1 -', [1 => $label]) : ts('- select %1 -', [1 => $label]);
689 if (in_array($widget, [
694 $options = $field->getOptions($search ?
'search' : 'create');
696 // Consolidate widget types to simplify the below switch statement
701 // Search field is always multi-select
702 if ($search ||
(self
::isSerialized($field) && $widget === 'Select')) {
703 $fieldAttributes['class'] = ltrim(($fieldAttributes['class'] ??
'') . ' huge');
704 $fieldAttributes['multiple'] = 'multiple';
705 $fieldAttributes['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 && $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 $fieldAttributes = array_merge($fieldAttributes, $customFieldAttributes);
720 $rangeDataTypes = ['Int', 'Float', 'Money'];
722 // at some point in time we might want to split the below into small functions
727 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
728 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $fieldAttributes);
729 $qf->add('text', $elementName . '_to', ts('To'), $fieldAttributes);
732 if ($field->text_length
) {
733 $fieldAttributes['maxlength'] = $field->text_length
;
734 if ($field->text_length
< 20) {
735 $fieldAttributes['size'] = $field->text_length
;
738 $element = $qf->add('text', $elementName, $label,
740 $useRequired && !$search
746 $fieldAttributes['rows'] = $field->note_rows ??
4;
747 $fieldAttributes['cols'] = $field->note_columns ??
60;
749 if ($field->text_length
) {
750 $fieldAttributes['maxlength'] = $field->text_length
;
752 $element = $qf->add('textarea',
756 $useRequired && !$search
761 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
762 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
763 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
766 'date' => $field->date_format
,
767 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
768 //CRM-18487 - max date should be the last date of the year.
769 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
770 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
772 if ($field->is_search_range
&& $search) {
773 $qf->add('datepicker', $elementName . '_from', $label, $fieldAttributes +
array('placeholder' => ts('From')), FALSE, $params);
774 $qf->add('datepicker', $elementName . '_to', NULL, $fieldAttributes +
array('placeholder' => ts('To')), FALSE, $params);
777 $element = $qf->add('datepicker', $elementName, $label, $fieldAttributes, $useRequired && !$search, $params);
782 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
783 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $fieldAttributes);
784 $qf->add('text', $elementName . '_to', ts('To'), $fieldAttributes);
787 $fieldAttributes = array_merge($fieldAttributes, $customFieldAttributes);
788 if ($search ||
empty($useRequired)) {
789 $fieldAttributes['allowClear'] = TRUE;
791 $qf->addRadio($elementName, $label, $options, $fieldAttributes, NULL, $useRequired);
795 // For all select elements
797 $fieldAttributes['class'] = ltrim(($fieldAttributes['class'] ??
'') . ' crm-select2');
798 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
799 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $fieldAttributes);
800 $qf->add('text', $elementName . '_to', ts('To'), $fieldAttributes);
803 if (empty($fieldAttributes['multiple'])) {
804 $options = ['' => $placeholder] +
$options;
806 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $fieldAttributes);
808 // Add and/or option for fields that store multiple values
809 if ($search && self
::isSerialized($field)) {
810 $qf->addRadio($elementName . '_operator', '', [
813 ], [], NULL, FALSE, [
814 'or' => ['title' => ts('Results may contain any of the selected options')],
815 'and' => ['title' => ts('Results must have all of the selected options')],
817 $qf->setDefaults([$elementName . '_operator' => 'or']);
824 foreach ($options as $v => $l) {
825 // TODO: I'm not sure if this is supposed to exclude whatever might be
826 // in $field->attributes (available in array format as
827 // $fieldAttributes). Leaving as-is for now.
828 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
831 $group = $element = $qf->addGroup($check, $elementName, $label);
832 $optionEditKey = 'data-option-edit-path';
833 if (isset($customFieldAttributes[$optionEditKey])) {
834 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
837 if ($useRequired && !$search) {
838 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
843 // we should not build upload file in search mode
848 strtolower($field->html_type
),
852 $useRequired && !$search
854 $qf->addUploadElement($elementName);
857 case 'RichTextEditor':
858 $fieldAttributes['rows'] = $field->note_rows
;
859 $fieldAttributes['cols'] = $field->note_columns
;
860 if ($field->text_length
) {
861 $fieldAttributes['maxlength'] = $field->text_length
;
863 $element = $qf->add('wysiwyg', $elementName, $label, $fieldAttributes, $useRequired && !$search);
866 case 'Autocomplete-Select':
867 static $customUrls = [];
868 if ($field->data_type
== 'ContactReference') {
869 // break if contact does not have permission to access ContactReference
870 if (!CRM_Core_Permission
::check('access contact reference fields')) {
873 $fieldAttributes['class'] = ltrim(($fieldAttributes['class'] ??
'') . ' crm-form-contact-reference huge');
874 $fieldAttributes['data-api-entity'] = 'Contact';
875 $element = $qf->add('text', $elementName, $label, $fieldAttributes, $useRequired && !$search);
877 $urlParams = "context=customfield&id={$field->id}";
878 $idOfelement = $elementName;
879 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
880 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
881 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
882 // rather than layering on more hacks.
883 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
884 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') +
1)), 0, -1);
886 $customUrls[$idOfelement] = CRM_Utils_System
::url('civicrm/ajax/contactref',
893 // FIXME: This won't work with customFieldOptions hook
894 $fieldAttributes +
= [
895 'entity' => 'OptionValue',
896 'placeholder' => $placeholder,
897 'multiple' => $search,
899 'params' => ['option_group_id' => $field->option_group_id
, 'is_active' => 1],
902 $element = $qf->addEntityRef($elementName, $label, $fieldAttributes, $useRequired && !$search);
905 $qf->assign('customUrls', $customUrls);
909 switch ($field->data_type
) {
911 // integers will have numeric rule applied to them.
912 if ($field->is_search_range
&& $search) {
913 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', [1 => $label]), 'integer');
914 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', [1 => $label]), 'integer');
916 elseif ($widget == 'Text') {
917 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', [1 => $label]), 'integer');
922 if ($field->is_search_range
&& $search) {
923 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', [1 => $label]), 'numeric');
924 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', [1 => $label]), 'numeric');
926 elseif ($widget == 'Text') {
927 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', [1 => $label]), 'numeric');
932 if ($field->is_search_range
&& $search) {
933 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
934 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
936 elseif ($widget == 'Text') {
937 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
942 $element->setAttribute('class', "url");
943 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
946 if ($field->is_view
&& !$search) {
947 $qf->freeze($elementName);
953 * Take a string of HTML element attributes and turn it into an associative
956 * @param string $attrString
957 * The attributes as a string, e.g. `rows=3 cols=40`.
960 * The attributes as an array, e.g. `['rows' => 3, 'cols' => 40]`.
962 public static function attributesFromString($attrString) {
964 foreach (explode(' ', $attrString) as $at) {
965 if (strpos($at, '=')) {
966 list($k, $v) = explode('=', $at);
967 $attributes[$k] = trim($v, ' "');
974 * Delete the Custom Field.
976 * @param object $field
979 public static function deleteField($field) {
980 CRM_Utils_System
::flushCache();
982 // first delete the custom option group and values associated with this field
983 if ($field->option_group_id
) {
984 //check if option group is related to any other field, if
985 //not delete the option group and related option values
986 self
::checkOptionGroup($field->option_group_id
);
989 // next drop the column from the custom value table
990 self
::createField($field, 'delete');
993 CRM_Core_BAO_UFField
::delUFField($field->id
);
994 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
996 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
1000 * @param string|int|array|null $value
1001 * @param CRM_Core_BAO_CustomField|int|array|string $field
1002 * @param int $entityId
1006 * @throws \CRM_Core_Exception
1008 public static function displayValue($value, $field, $entityId = NULL) {
1009 $field = is_array($field) ?
$field['id'] : $field;
1010 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1013 throw new CRM_Core_Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1016 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1017 $field = self
::getFieldObject($fieldId);
1020 $fieldInfo = ['options' => $field->getOptions()] +
(array) $field;
1022 $displayValue = self
::formatDisplayValue($value, $fieldInfo, $entityId);
1024 // Call hook to alter display value.
1025 CRM_Utils_Hook
::alterCustomFieldDisplayValue($displayValue, $value, $entityId, $fieldInfo);
1027 return $displayValue;
1031 * Lower-level logic for rendering a custom field value
1033 * @param string|array $value
1034 * @param array $field
1035 * @param int|null $entityId
1039 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1041 if (self
::isSerialized($field) && !is_array($value)) {
1042 $value = CRM_Utils_Array
::explodePadded($value);
1045 if ($field['html_type'] == 'CheckBox' && $value) {
1046 $value = CRM_Utils_Array
::convertCheckboxFormatToArray($value);
1049 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1051 switch ($field['html_type']) {
1054 case 'Autocomplete-Select':
1057 if ($field['data_type'] == 'ContactReference' && $value) {
1058 if (is_numeric($value)) {
1059 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1065 elseif (is_array($value)) {
1067 foreach ($value as $key => $val) {
1068 $v[] = $field['options'][$val] ??
NULL;
1070 $display = implode(', ', $v);
1073 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1074 // For float type (see Number and Money) $value would be decimal like
1075 // 1.00 (because it is stored in db as decimal), while options array
1076 // key would be integer like 1. In this case expression on line above
1077 // would return empty string (default value), despite the fact that
1078 // matching option exists in the array.
1079 // In such cases we could just get intval($value) and fetch matching
1080 // option again, but this would not work if key is float like 5.6.
1081 // So we need to truncate trailing zeros to make it work as expected.
1082 if ($display === '' && strpos($value, '.') !== FALSE) {
1083 // Use round() to truncate trailing zeros, e.g:
1084 // 10.00 -> 10, 10.60 -> 10.6, 10.69 -> 10.69.
1085 $value = (string) round($value, 5);
1086 $display = $field['options'][$value] ??
'';
1092 $customFormat = NULL;
1094 // FIXME: Are there any legitimate reasons why $value would be an array?
1095 // Or should we throw an exception here if it is?
1096 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1098 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1099 $format = $field['date_format'] ??
NULL;
1102 if (array_key_exists($format, $actualPHPFormats)) {
1103 $customTimeFormat = (array) $actualPHPFormats[$format];
1104 switch (CRM_Utils_Array
::value('time_format', $field)) {
1106 $customTimeFormat[] = 'g:iA';
1110 $customTimeFormat[] = 'G:i';
1114 //If time is not selected remove time from value.
1115 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1117 $customFormat = implode(" ", $customTimeFormat);
1120 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1124 // In the context of displaying a profile, show file/image
1127 if (CRM_Utils_Rule
::positiveInteger($value)) {
1131 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1133 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1135 $display = $url['file_url'];
1139 // In other contexts show a paperclip icon
1140 if (CRM_Utils_Rule
::integer($value)) {
1141 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1143 $file_description = '';
1145 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1147 catch (CiviCRM_API3_Exception
$dontcare) {
1151 $display = "{$icons[$value]}{$file_description}";
1154 //CRM-18396, if filename is passed instead
1162 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1166 $display = nl2br($display);
1170 if ($field['data_type'] == 'Money' && isset($value)) {
1171 // $value can also be an array(while using IN operator from search builder or api).
1172 foreach ((array) $value as $val) {
1173 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1175 $display = implode(', ', $disp);
1183 * Set default values for custom data used in profile.
1185 * @param int $customFieldId
1187 * @param string $elementName
1188 * Custom field name.
1189 * @param array $defaults
1190 * Associated array of fields.
1191 * @param int $contactId
1195 * @param mixed $value
1196 * If passed - dont fetch value from db,.
1197 * just format the given value
1199 public static function setProfileDefaults(
1207 //get the type of custom field
1208 $customField = new CRM_Core_BAO_CustomField();
1209 $customField->id
= $customFieldId;
1210 $customField->find(TRUE);
1213 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1214 $value = $customField->default_value
;
1218 if (!isset($value)) {
1219 $info = self
::getTableColumnGroup($customFieldId);
1220 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1221 $result = CRM_Core_DAO
::executeQuery($query);
1222 if ($result->fetch()) {
1223 $value = $result->value
;
1227 if ($customField->data_type
== 'Country') {
1229 $config = CRM_Core_Config
::singleton();
1230 if ($config->defaultContactCountry
) {
1231 $value = CRM_Core_BAO_Country
::defaultContactCountry();
1237 //set defaults if mode is registration
1238 if (!trim($value) &&
1240 (!in_array($mode, [CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
]))
1242 $value = $customField->default_value
;
1245 if ($customField->data_type
== 'Money' && isset($value)) {
1246 $value = number_format($value, 2);
1248 if (self
::isSerialized($customField) && $value) {
1249 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1250 $defaults[$elementName] = [];
1251 $checkedValue = CRM_Utils_Array
::explodePadded($value);
1252 foreach ($customOption as $val) {
1253 if (in_array($val['value'], $checkedValue)) {
1254 if ($customField->html_type
== 'CheckBox') {
1255 $defaults[$elementName][$val['value']] = 1;
1258 $defaults[$elementName][$val['value']] = $val['value'];
1264 $defaults[$elementName] = $value;
1271 * @param int $contactID
1273 * @param int $fileID
1274 * @param bool $absolute
1276 * @param string $multiRecordWhereClause
1280 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1283 $params = ['id' => $cfID];
1285 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1286 $columnName = $defaults['column_name'];
1288 //table name of custom data
1289 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1290 $defaults['custom_group_id'],
1294 //query to fetch id from civicrm_file
1295 if ($multiRecordWhereClause) {
1296 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1299 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1301 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1306 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1311 $result['file_id'] = $fileID;
1313 if ($fileType == 'image/jpeg' ||
1314 $fileType == 'image/pjpeg' ||
1315 $fileType == 'image/gif' ||
1316 $fileType == 'image/x-png' ||
1317 $fileType == 'image/png'
1319 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1324 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1325 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1326 $url = CRM_Utils_System
::url('civicrm/file',
1327 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1328 $absolute, NULL, TRUE, TRUE
1330 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1332 // for non image files
1334 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1338 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1339 $url = CRM_Utils_System
::url('civicrm/file',
1340 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1341 $absolute, NULL, TRUE, TRUE
1343 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1351 * Format custom fields before inserting.
1353 * @param int $customFieldId
1355 * @param array $customFormatted
1357 * @param mixed $value
1358 * Value of custom field.
1359 * @param string $customFieldExtend
1360 * Custom field extends.
1361 * @param int $customValueId
1362 * Custom option value id.
1363 * @param int $entityId
1364 * Entity id (contribution, membership...).
1365 * @param bool $inline
1366 * Consider inline custom groups only.
1367 * @param bool $checkPermission
1368 * If false, do not include permissioning clause.
1369 * @param bool $includeViewOnly
1370 * If true, fields marked 'View Only' are included. Required for APIv3.
1372 * @return array|NULL
1373 * formatted custom field array
1375 public static function formatCustomField(
1376 $customFieldId, &$customFormatted, $value,
1377 $customFieldExtend, $customValueId = NULL,
1380 $checkPermission = TRUE,
1381 $includeViewOnly = FALSE
1383 //get the custom fields for the entity
1384 //subtype and basic type
1385 $customDataSubType = NULL;
1386 if ($customFieldExtend) {
1387 // This is the case when getFieldsForImport() requires fields
1388 // of subtype and its parent.CRM-5143
1389 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1390 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1391 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1392 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1393 if (is_array($customFieldExtend)) {
1394 $customFieldExtend = array_unique(array_values($customFieldExtend));
1399 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1409 if (!array_key_exists($customFieldId, $customFields)) {
1413 // return if field is a 'code' field
1414 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1418 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1420 if (!$customValueId &&
1421 // we always create new entites for is_multiple unless specified
1422 !$customFields[$customFieldId]['is_multiple'] &&
1428 WHERE entity_id={$entityId}";
1430 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1433 //fix checkbox, now check box always submits values
1434 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1436 // Note that only during merge this is not an array, and you can directly use value
1437 if (is_array($value)) {
1438 $selectedValues = [];
1439 foreach ($value as $selId => $val) {
1441 $selectedValues[] = $selId;
1444 if (!empty($selectedValues)) {
1445 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1447 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1455 elseif (self
::isSerialized($customFields[$customFieldId])) {
1456 $value = $value ? CRM_Utils_Array
::implodePadded($value) : '';
1459 if (self
::isSerialized($customFields[$customFieldId]) &&
1460 $customFields[$customFieldId]['data_type'] == 'String' &&
1461 !empty($customFields[$customFieldId]['text_length']) &&
1464 // lets make sure that value is less than the length, else we'll
1465 // be losing some data, CRM-7481
1466 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1467 // need to do a few things here
1469 // 1. lets find a new length
1470 $newLength = $customFields[$customFieldId]['text_length'];
1471 $minLength = strlen($value);
1472 while ($newLength < $minLength) {
1473 $newLength = $newLength * 2;
1476 // set the custom field meta data to have a length larger than value
1477 // alter the custom value table column to match this length
1478 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1483 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1484 if (!CRM_Utils_System
::isNull($value)) {
1485 $format = $customFields[$customFieldId]['date_format'];
1486 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1491 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1492 $customFields[$customFieldId]['data_type'] == 'Money'
1498 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1499 $value = CRM_Utils_Rule
::cleanMoney($value);
1503 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1504 $customFields[$customFieldId]['data_type'] == 'Country'
1514 if ($customFields[$customFieldId]['data_type'] == 'File') {
1515 if (empty($value)) {
1519 $config = CRM_Core_Config
::singleton();
1521 // If we are already passing the file id as a value then retrieve and set the file data
1522 if (CRM_Utils_Rule
::integer($value)) {
1523 $fileDAO = new CRM_Core_DAO_File();
1524 $fileDAO->id
= $value;
1525 $fileDAO->find(TRUE);
1528 $fName = $fileDAO->uri
;
1529 $mimeType = $fileDAO->mime_type
;
1533 $fName = $value['name'];
1534 $mimeType = $value['type'];
1537 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1539 // rename this file to go into the secure directory only if
1540 // user has uploaded new file not existing verfied on the basis of $fileID
1541 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1542 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1545 if ($customValueId && empty($fileID)) {
1550 $params = [1 => [$customValueId, 'Integer']];
1551 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1554 $fileDAO = new CRM_Core_DAO_File();
1557 $fileDAO->id
= $fileID;
1560 $fileDAO->uri
= $filename;
1561 $fileDAO->mime_type
= $mimeType;
1562 $fileDAO->upload_date
= date('YmdHis');
1564 $fileID = $fileDAO->id
;
1568 if (!is_array($customFormatted)) {
1569 $customFormatted = [];
1572 if (!array_key_exists($customFieldId, $customFormatted)) {
1573 $customFormatted[$customFieldId] = [];
1577 if ($customValueId) {
1578 $index = $customValueId;
1581 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1582 $customFormatted[$customFieldId][$index] = [];
1584 $customFormatted[$customFieldId][$index] = [
1585 'id' => $customValueId > 0 ?
$customValueId : NULL,
1587 'type' => $customFields[$customFieldId]['data_type'],
1588 'custom_field_id' => $customFieldId,
1589 'custom_group_id' => $groupID,
1590 'table_name' => $tableName,
1591 'column_name' => $columnName,
1592 'file_id' => $fileID,
1593 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1596 //we need to sort so that custom fields are created in the order of entry
1597 krsort($customFormatted[$customFieldId]);
1598 return $customFormatted;
1602 * Get default custom table schema.
1604 * @param array $params
1608 public static function defaultCustomTableSchema($params) {
1609 // add the id and extends_id
1610 $collation = CRM_Core_BAO_SchemaHandler
::getInUseCollation();
1611 $characterSet = 'utf8';
1612 if (stripos($collation, 'utf8mb4') !== FALSE) {
1613 $characterSet = 'utf8mb4';
1616 'name' => $params['name'],
1617 'is_multiple' => $params['is_multiple'],
1618 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET {$characterSet} COLLATE {$collation}",
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 * Reformat existing values for a field when changing its serialize attribute
1704 * @param CRM_Core_DAO_CustomField $field
1705 * @throws CRM_Core_Exception
1707 private static function alterSerialize($field) {
1708 $table = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1709 $col = $field->column_name
;
1710 $sp = CRM_Core_DAO
::VALUE_SEPARATOR
;
1711 if ($field->serialize
) {
1712 $sql = "UPDATE `$table` SET `$col` = CONCAT('$sp', `$col`, '$sp') WHERE `$col` IS NOT NULL AND `$col` NOT LIKE '$sp%' AND `$col` != ''";
1715 $sql = "UPDATE `$table` SET `$col` = SUBSTRING_INDEX(SUBSTRING(`$col`, 2), '$sp', 1) WHERE `$col` LIKE '$sp%'";
1717 CRM_Core_DAO
::executeQuery($sql);
1721 * Determine whether it would be safe to move a field.
1723 * @param int $fieldID
1724 * FK to civicrm_custom_field.
1725 * @param int $newGroupID
1726 * FK to civicrm_custom_group.
1729 * array(string) or TRUE
1731 public static function _moveFieldValidate($fieldID, $newGroupID) {
1734 $field = new CRM_Core_DAO_CustomField();
1735 $field->id
= $fieldID;
1736 if (!$field->find(TRUE)) {
1737 $errors['fieldID'] = 'Invalid ID for custom field';
1741 $oldGroup = new CRM_Core_DAO_CustomGroup();
1742 $oldGroup->id
= $field->custom_group_id
;
1743 if (!$oldGroup->find(TRUE)) {
1744 $errors['fieldID'] = 'Invalid ID for old custom group';
1748 $newGroup = new CRM_Core_DAO_CustomGroup();
1749 $newGroup->id
= $newGroupID;
1750 if (!$newGroup->find(TRUE)) {
1751 $errors['newGroupID'] = 'Invalid ID for new custom group';
1757 FROM civicrm_custom_field a
1758 INNER JOIN civicrm_custom_field b
1760 AND a.label = b.label
1761 AND b.custom_group_id = %2
1764 1 => [$field->id
, 'Integer'],
1765 2 => [$newGroup->id
, 'Integer'],
1767 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1769 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1772 $tableName = $oldGroup->table_name
;
1773 $columnName = $field->column_name
;
1778 WHERE $columnName is not null
1780 $count = CRM_Core_DAO
::singleValueQuery($query);
1784 FROM civicrm_custom_group
1785 WHERE id IN ( %1, %2 )
1788 1 => [$oldGroup->id
, 'Integer'],
1789 2 => [$newGroup->id
, 'Integer'],
1792 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1794 while ($dao->fetch()) {
1795 $extends[] = $dao->extends;
1797 if ($extends[0] != $extends[1]) {
1798 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1802 return empty($errors) ?
TRUE : $errors;
1806 * Move a custom data field from one group (table) to another.
1808 * @param int $fieldID
1809 * FK to civicrm_custom_field.
1810 * @param int $newGroupID
1811 * FK to civicrm_custom_group.
1813 * @throws CRM_Core_Exception
1815 public static function moveField($fieldID, $newGroupID) {
1816 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1817 if (TRUE !== $validation) {
1818 throw new CRM_Core_Exception(implode(' ', $validation));
1820 $field = new CRM_Core_DAO_CustomField();
1821 $field->id
= $fieldID;
1824 $newGroup = new CRM_Core_DAO_CustomGroup();
1825 $newGroup->id
= $newGroupID;
1826 $newGroup->find(TRUE);
1828 $oldGroup = new CRM_Core_DAO_CustomGroup();
1829 $oldGroup->id
= $field->custom_group_id
;
1830 $oldGroup->find(TRUE);
1833 $add->custom_group_id
= $newGroup->id
;
1834 self
::createField($add, 'add');
1836 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, `{$field->column_name}`)
1837 SELECT entity_id, `{$field->column_name}` FROM {$oldGroup->table_name}
1838 ON DUPLICATE KEY UPDATE `{$field->column_name}` = {$oldGroup->table_name}.`{$field->column_name}`
1840 CRM_Core_DAO
::executeQuery($sql);
1843 $del->custom_group_id
= $oldGroup->id
;
1844 self
::createField($del, 'delete');
1848 CRM_Utils_System
::flushCache();
1852 * Create an option value for a custom field option group ID.
1854 * @param array $params
1855 * @param string $value
1856 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1857 * @param string $index
1858 * @param string $dataType
1860 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $index, $dataType) {
1861 if (strlen(trim($value))) {
1862 $optionValue = new CRM_Core_DAO_OptionValue();
1863 $optionValue->option_group_id
= $optionGroup->id
;
1864 $optionValue->label
= $params['option_label'][$index];
1865 $optionValue->name
= $params['option_name'][$index] ?? CRM_Utils_String
::titleToVar($params['option_label'][$index]);
1866 switch ($dataType) {
1868 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1872 $optionValue->value
= intval($value);
1876 $optionValue->value
= floatval($value);
1880 $optionValue->value
= trim($value);
1883 $optionValue->weight
= $params['option_weight'][$index];
1884 $optionValue->is_active
= $params['option_status'][$index] ??
FALSE;
1885 $optionValue->description
= $params['option_description'][$index] ??
NULL;
1886 $optionValue->color
= $params['option_color'][$index] ??
NULL;
1887 $optionValue->icon
= $params['option_icon'][$index] ??
NULL;
1888 $optionValue->save();
1893 * Prepare for the create operation.
1895 * Munge params, create the option values if needed.
1897 * This could be called by a single create or a batchCreate.
1899 * @param array $params
1903 protected static function prepareCreate($params) {
1904 $op = empty($params['id']) ?
'create' : 'edit';
1905 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1906 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1907 if ($op === 'create') {
1908 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1909 if (!isset($params['column_name'])) {
1910 // if add mode & column_name not present, calculate it.
1911 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1913 if (!isset($params['name'])) {
1914 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1918 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'column_name');
1921 $htmlType = $params['html_type'] ??
NULL;
1922 $dataType = $params['data_type'] ??
NULL;
1924 if ($htmlType === 'Select Date' && empty($params['date_format'])) {
1925 $params['date_format'] = Civi
::settings()->get('dateInputFormat');
1928 // Checkboxes are always serialized in current schema
1929 if ($htmlType == 'CheckBox') {
1930 $params['serialize'] = CRM_Core_DAO
::SERIALIZE_SEPARATOR_BOOKEND
;
1933 if (!empty($params['serialize'])) {
1934 if (isset($params['default_checkbox_option'])) {
1936 foreach (array_keys($params['default_checkbox_option']) as $k => $v) {
1937 if ($params['option_value'][$v]) {
1938 $defaultArray[] = $params['option_value'][$v];
1942 if (!empty($defaultArray)) {
1943 // also add the separator before and after the value per new convention (CRM-1604)
1944 $params['default_value'] = CRM_Utils_Array
::implodePadded($defaultArray);
1948 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])) {
1949 $params['default_value'] = $params['option_value'][$params['default_option']];
1954 // create any option group & values if required
1955 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1956 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)) {
1957 //CRM-16659: if option_value then create an option group for this custom field.
1958 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
1959 // first create an option group for this custom group
1960 $optionGroup = new CRM_Core_DAO_OptionGroup();
1961 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
1962 $optionGroup->title
= $params['label'];
1963 $optionGroup->is_active
= 1;
1964 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1965 $optionGroup->is_reserved
= 0;
1966 $optionGroup->data_type
= $dataType;
1967 $optionGroup->save();
1968 $params['option_group_id'] = $optionGroup->id
;
1969 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1970 foreach ($params['option_value'] as $k => $v) {
1971 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1977 // check for orphan option groups
1978 if (!empty($params['option_group_id'])) {
1979 if (!empty($params['id'])) {
1980 self
::fixOptionGroups($params['id'], $params['option_group_id']);
1983 // if we do not have a default value
1984 // retrieve it from one of the other custom fields which use this option group
1985 if (empty($params['default_value'])) {
1986 //don't insert only value separator as default value, CRM-4579
1987 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'], !empty($params['serialize']));
1989 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultValue))) {
1990 $params['default_value'] = $defaultValue;
1995 // Set default textarea attributes
1996 if ($op == 'create' && !isset($params['attributes']) && $htmlType == 'TextArea') {
1997 $params['attributes'] = 'rows=4, cols=60';
2003 * Create database entry for custom field and related option groups.
2005 * @param array $params
2007 * @return CRM_Core_DAO_CustomField
2009 protected static function createCustomFieldRecord($params) {
2010 $transaction = new CRM_Core_Transaction();
2011 $params = self
::prepareCreate($params);
2013 $alterSerialize = isset($params['serialize']) && !empty($params['id'])
2014 && ($params['serialize'] != CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'serialize'));
2016 $customField = new CRM_Core_DAO_CustomField();
2017 $customField->copyValues($params);
2018 $customField->save();
2020 //create/drop the index when we toggle the is_searchable flag
2021 $op = empty($params['id']) ?
'add' : 'modify';
2022 if ($op !== 'modify') {
2023 if ($params['is_append_field_id_to_column_name']) {
2024 $params['column_name'] .= "_{$customField->id}";
2026 $customField->column_name
= $params['column_name'];
2027 $customField->save();
2030 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
2031 $transaction->commit();
2033 // make sure all values are present in the object for further processing
2034 $customField->find(TRUE);
2036 if ($alterSerialize) {
2037 self
::alterSerialize($customField);
2040 return $customField;
2044 * Move custom data from one contact to another.
2046 * This is currently the start of a refactoring. The theory is each
2047 * entity could have a 'move' function with a DAO default one to fall back on.
2049 * At the moment this only does a small part of the process - ie deleting a file field that
2050 * is about to be overwritten. However, the goal is the whole process around the move for
2051 * custom data should be in here.
2053 * This is currently called by the merge class but it makes sense that api could
2054 * expose move actions as moving (e.g) contributions feels like a common
2055 * ask that should be handled by the form layer.
2057 * @param int $oldContactID
2058 * @param int $newContactID
2059 * @param int[] $fieldIDs
2060 * Optional list field ids to move.
2062 * @throws \CiviCRM_API3_Exception
2063 * @throws \Exception
2065 public function move($oldContactID, $newContactID, $fieldIDs) {
2066 if (empty($fieldIDs)) {
2069 $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'];
2071 foreach ($fieldIDs as $fieldID) {
2072 $return[] = 'custom_' . $fieldID;
2074 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2075 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2077 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2078 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2079 $fieldTypesNotHandledInMergeAttempt = ['File'];
2080 foreach ($fields as $field) {
2081 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2082 if ($field['data_type'] === 'File' && !$isMultiple) {
2083 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2084 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2086 if (!empty($oldContact['custom_' . $field['id']])) {
2087 CRM_Core_DAO
::executeQuery("
2088 UPDATE civicrm_entity_file
2089 SET entity_id = $newContactID
2090 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2094 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2095 CRM_Core_DAO
::executeQuery(
2096 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, `{$field['column_name']}`)
2097 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2098 ON DUPLICATE KEY UPDATE
2099 `{$field['column_name']}` = {$oldContact['custom_' . $field['id']]}
2106 * Get the database table name and column name for a custom field.
2108 * @param int $fieldID
2109 * The fieldID of the custom field.
2110 * @param bool $force
2111 * Force the sql to be run again (primarily used for tests).
2114 * fatal is fieldID does not exists, else array of tableName, columnName
2115 * @throws \CRM_Core_Exception
2117 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2118 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2119 $cache = CRM_Utils_Cache
::singleton();
2120 $fieldValues = $cache->get($cacheKey);
2121 if (empty($fieldValues) ||
$force) {
2123 SELECT cg.table_name, cf.column_name, cg.id
2124 FROM civicrm_custom_group cg,
2125 civicrm_custom_field cf
2126 WHERE cf.custom_group_id = cg.id
2128 $params = [1 => [$fieldID, 'Integer']];
2129 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2131 if (!$dao->fetch()) {
2132 throw new CRM_Core_Exception("Cannot find table and column information for Custom Field " . $fieldID);
2134 $fieldValues = [$dao->table_name
, $dao->column_name
, $dao->id
];
2135 $cache->set($cacheKey, $fieldValues);
2137 return $fieldValues;
2141 * Get custom option groups.
2143 * @deprecated Use the API OptionGroup.get
2145 * @param array $includeFieldIds
2146 * Ids of custom fields for which option groups must be included.
2148 * Currently this is required in the cases where option groups are to be included
2149 * for inactive fields : CRM-5369
2153 public static function customOptionGroup($includeFieldIds = NULL) {
2154 static $customOptionGroup = NULL;
2156 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2157 if ($cacheKey == 'force') {
2158 $customOptionGroup[$cacheKey] = NULL;
2161 if (empty($customOptionGroup[$cacheKey])) {
2162 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2164 //support for single as well as array format.
2165 if (!empty($includeFieldIds)) {
2166 if (is_array($includeFieldIds)) {
2167 $includeFieldIds = implode(',', $includeFieldIds);
2169 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2173 SELECT g.id, g.title
2174 FROM civicrm_option_group g
2175 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2176 WHERE {$whereClause}";
2178 $dao = CRM_Core_DAO
::executeQuery($query);
2179 while ($dao->fetch()) {
2180 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2184 return $customOptionGroup[$cacheKey];
2188 * Get defaults for new entity.
2192 public static function getDefaults() {
2194 'is_required' => FALSE,
2195 'is_searchable' => FALSE,
2196 'in_selector' => FALSE,
2197 'is_search_range' => FALSE,
2198 //CRM-15792 - Custom field gets disabled if is_active not set
2199 // this would ideally be a mysql default.
2200 'is_active' => TRUE,
2206 * Fix orphan groups.
2208 * @param int $customFieldId
2210 * @param int $optionGroupId
2213 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2214 // check if option group belongs to any custom Field else delete
2215 // get the current option group
2216 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2220 // get the updated option group
2221 // if both are same return
2222 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2226 // check if option group is related to any other field
2227 self
::checkOptionGroup($currentOptionGroupId);
2231 * Check if option group is related to more than one custom field.
2233 * @param int $optionGroupId
2236 public static function checkOptionGroup($optionGroupId) {
2239 FROM civicrm_custom_field
2240 WHERE option_group_id = {$optionGroupId}";
2242 $count = CRM_Core_DAO
::singleValueQuery($query);
2245 //delete the option group
2246 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2251 * Get option group default.
2253 * @param int $optionGroupId
2254 * @param bool $serialize
2256 * @return null|string
2258 public static function getOptionGroupDefault($optionGroupId, $serialize) {
2260 SELECT default_value, serialize
2261 FROM civicrm_custom_field
2262 WHERE option_group_id = {$optionGroupId}
2263 AND default_value IS NOT NULL";
2265 $dao = CRM_Core_DAO
::executeQuery($query);
2266 while ($dao->fetch()) {
2267 if ($dao->serialize
== $serialize) {
2268 return $dao->default_value
;
2270 $defaultValue = $dao->default_value
;
2273 // Convert serialization
2274 if (isset($defaultValue) && $serialize) {
2275 return CRM_Utils_Array
::implodePadded([$defaultValue]);
2277 elseif (isset($defaultValue)) {
2278 return CRM_Utils_Array
::explodePadded($defaultValue)[0];
2284 * Post process function.
2286 * @param array $params
2287 * @param int $entityID
2288 * @param string $customFieldExtends
2289 * @param bool $inline
2290 * @param bool $checkPermissions
2294 public static function postProcess(
2297 $customFieldExtends,
2299 $checkPermissions = TRUE
2303 foreach ($params as $key => $value) {
2304 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2306 // for autocomplete transfer hidden value instead of label
2307 if ($params[$key] && isset($params[$key . '_id'])) {
2308 $value = $params[$key . '_id'];
2311 // we need to append time with date
2312 if ($params[$key] && isset($params[$key . '_time'])) {
2313 $value .= ' ' . $params[$key . '_time'];
2316 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2319 $customFieldExtends,
2320 $customFieldInfo[1],
2331 * Get custom field ID from field/group name/title.
2333 * @param string $fieldName Field name or label
2334 * @param string|null $groupName (Optional) Group name or label
2335 * @param bool $fullString Whether to return "custom_123" or "123"
2337 * @return string|int|null
2338 * @throws \CiviCRM_API3_Exception
2340 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2341 $cacheKey = $groupName . '.' . $fieldName;
2342 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2343 $customFieldParams = [
2344 'name' => $fieldName,
2345 'label' => $fieldName,
2346 'options' => ['or' => [["name", "label"]]],
2350 $customFieldParams['custom_group_id.name'] = $groupName;
2351 $customFieldParams['custom_group_id.title'] = $groupName;
2352 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2355 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2357 if (empty($field['id'])) {
2358 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2359 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2362 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2363 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2368 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2370 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2374 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2380 public static function getNameFromID($ids) {
2381 if (is_array($ids)) {
2382 $ids = implode(',', $ids);
2385 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2386 FROM civicrm_custom_field f
2387 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2388 WHERE f.id IN ($ids)";
2390 $dao = CRM_Core_DAO
::executeQuery($sql);
2392 while ($dao->fetch()) {
2393 $result[$dao->id
] = [
2394 'field_name' => $dao->field_name
,
2395 'field_label' => $dao->field_label
,
2396 'group_name' => $dao->group_name
,
2397 'group_title' => $dao->group_title
,
2404 * Validate custom data.
2406 * @param array $params
2407 * Custom data submitted.
2408 * ie array( 'custom_1' => 'validate me' );
2411 * validation errors.
2413 public static function validateCustomData($params) {
2415 if (!is_array($params) ||
empty($params)) {
2419 //pick up profile fields.
2420 $profileFields = [];
2421 $ufGroupId = $params['ufGroupId'] ??
NULL;
2423 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2425 CRM_Core_Action
::VIEW
2429 //lets start w/ params.
2430 foreach ($params as $key => $value) {
2431 $customFieldID = self
::getKeyID($key);
2432 if (!$customFieldID) {
2436 //load the structural info for given field.
2437 $field = new CRM_Core_DAO_CustomField();
2438 $field->id
= $customFieldID;
2439 if (!$field->find(TRUE)) {
2442 $dataType = $field->data_type
;
2444 $profileField = CRM_Utils_Array
::value($key, $profileFields, []);
2445 $fieldTitle = $profileField['title'] ??
NULL;
2446 $isRequired = $profileField['is_required'] ??
NULL;
2448 $fieldTitle = $field->label
;
2451 //no need to validate.
2452 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2456 //lets validate first for required field.
2457 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2458 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
2462 //now time to take care of custom field form rules.
2463 $ruleName = $errorMsg = NULL;
2464 switch ($dataType) {
2466 $ruleName = 'integer';
2467 $errorMsg = ts('%1 must be an integer (whole number).',
2468 array(1 => $fieldTitle)
2473 $ruleName = 'money';
2474 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2475 array(1 => $fieldTitle)
2480 $ruleName = 'numeric';
2481 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2482 array(1 => $fieldTitle)
2487 $ruleName = 'wikiURL';
2488 $errorMsg = ts('%1 must be valid Website.',
2489 array(1 => $fieldTitle)
2494 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2496 $funName = "CRM_Utils_Rule::{$ruleName}";
2497 if (is_callable($funName)) {
2498 $valid = call_user_func($funName, $value);
2501 $errors[$key] = $errorMsg;
2510 * Is this field a multi record field.
2512 * @param int $customId
2516 public static function isMultiRecordField($customId) {
2517 $isMultipleWithGid = FALSE;
2518 if (!is_numeric($customId)) {
2519 $customId = self
::getKeyID($customId);
2521 if (is_numeric($customId)) {
2522 $sql = "SELECT cg.id cgId
2523 FROM civicrm_custom_group cg
2524 INNER JOIN civicrm_custom_field cf
2525 ON cg.id = cf.custom_group_id
2526 WHERE cf.id = %1 AND cg.is_multiple = 1";
2527 $params[1] = [$customId, 'Integer'];
2528 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2529 if ($dao->fetch()) {
2531 $isMultipleWithGid = $dao->cgId
;
2536 return $isMultipleWithGid;
2540 * Does this field type have any select options?
2542 * @param array $field
2546 public static function hasOptions($field) {
2547 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2548 $field = (array) $field;
2549 // This will include boolean fields with Yes/No options.
2550 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2553 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2554 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2555 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2558 if (strpos($field['html_type'], 'Select') !== FALSE) {
2561 return !empty($field['option_group_id']);
2565 * Does this field store a serialized string?
2567 * @param CRM_Core_DAO_CustomField|array $field
2571 public static function isSerialized($field) {
2572 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2573 $html_type = is_object($field) ?
$field->html_type
: $field['html_type'];
2574 // APIv3 has a "legacy" mode where it returns old-style html_type of "Multi-Select"
2575 // If anyone is using this function in conjunction with legacy api output, we'll accomodate:
2576 if ($html_type === 'CheckBox' ||
strpos($html_type, 'Multi') !== FALSE) {
2579 // Otherwise this is the new standard as of 5.27
2580 return is_object($field) ?
!empty($field->serialize
) : !empty($field['serialize']);
2584 * Get api entity for this field
2588 public function getEntity() {
2589 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2590 return in_array($entity, ['Individual', 'Household', 'Organization']) ?
'Contact' : $entity;
2594 * Set pseudoconstant properties for field metadata.
2596 * @param array $field
2597 * @param string|null $optionGroupName
2599 private static function getOptionsForField(&$field, $optionGroupName) {
2600 if ($optionGroupName) {
2601 $field['pseudoconstant'] = [
2602 'optionGroupName' => $optionGroupName,
2603 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2606 elseif ($field['data_type'] == 'Boolean') {
2607 $field['pseudoconstant'] = [
2608 'callback' => 'CRM_Core_SelectValues::boolean',
2611 elseif ($field['data_type'] == 'Country') {
2612 $field['pseudoconstant'] = [
2613 'table' => 'civicrm_country',
2614 'keyColumn' => 'id',
2615 'labelColumn' => 'name',
2616 'nameColumn' => 'iso_code',
2619 elseif ($field['data_type'] == 'StateProvince') {
2620 $field['pseudoconstant'] = [
2621 'table' => 'civicrm_state_province',
2622 'keyColumn' => 'id',
2623 'labelColumn' => 'name',
2629 * @param CRM_Core_DAO_CustomField $field
2630 * @param 'add|modify' $operation
2634 protected static function prepareCreateParams($field, $operation) {
2635 $tableName = CRM_Core_DAO
::getFieldValue(
2636 'CRM_Core_DAO_CustomGroup',
2637 $field->custom_group_id
,
2642 'table_name' => $tableName,
2643 'operation' => $operation,
2644 'name' => $field->column_name
,
2645 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2649 'required' => $field->is_required
,
2650 'searchable' => $field->is_searchable
,
2653 if ($operation == 'delete') {
2654 $fkName = "{$tableName}_{$field->column_name}";
2655 if (strlen($fkName) >= 48) {
2656 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2658 $params['fkName'] = $fkName;
2660 if ($field->data_type
== 'Country' && !self
::isSerialized($field)) {
2661 $params['fk_table_name'] = 'civicrm_country';
2662 $params['fk_field_name'] = 'id';
2663 $params['fk_attributes'] = 'ON DELETE SET NULL';
2665 elseif ($field->data_type
== 'StateProvince' && !self
::isSerialized($field)) {
2666 $params['fk_table_name'] = 'civicrm_state_province';
2667 $params['fk_field_name'] = 'id';
2668 $params['fk_attributes'] = 'ON DELETE SET NULL';
2670 elseif ($field->data_type
== 'StateProvince' ||
$field->data_type
== 'Country') {
2671 $params['type'] = 'varchar(255)';
2673 elseif ($field->data_type
== 'File') {
2674 $params['fk_table_name'] = 'civicrm_file';
2675 $params['fk_field_name'] = 'id';
2676 $params['fk_attributes'] = 'ON DELETE SET NULL';
2678 elseif ($field->data_type
== 'ContactReference') {
2679 $params['fk_table_name'] = 'civicrm_contact';
2680 $params['fk_field_name'] = 'id';
2681 $params['fk_attributes'] = 'ON DELETE SET NULL';
2683 if (isset($field->default_value
)) {
2684 $params['default'] = "'{$field->default_value}'";