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.
282 public static function &getFields(
283 $customDataType = 'Individual',
286 $customDataSubType = NULL,
287 $customDataSubName = NULL,
289 $onlySubType = FALSE,
290 $checkPermission = TRUE
292 if (empty($customDataType)) {
293 $customDataType = ['Contact', 'Individual', 'Organization', 'Household'];
295 if ($customDataType === 'ANY') {
296 // NULL should have been respected but the line above broke that.
297 // boo for us not having enough unit tests back them.
298 $customDataType = NULL;
300 if ($customDataType && !is_array($customDataType)) {
302 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
303 // This is the case when getFieldsForImport() requires fields
304 // limited strictly to a subtype.
305 $customDataSubType = $customDataType;
306 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
310 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
311 // this makes the method flexible to support retrieving fields
312 // for multiple extends value.
313 $customDataType = [$customDataType];
317 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
319 if (is_array($customDataType)) {
320 $cacheKey = implode('_', $customDataType);
323 $cacheKey = $customDataType;
326 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
327 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
328 $cacheKey .= $showAll ?
'_1' : '_0';
329 $cacheKey .= $inline ?
'_1_' : '_0_';
330 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
331 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
332 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
333 $cacheKey .= '_' . CRM_Core_Config
::domainID() . '_';
335 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
337 // also get the permission stuff here
338 if ($checkPermission) {
339 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
344 $permissionClause = '(1)';
347 // lets md5 permission clause and take first 8 characters
348 $cacheKey .= substr(md5($permissionClause), 0, 8);
350 if (strlen($cacheKey) > 40) {
351 $cacheKey = md5($cacheKey);
354 if (!self
::$_importFields ||
355 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
357 if (!self
::$_importFields) {
358 self
::$_importFields = [];
361 // check if we can retrieve from database cache
362 $fields = Civi
::Cache('fields')->get("custom importableFields $cacheKey");
364 if ($fields === NULL) {
365 $cfTable = self
::getTableName();
368 if (is_array($customDataType)) {
370 foreach ($customDataType as $dataType) {
371 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
372 if (in_array($dataType, ['Individual', 'Household', 'Organization'])) {
373 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
376 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
378 $value = $value ?
$value . ", {$val}" : $val;
382 $extends = "AND $cgTable.extends IN ( $value ) ";
386 if (!empty($customDataType) && empty($extends)) {
387 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
388 self
::$_importFields[$cacheKey] = [];
389 return self
::$_importFields[$cacheKey];
393 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
396 $query = "SELECT $cfTable.id, $cfTable.label,
400 $cfTable.default_value,
401 $cfTable.options_per_line, $cfTable.text_length,
402 $cfTable.custom_group_id,
403 $cfTable.is_required,
404 $cfTable.column_name,
405 $cgTable.extends, $cfTable.is_search_range,
406 $cgTable.extends_entity_column_value,
407 $cgTable.extends_entity_column_id,
409 $cfTable.option_group_id,
410 $cfTable.date_format,
411 $cfTable.time_format,
412 $cgTable.is_multiple,
415 og.name as option_group_name
418 ON $cfTable.custom_group_id = $cgTable.id
419 LEFT JOIN civicrm_option_group og
420 ON $cfTable.option_group_id = og.id
424 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
428 $query .= " AND $cgTable.style = 'Inline' ";
431 //get the custom fields for specific type in
432 //combination with fields those support any type.
433 if (!empty($customDataSubType)) {
435 foreach ($customDataSubType as $subtype) {
436 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($subtype, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
;
437 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
440 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
442 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
445 if ($customDataSubName) {
446 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
449 // also get the permission stuff here
450 if ($checkPermission) {
451 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
456 $permissionClause = '(1)';
459 $query .= " $extends AND $permissionClause
460 ORDER BY $cgTable.weight, $cgTable.title,
461 $cfTable.weight, $cfTable.label";
463 $dao = CRM_Core_DAO
::executeQuery($query);
466 while (($dao->fetch()) != NULL) {
467 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
468 $fields[$dao->id
]['id'] = $dao->id
;
469 $fields[$dao->id
]['label'] = $dao->label
;
470 // This seems broken, but not in a new way.
471 $fields[$dao->id
]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
472 // To support the consolidation of various functions & their expectations.
473 $fields[$dao->id
]['title'] = $dao->label
;
474 $fields[$dao->id
]['custom_field_id'] = $dao->id
;
475 $fields[$dao->id
]['groupTitle'] = $dao->title
;
476 $fields[$dao->id
]['data_type'] = $dao->data_type
;
477 $fields[$dao->id
]['name'] = 'custom_' . $dao->id
;
478 $fields[$dao->id
]['type'] = CRM_Utils_Array
::value($dao->data_type
, self
::dataToType());
479 $fields[$dao->id
]['html_type'] = $dao->html_type
;
480 $fields[$dao->id
]['default_value'] = $dao->default_value
;
481 $fields[$dao->id
]['text_length'] = $dao->text_length
;
482 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
483 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
484 $fields[$dao->id
]['extends'] = $dao->extends;
485 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
486 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
487 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
488 $fields[$dao->id
]['is_view'] = $dao->is_view
;
489 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
490 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
491 $fields[$dao->id
]['date_format'] = $dao->date_format
;
492 $fields[$dao->id
]['time_format'] = $dao->time_format
;
493 $fields[$dao->id
]['is_required'] = $dao->is_required
;
494 $fields[$dao->id
]['table_name'] = $dao->table_name
;
495 $fields[$dao->id
]['column_name'] = $dao->column_name
;
496 $fields[$dao->id
]['serialize'] = $dao->serialize
;
497 $fields[$dao->id
]['where'] = $dao->table_name
. '.' . $dao->column_name
;
498 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
499 $fields[$dao->id
]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery
::$extendsMap) ? CRM_Core_BAO_CustomQuery
::$extendsMap[$dao->extends] : '';
500 if (in_array($dao->extends, CRM_Contact_BAO_ContactType
::subTypes())) {
501 // if $extends is a subtype, refer contact table
502 $fields[$dao->id
]['extends_table'] = 'civicrm_contact';
504 // Search table is used by query object searches..
505 $fields[$dao->id
]['search_table'] = ($fields[$dao->id
]['extends_table'] == 'civicrm_contact') ?
'contact_a' : $fields[$dao->id
]['extends_table'];
506 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
509 Civi
::cache('fields')->set("custom importableFields $cacheKey", $fields);
511 self
::$_importFields[$cacheKey] = $fields;
514 return self
::$_importFields[$cacheKey];
518 * Return the field ids and names (with groups) for import purpose.
520 * @param int|string $contactType Contact type
521 * @param bool $showAll
522 * If true returns all fields (includes disabled fields).
523 * @param bool $onlyParent
524 * Return fields ONLY related to basic types.
525 * @param bool $search
526 * When called from search and multiple records need to be returned.
527 * @param bool $checkPermission
528 * If false, do not include permissioning clause.
530 * @param bool $withMultiple
534 public static function getFieldsForImport(
535 $contactType = 'Individual',
539 $checkPermission = TRUE,
540 $withMultiple = FALSE
542 // Note: there are situations when we want getFieldsForImport() return fields related
543 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
544 $fields = &self
::getFields($contactType,
554 $importableFields = [];
555 foreach ($fields as $id => $values) {
556 // for now we should not allow multiple fields in profile / export etc, hence unsetting
558 (!empty($values['is_multiple']) && !$withMultiple)
562 if (!empty($values['text_length'])) {
563 $values['maxlength'] = (int) $values['text_length'];
566 /* generate the key for the fields array */
569 $importableFields[$key] = $values;
570 $importableFields[$key]['import'] = 1;
573 return $importableFields;
577 * Get the field id from an import key.
587 public static function getKeyID($key, $all = FALSE) {
589 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
596 CRM_Utils_Array
::value(2, $match),
600 return $all ?
[NULL, NULL] : NULL;
604 * Use the cache to get all values of a specific custom field.
606 * @param int $fieldID
607 * The custom field ID.
609 * @return CRM_Core_BAO_CustomField
611 * @throws CRM_Core_Exception
613 public static function getFieldObject($fieldID) {
614 $field = new CRM_Core_BAO_CustomField();
616 // check if we can get the field values from the system cache
617 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
618 $cache = CRM_Utils_Cache
::singleton();
619 $fieldValues = $cache->get($cacheKey);
620 if (empty($fieldValues)) {
621 $field->id
= $fieldID;
622 if (!$field->find(TRUE)) {
623 throw new CRM_Core_Exception('Cannot find Custom Field');
627 CRM_Core_DAO
::storeValues($field, $fieldValues);
629 $cache->set($cacheKey, $fieldValues);
632 $field->copyValues($fieldValues);
639 * Add a custom field to an existing form.
641 * @param CRM_Core_Form $qf
642 * Form object (reference).
643 * @param string $elementName
644 * Name of the custom field.
645 * @param int $fieldId
646 * @param bool $useRequired
647 * True if required else false.
648 * @param bool $search
649 * True if used for search else false.
650 * @param string $label
651 * Label for custom field.
652 * @return \HTML_QuickForm_Element|null
653 * @throws \CiviCRM_API3_Exception
655 public static function addQuickFormElement(
656 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
658 $field = self
::getFieldObject($fieldId);
659 $widget = $field->html_type
;
661 $customFieldAttributes = [];
663 // Custom field HTML should indicate group+field name
664 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
665 $dataCrmCustomVal = $groupName . ':' . $field->name
;
666 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
667 $field->attributes
.= $dataCrmCustomAttr;
669 // Fixed for Issue CRM-2183
670 if ($widget == 'TextArea' && $search) {
674 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
676 // FIXME: Why are select state/country separate widget types?
677 $isSelect = (in_array($widget, [
679 'Select State/Province',
686 $options = $field->getOptions($search ?
'search' : 'create');
688 // Consolidate widget types to simplify the below switch statement
689 if ($search ||
(strpos($widget, 'Select') !== FALSE)) {
693 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
694 $selectAttributes = ['class' => 'crm-select2'];
696 // Search field is always multi-select
697 if ($search ||
(self
::isSerialized($field) && $widget === 'Select')) {
698 $selectAttributes['class'] .= ' huge';
699 $selectAttributes['multiple'] = 'multiple';
700 $selectAttributes['placeholder'] = $placeholder;
703 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
704 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
705 if ($field->option_group_id
&& !$search && $isSelect && $canEditOptions) {
706 $customFieldAttributes +
= [
707 'data-api-entity' => $field->getEntity(),
708 'data-api-field' => 'custom_' . $field->id
,
709 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
711 $selectAttributes +
= $customFieldAttributes;
715 $rangeDataTypes = ['Int', 'Float', 'Money'];
717 if (!isset($label)) {
718 $label = $field->label
;
721 // at some point in time we might want to split the below into small functions
726 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
727 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
728 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
731 if ($field->text_length
) {
732 $field->attributes
.= ' maxlength=' . $field->text_length
;
733 if ($field->text_length
< 20) {
734 $field->attributes
.= ' size=' . $field->text_length
;
737 $element = $qf->add('text', $elementName, $label,
739 $useRequired && !$search
745 $attributes = $dataCrmCustomAttr;
746 if ($field->note_rows
) {
747 $attributes .= 'rows=' . $field->note_rows
;
750 $attributes .= 'rows=4';
752 if ($field->note_columns
) {
753 $attributes .= ' cols=' . $field->note_columns
;
756 $attributes .= ' cols=60';
758 if ($field->text_length
) {
759 $attributes .= ' maxlength=' . $field->text_length
;
761 $element = $qf->add('textarea',
765 $useRequired && !$search
770 $attr = ['data-crm-custom' => $dataCrmCustomVal];
771 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
772 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
773 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
776 'date' => $field->date_format
,
777 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
778 //CRM-18487 - max date should be the last date of the year.
779 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
780 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
782 if ($field->is_search_range
&& $search) {
783 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
784 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
787 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
792 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
793 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
794 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
798 parse_str($field->attributes
, $radioAttributes);
799 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
801 foreach ($options as $v => $l) {
802 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
804 $element = $qf->addGroup($choice, $elementName, $label);
805 $optionEditKey = 'data-option-edit-path';
806 if (isset($selectAttributes[$optionEditKey])) {
807 $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
810 if ($useRequired && !$search) {
811 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
814 $element->setAttribute('allowClear', TRUE);
819 // For all select elements
821 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
822 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
823 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
826 if (empty($selectAttributes['multiple'])) {
827 $options = ['' => $placeholder] +
$options;
829 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
831 // Add and/or option for fields that store multiple values
832 if ($search && self
::isSerialized($field)) {
835 $qf->createElement('radio', NULL, '', ts('Any'), 'or', ['title' => ts('Results may contain any of the selected options')]),
836 $qf->createElement('radio', NULL, '', ts('All'), 'and', ['title' => ts('Results must have all of the selected options')]),
838 $qf->addGroup($operators, $elementName . '_operator');
839 $qf->setDefaults([$elementName . '_operator' => 'or']);
846 foreach ($options as $v => $l) {
847 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
850 $group = $element = $qf->addGroup($check, $elementName, $label);
851 $optionEditKey = 'data-option-edit-path';
852 if (isset($customFieldAttributes[$optionEditKey])) {
853 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
856 if ($useRequired && !$search) {
857 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
862 // we should not build upload file in search mode
867 strtolower($field->html_type
),
871 $useRequired && !$search
873 $qf->addUploadElement($elementName);
876 case 'RichTextEditor':
878 'rows' => $field->note_rows
,
879 'cols' => $field->note_columns
,
880 'data-crm-custom' => $dataCrmCustomVal,
882 if ($field->text_length
) {
883 $attributes['maxlength'] = $field->text_length
;
885 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
888 case 'Autocomplete-Select':
889 static $customUrls = [];
890 // Fixme: why is this a string in the first place??
891 $attributes = array();
892 if ($field->attributes
) {
893 foreach (explode(' ', $field->attributes
) as $at) {
894 if (strpos($at, '=')) {
895 list($k, $v) = explode('=', $at);
896 $attributes[$k] = trim($v, ' "');
900 if ($field->data_type
== 'ContactReference') {
901 // break if contact does not have permission to access ContactReference
902 if (!CRM_Core_Permission
::check('access contact reference fields')) {
905 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
906 $attributes['data-api-entity'] = 'Contact';
907 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
909 $urlParams = "context=customfield&id={$field->id}";
910 $idOfelement = $elementName;
911 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
912 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
913 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
914 // rather than layering on more hacks.
915 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
916 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') +
1)), 0, -1);
918 $customUrls[$idOfelement] = CRM_Utils_System
::url('civicrm/ajax/contactref',
925 // FIXME: This won't work with customFieldOptions hook
927 'entity' => 'OptionValue',
928 'placeholder' => $placeholder,
929 'multiple' => $search,
931 'params' => ['option_group_id' => $field->option_group_id
, 'is_active' => 1],
934 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
937 $qf->assign('customUrls', $customUrls);
941 switch ($field->data_type
) {
943 // integers will have numeric rule applied to them.
944 if ($field->is_search_range
&& $search) {
945 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', [1 => $label]), 'integer');
946 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', [1 => $label]), 'integer');
948 elseif ($widget == 'Text') {
949 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', [1 => $label]), 'integer');
954 if ($field->is_search_range
&& $search) {
955 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', [1 => $label]), 'numeric');
956 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', [1 => $label]), 'numeric');
958 elseif ($widget == 'Text') {
959 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', [1 => $label]), 'numeric');
964 if ($field->is_search_range
&& $search) {
965 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
966 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
968 elseif ($widget == 'Text') {
969 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
974 $element->setAttribute('class', "url");
975 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
978 if ($field->is_view
&& !$search) {
979 $qf->freeze($elementName);
985 * Delete the Custom Field.
987 * @param object $field
990 public static function deleteField($field) {
991 CRM_Utils_System
::flushCache();
993 // first delete the custom option group and values associated with this field
994 if ($field->option_group_id
) {
995 //check if option group is related to any other field, if
996 //not delete the option group and related option values
997 self
::checkOptionGroup($field->option_group_id
);
1000 // next drop the column from the custom value table
1001 self
::createField($field, 'delete');
1004 CRM_Core_BAO_UFField
::delUFField($field->id
);
1005 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1007 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
1011 * @param string|int|array|null $value
1012 * @param CRM_Core_BAO_CustomField|int|array|string $field
1013 * @param int $entityId
1017 * @throws \CRM_Core_Exception
1019 public static function displayValue($value, $field, $entityId = NULL) {
1020 $field = is_array($field) ?
$field['id'] : $field;
1021 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1024 throw new CRM_Core_Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1027 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1028 $field = self
::getFieldObject($fieldId);
1031 $fieldInfo = ['options' => $field->getOptions()] +
(array) $field;
1033 $displayValue = self
::formatDisplayValue($value, $fieldInfo, $entityId);
1035 // Call hook to alter display value.
1036 CRM_Utils_Hook
::alterCustomFieldDisplayValue($displayValue, $value, $entityId, $fieldInfo);
1038 return $displayValue;
1042 * Lower-level logic for rendering a custom field value
1044 * @param string|array $value
1045 * @param array $field
1046 * @param int|null $entityId
1050 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1052 if (self
::isSerialized($field) && !is_array($value)) {
1053 $value = CRM_Utils_Array
::explodePadded($value);
1056 if ($field['html_type'] == 'CheckBox' && $value) {
1057 $value = CRM_Utils_Array
::convertCheckboxFormatToArray($value);
1060 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1062 switch ($field['html_type']) {
1065 case 'Autocomplete-Select':
1067 case 'Select Country':
1068 case 'Select State/Province':
1070 if ($field['data_type'] == 'ContactReference' && $value) {
1071 if (is_numeric($value)) {
1072 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1078 elseif (is_array($value)) {
1080 foreach ($value as $key => $val) {
1081 $v[] = $field['options'][$val] ??
NULL;
1083 $display = implode(', ', $v);
1086 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1091 $customFormat = NULL;
1093 // FIXME: Are there any legitimate reasons why $value would be an array?
1094 // Or should we throw an exception here if it is?
1095 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1097 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1098 $format = $field['date_format'] ??
NULL;
1101 if (array_key_exists($format, $actualPHPFormats)) {
1102 $customTimeFormat = (array) $actualPHPFormats[$format];
1103 switch (CRM_Utils_Array
::value('time_format', $field)) {
1105 $customTimeFormat[] = 'g:iA';
1109 $customTimeFormat[] = 'G:i';
1113 //If time is not selected remove time from value.
1114 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1116 $customFormat = implode(" ", $customTimeFormat);
1119 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1123 // In the context of displaying a profile, show file/image
1126 if (CRM_Utils_Rule
::positiveInteger($value)) {
1130 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1132 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1134 $display = $url['file_url'];
1138 // In other contexts show a paperclip icon
1139 if (CRM_Utils_Rule
::integer($value)) {
1140 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1142 $file_description = '';
1144 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1146 catch (CiviCRM_API3_Exception
$dontcare) {
1150 $display = "{$icons[$value]}{$file_description}";
1153 //CRM-18396, if filename is passed instead
1161 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1165 $display = nl2br($display);
1169 if ($field['data_type'] == 'Money' && isset($value)) {
1170 // $value can also be an array(while using IN operator from search builder or api).
1171 foreach ((array) $value as $val) {
1172 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1174 $display = implode(', ', $disp);
1182 * Set default values for custom data used in profile.
1184 * @param int $customFieldId
1186 * @param string $elementName
1187 * Custom field name.
1188 * @param array $defaults
1189 * Associated array of fields.
1190 * @param int $contactId
1194 * @param mixed $value
1195 * If passed - dont fetch value from db,.
1196 * just format the given value
1198 public static function setProfileDefaults(
1206 //get the type of custom field
1207 $customField = new CRM_Core_BAO_CustomField();
1208 $customField->id
= $customFieldId;
1209 $customField->find(TRUE);
1212 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1213 $value = $customField->default_value
;
1217 if (!isset($value)) {
1218 $info = self
::getTableColumnGroup($customFieldId);
1219 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1220 $result = CRM_Core_DAO
::executeQuery($query);
1221 if ($result->fetch()) {
1222 $value = $result->value
;
1226 if ($customField->data_type
== 'Country') {
1228 $config = CRM_Core_Config
::singleton();
1229 if ($config->defaultContactCountry
) {
1230 $value = CRM_Core_BAO_Country
::defaultContactCountry();
1236 //set defaults if mode is registration
1237 if (!trim($value) &&
1239 (!in_array($mode, [CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
]))
1241 $value = $customField->default_value
;
1244 if ($customField->data_type
== 'Money' && isset($value)) {
1245 $value = number_format($value, 2);
1247 if (self
::isSerialized($customField) && $value) {
1248 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1249 $defaults[$elementName] = [];
1250 $checkedValue = CRM_Utils_Array
::explodePadded($value);
1251 foreach ($customOption as $val) {
1252 if (in_array($val['value'], $checkedValue)) {
1253 if ($customField->html_type
== 'CheckBox') {
1254 $defaults[$elementName][$val['value']] = 1;
1257 $defaults[$elementName][$val['value']] = $val['value'];
1263 $defaults[$elementName] = $value;
1270 * @param int $contactID
1272 * @param int $fileID
1273 * @param bool $absolute
1275 * @param string $multiRecordWhereClause
1279 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1282 $params = ['id' => $cfID];
1284 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1285 $columnName = $defaults['column_name'];
1287 //table name of custom data
1288 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1289 $defaults['custom_group_id'],
1293 //query to fetch id from civicrm_file
1294 if ($multiRecordWhereClause) {
1295 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1298 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1300 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1305 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1310 $result['file_id'] = $fileID;
1312 if ($fileType == 'image/jpeg' ||
1313 $fileType == 'image/pjpeg' ||
1314 $fileType == 'image/gif' ||
1315 $fileType == 'image/x-png' ||
1316 $fileType == 'image/png'
1318 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1323 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1324 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1325 $url = CRM_Utils_System
::url('civicrm/file',
1326 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1327 $absolute, NULL, TRUE, TRUE
1329 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1331 // for non image files
1333 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1337 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1338 $url = CRM_Utils_System
::url('civicrm/file',
1339 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1340 $absolute, NULL, TRUE, TRUE
1342 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1350 * Format custom fields before inserting.
1352 * @param int $customFieldId
1354 * @param array $customFormatted
1356 * @param mixed $value
1357 * Value of custom field.
1358 * @param string $customFieldExtend
1359 * Custom field extends.
1360 * @param int $customValueId
1361 * Custom option value id.
1362 * @param int $entityId
1363 * Entity id (contribution, membership...).
1364 * @param bool $inline
1365 * Consider inline custom groups only.
1366 * @param bool $checkPermission
1367 * If false, do not include permissioning clause.
1368 * @param bool $includeViewOnly
1369 * If true, fields marked 'View Only' are included. Required for APIv3.
1371 * @return array|NULL
1372 * formatted custom field array
1374 public static function formatCustomField(
1375 $customFieldId, &$customFormatted, $value,
1376 $customFieldExtend, $customValueId = NULL,
1379 $checkPermission = TRUE,
1380 $includeViewOnly = FALSE
1382 //get the custom fields for the entity
1383 //subtype and basic type
1384 $customDataSubType = NULL;
1385 if ($customFieldExtend) {
1386 // This is the case when getFieldsForImport() requires fields
1387 // of subtype and its parent.CRM-5143
1388 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1389 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1390 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1391 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1392 if (is_array($customFieldExtend)) {
1393 $customFieldExtend = array_unique(array_values($customFieldExtend));
1398 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1408 if (!array_key_exists($customFieldId, $customFields)) {
1412 // return if field is a 'code' field
1413 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1417 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1419 if (!$customValueId &&
1420 // we always create new entites for is_multiple unless specified
1421 !$customFields[$customFieldId]['is_multiple'] &&
1427 WHERE entity_id={$entityId}";
1429 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1432 //fix checkbox, now check box always submits values
1433 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1435 // Note that only during merge this is not an array, and you can directly use value
1436 if (is_array($value)) {
1437 $selectedValues = [];
1438 foreach ($value as $selId => $val) {
1440 $selectedValues[] = $selId;
1443 if (!empty($selectedValues)) {
1444 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1446 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1454 elseif (self
::isSerialized($customFields[$customFieldId])) {
1455 $value = $value ? CRM_Utils_Array
::implodePadded($value) : '';
1458 if (self
::isSerialized($customFields[$customFieldId]) &&
1459 $customFields[$customFieldId]['data_type'] == 'String' &&
1460 !empty($customFields[$customFieldId]['text_length']) &&
1463 // lets make sure that value is less than the length, else we'll
1464 // be losing some data, CRM-7481
1465 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1466 // need to do a few things here
1468 // 1. lets find a new length
1469 $newLength = $customFields[$customFieldId]['text_length'];
1470 $minLength = strlen($value);
1471 while ($newLength < $minLength) {
1472 $newLength = $newLength * 2;
1475 // set the custom field meta data to have a length larger than value
1476 // alter the custom value table column to match this length
1477 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1482 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1483 if (!CRM_Utils_System
::isNull($value)) {
1484 $format = $customFields[$customFieldId]['date_format'];
1485 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1490 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1491 $customFields[$customFieldId]['data_type'] == 'Money'
1497 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1498 $value = CRM_Utils_Rule
::cleanMoney($value);
1502 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1503 $customFields[$customFieldId]['data_type'] == 'Country'
1513 if ($customFields[$customFieldId]['data_type'] == 'File') {
1514 if (empty($value)) {
1518 $config = CRM_Core_Config
::singleton();
1520 // If we are already passing the file id as a value then retrieve and set the file data
1521 if (CRM_Utils_Rule
::integer($value)) {
1522 $fileDAO = new CRM_Core_DAO_File();
1523 $fileDAO->id
= $value;
1524 $fileDAO->find(TRUE);
1527 $fName = $fileDAO->uri
;
1528 $mimeType = $fileDAO->mime_type
;
1532 $fName = $value['name'];
1533 $mimeType = $value['type'];
1536 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1538 // rename this file to go into the secure directory only if
1539 // user has uploaded new file not existing verfied on the basis of $fileID
1540 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1541 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1544 if ($customValueId && empty($fileID)) {
1549 $params = [1 => [$customValueId, 'Integer']];
1550 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1553 $fileDAO = new CRM_Core_DAO_File();
1556 $fileDAO->id
= $fileID;
1559 $fileDAO->uri
= $filename;
1560 $fileDAO->mime_type
= $mimeType;
1561 $fileDAO->upload_date
= date('YmdHis');
1563 $fileID = $fileDAO->id
;
1567 if (!is_array($customFormatted)) {
1568 $customFormatted = [];
1571 if (!array_key_exists($customFieldId, $customFormatted)) {
1572 $customFormatted[$customFieldId] = [];
1576 if ($customValueId) {
1577 $index = $customValueId;
1580 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1581 $customFormatted[$customFieldId][$index] = [];
1583 $customFormatted[$customFieldId][$index] = [
1584 'id' => $customValueId > 0 ?
$customValueId : NULL,
1586 'type' => $customFields[$customFieldId]['data_type'],
1587 'custom_field_id' => $customFieldId,
1588 'custom_group_id' => $groupID,
1589 'table_name' => $tableName,
1590 'column_name' => $columnName,
1591 'file_id' => $fileID,
1592 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1595 //we need to sort so that custom fields are created in the order of entry
1596 krsort($customFormatted[$customFieldId]);
1597 return $customFormatted;
1601 * Get default custom table schema.
1603 * @param array $params
1607 public static function defaultCustomTableSchema($params) {
1608 // add the id and extends_id
1610 'name' => $params['name'],
1611 'is_multiple' => $params['is_multiple'],
1612 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1616 'type' => 'int unsigned',
1619 'attributes' => 'AUTO_INCREMENT',
1620 'comment' => 'Default MySQL primary key',
1623 'name' => 'entity_id',
1624 'type' => 'int unsigned',
1626 'comment' => 'Table that this extends',
1627 'fk_table_name' => $params['extends_name'],
1628 'fk_field_name' => 'id',
1629 'fk_attributes' => 'ON DELETE CASCADE',
1634 if (!$params['is_multiple']) {
1635 $table['indexes'] = [
1638 'field_name_1' => 'entity_id',
1646 * Create custom field.
1648 * @param CRM_Core_DAO_CustomField $field
1649 * @param string $operation
1651 public static function createField($field, $operation) {
1652 $sql = str_repeat(' ', 8);
1653 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1654 $sql .= "ALTER TABLE " . $tableName;
1655 $sql .= self
::getAlterFieldSQL($field, $operation);
1657 // CRM-7007: do not i18n-rewrite this query
1658 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1660 $config = CRM_Core_Config
::singleton();
1661 if ($config->logging
) {
1662 // CRM-16717 not sure why this was originally limited to add.
1663 // For example custom tables can have field length changes - which need to flow through to logging.
1664 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1665 if ($operation === 'add' ||
$operation === 'modify') {
1666 $logging = new CRM_Logging_Schema();
1667 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name
]]);
1671 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
1675 * @param CRM_Core_DAO_CustomField $field
1676 * @param string $operation
1680 public static function getAlterFieldSQL($field, $operation) {
1681 $indexExist = $operation === 'add' ?
FALSE : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $field->id
, 'is_searchable');
1682 $params = self
::prepareCreateParams($field, $operation);
1683 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1684 // a function only used by Custom Field creation...
1685 $params['required'] = FALSE;
1686 return CRM_Core_BAO_SchemaHandler
::getFieldAlterSQL($params, $indexExist);
1690 * Determine whether it would be safe to move a field.
1692 * @param int $fieldID
1693 * FK to civicrm_custom_field.
1694 * @param int $newGroupID
1695 * FK to civicrm_custom_group.
1698 * array(string) or TRUE
1700 public static function _moveFieldValidate($fieldID, $newGroupID) {
1703 $field = new CRM_Core_DAO_CustomField();
1704 $field->id
= $fieldID;
1705 if (!$field->find(TRUE)) {
1706 $errors['fieldID'] = 'Invalid ID for custom field';
1710 $oldGroup = new CRM_Core_DAO_CustomGroup();
1711 $oldGroup->id
= $field->custom_group_id
;
1712 if (!$oldGroup->find(TRUE)) {
1713 $errors['fieldID'] = 'Invalid ID for old custom group';
1717 $newGroup = new CRM_Core_DAO_CustomGroup();
1718 $newGroup->id
= $newGroupID;
1719 if (!$newGroup->find(TRUE)) {
1720 $errors['newGroupID'] = 'Invalid ID for new custom group';
1726 FROM civicrm_custom_field a
1727 INNER JOIN civicrm_custom_field b
1729 AND a.label = b.label
1730 AND b.custom_group_id = %2
1733 1 => [$field->id
, 'Integer'],
1734 2 => [$newGroup->id
, 'Integer'],
1736 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1738 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1741 $tableName = $oldGroup->table_name
;
1742 $columnName = $field->column_name
;
1747 WHERE $columnName is not null
1749 $count = CRM_Core_DAO
::singleValueQuery($query);
1753 FROM civicrm_custom_group
1754 WHERE id IN ( %1, %2 )
1757 1 => [$oldGroup->id
, 'Integer'],
1758 2 => [$newGroup->id
, 'Integer'],
1761 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1763 while ($dao->fetch()) {
1764 $extends[] = $dao->extends;
1766 if ($extends[0] != $extends[1]) {
1767 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1771 return empty($errors) ?
TRUE : $errors;
1775 * Move a custom data field from one group (table) to another.
1777 * @param int $fieldID
1778 * FK to civicrm_custom_field.
1779 * @param int $newGroupID
1780 * FK to civicrm_custom_group.
1782 * @throws CRM_Core_Exception
1784 public static function moveField($fieldID, $newGroupID) {
1785 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1786 if (TRUE !== $validation) {
1787 throw new CRM_Core_Exception(implode(' ', $validation));
1789 $field = new CRM_Core_DAO_CustomField();
1790 $field->id
= $fieldID;
1793 $newGroup = new CRM_Core_DAO_CustomGroup();
1794 $newGroup->id
= $newGroupID;
1795 $newGroup->find(TRUE);
1797 $oldGroup = new CRM_Core_DAO_CustomGroup();
1798 $oldGroup->id
= $field->custom_group_id
;
1799 $oldGroup->find(TRUE);
1802 $add->custom_group_id
= $newGroup->id
;
1803 self
::createField($add, 'add');
1805 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1806 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1807 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1809 CRM_Core_DAO
::executeQuery($sql);
1812 $del->custom_group_id
= $oldGroup->id
;
1813 self
::createField($del, 'delete');
1817 CRM_Utils_System
::flushCache();
1821 * Create an option value for a custom field option group ID.
1823 * @param array $params
1824 * @param string $value
1825 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1826 * @param string $index
1827 * @param string $dataType
1829 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $index, $dataType) {
1830 if (strlen(trim($value))) {
1831 $optionValue = new CRM_Core_DAO_OptionValue();
1832 $optionValue->option_group_id
= $optionGroup->id
;
1833 $optionValue->label
= $params['option_label'][$index];
1834 $optionValue->name
= $params['option_name'][$index] ?? CRM_Utils_String
::titleToVar($params['option_label'][$index]);
1835 switch ($dataType) {
1837 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1841 $optionValue->value
= intval($value);
1845 $optionValue->value
= floatval($value);
1849 $optionValue->value
= trim($value);
1852 $optionValue->weight
= $params['option_weight'][$index];
1853 $optionValue->is_active
= $params['option_status'][$index] ??
FALSE;
1854 $optionValue->description
= $params['option_description'][$index] ??
NULL;
1855 $optionValue->color
= $params['option_color'][$index] ??
NULL;
1856 $optionValue->icon
= $params['option_icon'][$index] ??
NULL;
1857 $optionValue->save();
1862 * Prepare for the create operation.
1864 * Munge params, create the option values if needed.
1866 * This could be called by a single create or a batchCreate.
1868 * @param array $params
1872 protected static function prepareCreate($params) {
1873 $op = empty($params['id']) ?
'create' : 'edit';
1874 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1875 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1876 if ($op === 'create') {
1877 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1878 if (!isset($params['column_name'])) {
1879 // if add mode & column_name not present, calculate it.
1880 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1882 if (!isset($params['name'])) {
1883 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1887 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'column_name');
1890 $htmlType = $params['html_type'] ??
NULL;
1891 $dataType = $params['data_type'] ??
NULL;
1893 if ($htmlType === 'Select Date' && empty($params['date_format'])) {
1894 $params['date_format'] = Civi
::settings()->get('dateInputFormat');
1897 // Checkboxes are always serialized in current schema
1898 if ($htmlType == 'CheckBox') {
1899 $params['serialize'] = CRM_Core_DAO
::SERIALIZE_SEPARATOR_BOOKEND
;
1902 if (!empty($params['serialize'])) {
1903 if (isset($params['default_checkbox_option'])) {
1905 foreach (array_keys($params['default_checkbox_option']) as $k => $v) {
1906 if ($params['option_value'][$v]) {
1907 $defaultArray[] = $params['option_value'][$v];
1911 if (!empty($defaultArray)) {
1912 // also add the separator before and after the value per new convention (CRM-1604)
1913 $params['default_value'] = CRM_Utils_Array
::implodePadded($defaultArray);
1917 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])) {
1918 $params['default_value'] = $params['option_value'][$params['default_option']];
1923 // create any option group & values if required
1924 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1925 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)) {
1926 //CRM-16659: if option_value then create an option group for this custom field.
1927 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
1928 // first create an option group for this custom group
1929 $optionGroup = new CRM_Core_DAO_OptionGroup();
1930 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
1931 $optionGroup->title
= $params['label'];
1932 $optionGroup->is_active
= 1;
1933 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1934 $optionGroup->is_reserved
= 0;
1935 $optionGroup->data_type
= $dataType;
1936 $optionGroup->save();
1937 $params['option_group_id'] = $optionGroup->id
;
1938 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1939 foreach ($params['option_value'] as $k => $v) {
1940 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1946 // check for orphan option groups
1947 if (!empty($params['option_group_id'])) {
1948 if (!empty($params['id'])) {
1949 self
::fixOptionGroups($params['id'], $params['option_group_id']);
1952 // if we do not have a default value
1953 // retrieve it from one of the other custom fields which use this option group
1954 if (empty($params['default_value'])) {
1955 //don't insert only value separator as default value, CRM-4579
1956 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'], !empty($params['serialize']));
1958 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultValue))) {
1959 $params['default_value'] = $defaultValue;
1964 // Set default textarea attributes
1965 if ($op == 'create' && !isset($params['attributes']) && $htmlType == 'TextArea') {
1966 $params['attributes'] = 'rows=4, cols=60';
1972 * Create database entry for custom field and related option groups.
1974 * @param array $params
1976 * @return CRM_Core_DAO_CustomField
1978 protected static function createCustomFieldRecord($params) {
1979 $transaction = new CRM_Core_Transaction();
1980 $params = self
::prepareCreate($params);
1982 $customField = new CRM_Core_DAO_CustomField();
1983 $customField->copyValues($params);
1984 $customField->save();
1986 //create/drop the index when we toggle the is_searchable flag
1987 $op = empty($params['id']) ?
'add' : 'modify';
1988 if ($op !== 'modify') {
1989 if ($params['is_append_field_id_to_column_name']) {
1990 $params['column_name'] .= "_{$customField->id}";
1992 $customField->column_name
= $params['column_name'];
1993 $customField->save();
1996 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
1997 $transaction->commit();
1999 // make sure all values are present in the object for further processing
2000 $customField->find(TRUE);
2001 return $customField;
2005 * Move custom data from one contact to another.
2007 * This is currently the start of a refactoring. The theory is each
2008 * entity could have a 'move' function with a DAO default one to fall back on.
2010 * At the moment this only does a small part of the process - ie deleting a file field that
2011 * is about to be overwritten. However, the goal is the whole process around the move for
2012 * custom data should be in here.
2014 * This is currently called by the merge class but it makes sense that api could
2015 * expose move actions as moving (e.g) contributions feels like a common
2016 * ask that should be handled by the form layer.
2018 * @param int $oldContactID
2019 * @param int $newContactID
2020 * @param int[] $fieldIDs
2021 * Optional list field ids to move.
2023 * @throws \CiviCRM_API3_Exception
2024 * @throws \Exception
2026 public function move($oldContactID, $newContactID, $fieldIDs) {
2027 if (empty($fieldIDs)) {
2030 $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'];
2032 foreach ($fieldIDs as $fieldID) {
2033 $return[] = 'custom_' . $fieldID;
2035 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2036 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2038 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2039 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2040 $fieldTypesNotHandledInMergeAttempt = ['File'];
2041 foreach ($fields as $field) {
2042 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2043 if ($field['data_type'] === 'File' && !$isMultiple) {
2044 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2045 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2047 if (!empty($oldContact['custom_' . $field['id']])) {
2048 CRM_Core_DAO
::executeQuery("
2049 UPDATE civicrm_entity_file
2050 SET entity_id = $newContactID
2051 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2055 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2056 CRM_Core_DAO
::executeQuery(
2057 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2058 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2059 ON DUPLICATE KEY UPDATE
2060 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2067 * Get the database table name and column name for a custom field.
2069 * @param int $fieldID
2070 * The fieldID of the custom field.
2071 * @param bool $force
2072 * Force the sql to be run again (primarily used for tests).
2075 * fatal is fieldID does not exists, else array of tableName, columnName
2076 * @throws \CRM_Core_Exception
2078 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2079 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2080 $cache = CRM_Utils_Cache
::singleton();
2081 $fieldValues = $cache->get($cacheKey);
2082 if (empty($fieldValues) ||
$force) {
2084 SELECT cg.table_name, cf.column_name, cg.id
2085 FROM civicrm_custom_group cg,
2086 civicrm_custom_field cf
2087 WHERE cf.custom_group_id = cg.id
2089 $params = [1 => [$fieldID, 'Integer']];
2090 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2092 if (!$dao->fetch()) {
2093 throw new CRM_Core_Exception("Cannot find table and column information for Custom Field " . $fieldID);
2095 $fieldValues = [$dao->table_name
, $dao->column_name
, $dao->id
];
2096 $cache->set($cacheKey, $fieldValues);
2098 return $fieldValues;
2102 * Get custom option groups.
2104 * @deprecated Use the API OptionGroup.get
2106 * @param array $includeFieldIds
2107 * Ids of custom fields for which option groups must be included.
2109 * Currently this is required in the cases where option groups are to be included
2110 * for inactive fields : CRM-5369
2114 public static function customOptionGroup($includeFieldIds = NULL) {
2115 static $customOptionGroup = NULL;
2117 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2118 if ($cacheKey == 'force') {
2119 $customOptionGroup[$cacheKey] = NULL;
2122 if (empty($customOptionGroup[$cacheKey])) {
2123 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2125 //support for single as well as array format.
2126 if (!empty($includeFieldIds)) {
2127 if (is_array($includeFieldIds)) {
2128 $includeFieldIds = implode(',', $includeFieldIds);
2130 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2134 SELECT g.id, g.title
2135 FROM civicrm_option_group g
2136 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2137 WHERE {$whereClause}";
2139 $dao = CRM_Core_DAO
::executeQuery($query);
2140 while ($dao->fetch()) {
2141 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2145 return $customOptionGroup[$cacheKey];
2149 * Get defaults for new entity.
2153 public static function getDefaults() {
2155 'is_required' => FALSE,
2156 'is_searchable' => FALSE,
2157 'in_selector' => FALSE,
2158 'is_search_range' => FALSE,
2159 //CRM-15792 - Custom field gets disabled if is_active not set
2160 // this would ideally be a mysql default.
2161 'is_active' => TRUE,
2167 * Fix orphan groups.
2169 * @param int $customFieldId
2171 * @param int $optionGroupId
2174 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2175 // check if option group belongs to any custom Field else delete
2176 // get the current option group
2177 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2181 // get the updated option group
2182 // if both are same return
2183 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2187 // check if option group is related to any other field
2188 self
::checkOptionGroup($currentOptionGroupId);
2192 * Check if option group is related to more than one custom field.
2194 * @param int $optionGroupId
2197 public static function checkOptionGroup($optionGroupId) {
2200 FROM civicrm_custom_field
2201 WHERE option_group_id = {$optionGroupId}";
2203 $count = CRM_Core_DAO
::singleValueQuery($query);
2206 //delete the option group
2207 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2212 * Get option group default.
2214 * @param int $optionGroupId
2215 * @param bool $serialize
2217 * @return null|string
2219 public static function getOptionGroupDefault($optionGroupId, $serialize) {
2221 SELECT default_value, serialize
2222 FROM civicrm_custom_field
2223 WHERE option_group_id = {$optionGroupId}
2224 AND default_value IS NOT NULL";
2226 $dao = CRM_Core_DAO
::executeQuery($query);
2227 while ($dao->fetch()) {
2228 if ($dao->serialize
== $serialize) {
2229 return $dao->default_value
;
2231 $defaultValue = $dao->default_value
;
2234 // Convert serialization
2235 if (isset($defaultValue) && $serialize) {
2236 return CRM_Utils_Array
::implodePadded([$defaultValue]);
2238 elseif (isset($defaultValue)) {
2239 return CRM_Utils_Array
::explodePadded($defaultValue)[0];
2245 * Post process function.
2247 * @param array $params
2248 * @param int $entityID
2249 * @param string $customFieldExtends
2250 * @param bool $inline
2251 * @param bool $checkPermissions
2255 public static function postProcess(
2258 $customFieldExtends,
2260 $checkPermissions = TRUE
2264 foreach ($params as $key => $value) {
2265 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2267 // for autocomplete transfer hidden value instead of label
2268 if ($params[$key] && isset($params[$key . '_id'])) {
2269 $value = $params[$key . '_id'];
2272 // we need to append time with date
2273 if ($params[$key] && isset($params[$key . '_time'])) {
2274 $value .= ' ' . $params[$key . '_time'];
2277 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2280 $customFieldExtends,
2281 $customFieldInfo[1],
2292 * Get custom field ID from field/group name/title.
2294 * @param string $fieldName Field name or label
2295 * @param string|null $groupName (Optional) Group name or label
2296 * @param bool $fullString Whether to return "custom_123" or "123"
2298 * @return string|int|null
2299 * @throws \CiviCRM_API3_Exception
2301 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2302 $cacheKey = $groupName . '.' . $fieldName;
2303 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2304 $customFieldParams = [
2305 'name' => $fieldName,
2306 'label' => $fieldName,
2307 'options' => ['or' => [["name", "label"]]],
2311 $customFieldParams['custom_group_id.name'] = $groupName;
2312 $customFieldParams['custom_group_id.title'] = $groupName;
2313 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2316 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2318 if (empty($field['id'])) {
2319 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2320 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2323 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2324 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2329 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2331 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2335 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2341 public static function getNameFromID($ids) {
2342 if (is_array($ids)) {
2343 $ids = implode(',', $ids);
2346 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2347 FROM civicrm_custom_field f
2348 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2349 WHERE f.id IN ($ids)";
2351 $dao = CRM_Core_DAO
::executeQuery($sql);
2353 while ($dao->fetch()) {
2354 $result[$dao->id
] = [
2355 'field_name' => $dao->field_name
,
2356 'field_label' => $dao->field_label
,
2357 'group_name' => $dao->group_name
,
2358 'group_title' => $dao->group_title
,
2365 * Validate custom data.
2367 * @param array $params
2368 * Custom data submitted.
2369 * ie array( 'custom_1' => 'validate me' );
2372 * validation errors.
2374 public static function validateCustomData($params) {
2376 if (!is_array($params) ||
empty($params)) {
2380 //pick up profile fields.
2381 $profileFields = [];
2382 $ufGroupId = $params['ufGroupId'] ??
NULL;
2384 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2386 CRM_Core_Action
::VIEW
2390 //lets start w/ params.
2391 foreach ($params as $key => $value) {
2392 $customFieldID = self
::getKeyID($key);
2393 if (!$customFieldID) {
2397 //load the structural info for given field.
2398 $field = new CRM_Core_DAO_CustomField();
2399 $field->id
= $customFieldID;
2400 if (!$field->find(TRUE)) {
2403 $dataType = $field->data_type
;
2405 $profileField = CRM_Utils_Array
::value($key, $profileFields, []);
2406 $fieldTitle = $profileField['title'] ??
NULL;
2407 $isRequired = $profileField['is_required'] ??
NULL;
2409 $fieldTitle = $field->label
;
2412 //no need to validate.
2413 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2417 //lets validate first for required field.
2418 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2419 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
2423 //now time to take care of custom field form rules.
2424 $ruleName = $errorMsg = NULL;
2425 switch ($dataType) {
2427 $ruleName = 'integer';
2428 $errorMsg = ts('%1 must be an integer (whole number).',
2429 array(1 => $fieldTitle)
2434 $ruleName = 'money';
2435 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2436 array(1 => $fieldTitle)
2441 $ruleName = 'numeric';
2442 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2443 array(1 => $fieldTitle)
2448 $ruleName = 'wikiURL';
2449 $errorMsg = ts('%1 must be valid Website.',
2450 array(1 => $fieldTitle)
2455 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2457 $funName = "CRM_Utils_Rule::{$ruleName}";
2458 if (is_callable($funName)) {
2459 $valid = call_user_func($funName, $value);
2462 $errors[$key] = $errorMsg;
2471 * Is this field a multi record field.
2473 * @param int $customId
2477 public static function isMultiRecordField($customId) {
2478 $isMultipleWithGid = FALSE;
2479 if (!is_numeric($customId)) {
2480 $customId = self
::getKeyID($customId);
2482 if (is_numeric($customId)) {
2483 $sql = "SELECT cg.id cgId
2484 FROM civicrm_custom_group cg
2485 INNER JOIN civicrm_custom_field cf
2486 ON cg.id = cf.custom_group_id
2487 WHERE cf.id = %1 AND cg.is_multiple = 1";
2488 $params[1] = [$customId, 'Integer'];
2489 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2490 if ($dao->fetch()) {
2492 $isMultipleWithGid = $dao->cgId
;
2497 return $isMultipleWithGid;
2501 * Does this field type have any select options?
2503 * @param array $field
2507 public static function hasOptions($field) {
2508 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2509 $field = (array) $field;
2510 // This will include boolean fields with Yes/No options.
2511 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2514 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2515 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2516 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2519 if (strpos($field['html_type'], 'Select') !== FALSE) {
2522 return !empty($field['option_group_id']);
2526 * Does this field store a serialized string?
2528 * @param CRM_Core_DAO_CustomField|array $field
2532 public static function isSerialized($field) {
2533 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2534 $html_type = is_object($field) ?
$field->html_type
: $field['html_type'];
2535 // APIv3 has a "legacy" mode where it returns old-style html_type of "Multi-Select"
2536 // If anyone is using this function in conjunction with legacy api output, we'll accomodate:
2537 if ($html_type === 'CheckBox' ||
strpos($html_type, 'Multi') !== FALSE) {
2540 // Otherwise this is the new standard as of 5.26
2541 return is_object($field) ?
!empty($field->serialize
) : !empty($field['serialize']);
2545 * Get api entity for this field
2549 public function getEntity() {
2550 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2551 return in_array($entity, ['Individual', 'Household', 'Organization']) ?
'Contact' : $entity;
2555 * Set pseudoconstant properties for field metadata.
2557 * @param array $field
2558 * @param string|null $optionGroupName
2560 private static function getOptionsForField(&$field, $optionGroupName) {
2561 if ($optionGroupName) {
2562 $field['pseudoconstant'] = [
2563 'optionGroupName' => $optionGroupName,
2564 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2567 elseif ($field['data_type'] == 'Boolean') {
2568 $field['pseudoconstant'] = [
2569 'callback' => 'CRM_Core_SelectValues::boolean',
2572 elseif ($field['data_type'] == 'Country') {
2573 $field['pseudoconstant'] = [
2574 'table' => 'civicrm_country',
2575 'keyColumn' => 'id',
2576 'labelColumn' => 'name',
2577 'nameColumn' => 'iso_code',
2580 elseif ($field['data_type'] == 'StateProvince') {
2581 $field['pseudoconstant'] = [
2582 'table' => 'civicrm_state_province',
2583 'keyColumn' => 'id',
2584 'labelColumn' => 'name',
2590 * @param CRM_Core_DAO_CustomField $field
2591 * @param 'add|modify' $operation
2595 protected static function prepareCreateParams($field, $operation) {
2596 $tableName = CRM_Core_DAO
::getFieldValue(
2597 'CRM_Core_DAO_CustomGroup',
2598 $field->custom_group_id
,
2603 'table_name' => $tableName,
2604 'operation' => $operation,
2605 'name' => $field->column_name
,
2606 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2610 'required' => $field->is_required
,
2611 'searchable' => $field->is_searchable
,
2614 if ($operation == 'delete') {
2615 $fkName = "{$tableName}_{$field->column_name}";
2616 if (strlen($fkName) >= 48) {
2617 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2619 $params['fkName'] = $fkName;
2621 if ($field->data_type
== 'Country' && !self
::isSerialized($field)) {
2622 $params['fk_table_name'] = 'civicrm_country';
2623 $params['fk_field_name'] = 'id';
2624 $params['fk_attributes'] = 'ON DELETE SET NULL';
2626 elseif ($field->data_type
== 'StateProvince' && !self
::isSerialized($field)) {
2627 $params['fk_table_name'] = 'civicrm_state_province';
2628 $params['fk_field_name'] = 'id';
2629 $params['fk_attributes'] = 'ON DELETE SET NULL';
2631 elseif ($field->data_type
== 'StateProvince' ||
$field->data_type
== 'Country') {
2632 $params['type'] = 'varchar(255)';
2634 elseif ($field->data_type
== 'File') {
2635 $params['fk_table_name'] = 'civicrm_file';
2636 $params['fk_field_name'] = 'id';
2637 $params['fk_attributes'] = 'ON DELETE SET NULL';
2639 elseif ($field->data_type
== 'ContactReference') {
2640 $params['fk_table_name'] = 'civicrm_contact';
2641 $params['fk_field_name'] = 'id';
2642 $params['fk_attributes'] = 'ON DELETE SET NULL';
2644 if (isset($field->default_value
)) {
2645 $params['default'] = "'{$field->default_value}'";