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 for valid combinations of data_type & descriptions.
28 public static $_dataType = NULL;
31 * Array for valid combinations of data_type & html_type.
35 public static $_dataToHtml = NULL;
38 * Array to hold (formatted) fields for import
42 public static $_importFields = NULL;
45 * Build and retrieve the list of data types and descriptions.
48 * Data type => Description
50 public static function &dataType() {
51 if (!(self
::$_dataType)) {
53 'String' => ts('Alphanumeric'),
54 'Int' => ts('Integer'),
55 'Float' => ts('Number'),
56 'Money' => ts('Money'),
59 'Boolean' => ts('Yes or No'),
60 'StateProvince' => ts('State/Province'),
61 'Country' => ts('Country'),
64 'ContactReference' => ts('Contact Reference'),
67 return self
::$_dataType;
71 * Build the map of custom field's data types and there respective Util type
74 * Data data-type => CRM_Utils_Type
76 public static function dataToType() {
78 'String' => CRM_Utils_Type
::T_STRING
,
79 'Int' => CRM_Utils_Type
::T_INT
,
80 'Money' => CRM_Utils_Type
::T_MONEY
,
81 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
82 'Float' => CRM_Utils_Type
::T_FLOAT
,
83 'Date' => CRM_Utils_Type
::T_DATE
,
84 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
85 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
86 'StateProvince' => CRM_Utils_Type
::T_INT
,
87 'File' => CRM_Utils_Type
::T_STRING
,
88 'Link' => CRM_Utils_Type
::T_STRING
,
89 'ContactReference' => CRM_Utils_Type
::T_INT
,
90 'Country' => CRM_Utils_Type
::T_INT
,
95 * Get data to html array.
97 * (Does this caching achieve anything?)
101 public static function dataToHtml() {
102 if (!self
::$_dataToHtml) {
103 self
::$_dataToHtml = [
106 'Select' => 'Select',
108 'CheckBox' => 'CheckBox',
109 'Multi-Select' => 'Multi-Select',
110 'Autocomplete-Select' => 'Autocomplete-Select',
112 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
113 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
114 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
115 ['TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'],
116 ['Date' => 'Select Date'],
117 ['Radio' => 'Radio'],
118 ['StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'],
119 ['Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'],
122 ['ContactReference' => 'Autocomplete-Select'],
125 return self
::$_dataToHtml;
129 * Takes an associative array and creates a custom field object.
131 * This function is invoked from within the web form layer and also from the api layer
133 * @param array $params
134 * (reference) an assoc array of name/value pairs.
136 * @return CRM_Core_DAO_CustomField
138 public static function create($params) {
139 $customField = self
::createCustomFieldRecord($params);
140 $op = empty($params['id']) ?
'add' : 'modify';
141 self
::createField($customField, $op);
143 CRM_Utils_Hook
::post(($op === 'add' ?
'create' : 'edit'), 'CustomField', $customField->id
, $customField);
145 CRM_Utils_System
::flushCache();
146 // Flush caches is not aggressive about clearing the specific cache we know we want to clear
147 // so do it manually. Ideally we wouldn't need to clear others...
148 Civi
::cache('metadata')->clear();
154 * Create/ update several fields at once in a mysql efficient way.
156 * https://lab.civicrm.org/dev/core/issues/1093
158 * The intention is that apiv4 would expose any BAO with bulkSave as a new action.
160 * @param array $bulkParams
161 * Array of arrays as would be passed into create
162 * @param array $defaults
163 * Default parameters to be be merged into each of the params.
165 * @throws \CiviCRM_API3_Exception
167 public static function bulkSave($bulkParams, $defaults = []) {
168 $addedColumns = $sql = $tables = $customFields = [];
169 foreach ($bulkParams as $index => $fieldParams) {
170 $params = array_merge($defaults, $fieldParams);
171 $customField = self
::createCustomFieldRecord($params);
172 $fieldSQL = self
::getAlterFieldSQL($customField, empty($params['id']) ?
'add' : 'modify');
173 if (!isset($params['custom_group_id'])) {
174 $params['custom_group_id'] = civicrm_api3('CustomField', 'getvalue', ['id' => $customField->id
, 'return' => 'custom_group_id']);
176 if (!isset($params['table_name'])) {
177 if (!isset($tables[$params['custom_group_id']])) {
178 $tables[$params['custom_group_id']] = civicrm_api3('CustomGroup', 'getvalue', [
179 'id' => $params['custom_group_id'],
180 'return' => 'table_name',
183 $params['table_name'] = $tables[$params['custom_group_id']];
185 $sql[$params['table_name']][] = $fieldSQL;
186 $addedColumns[$params['table_name']][] = $customField->name
;
187 $customFields[$index] = $customField;
190 foreach ($sql as $tableName => $statements) {
191 // CRM-7007: do not i18n-rewrite this query
192 CRM_Core_DAO
::executeQuery("ALTER TABLE $tableName " . implode(', ', $statements), [], TRUE, NULL, FALSE, FALSE);
194 if (CRM_Core_Config
::singleton()->logging
) {
195 $logging = new CRM_Logging_Schema();
196 $logging->fixSchemaDifferencesFor($tableName, ['ADD' => $addedColumns[$tableName]]);
199 Civi
::service('sql_triggers')->rebuild($params['table_name'], TRUE);
201 CRM_Utils_System
::flushCache();
202 foreach ($customFields as $index => $customField) {
203 CRM_Utils_Hook
::post(empty($bulkParams[$index]['id']) ?
'create' : 'edit', 'CustomField', $customField->id
, $customField);
208 * Fetch object based on array of properties.
210 * @param array $params
211 * (reference ) an assoc array of name/value pairs.
212 * @param array $defaults
213 * (reference ) an assoc array to hold the flattened values.
215 * @return CRM_Core_DAO_CustomField
217 public static function retrieve(&$params, &$defaults) {
218 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
222 * Update the is_active flag in the db.
225 * Id of the database record.
226 * @param bool $is_active
227 * Value we want to set the is_active field.
230 * true if we found and updated the object, else false
232 public static function setIsActive($id, $is_active) {
234 CRM_Utils_System
::flushCache();
236 //enable-disable CustomField
237 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
238 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
242 * Get the field title.
250 public static function getTitle($id) {
251 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
255 * @param string $context
258 public function getOptions($context = NULL) {
259 CRM_Core_DAO
::buildOptionsContext($context);
264 $cacheKey = "CRM_Core_BAO_CustomField_getOptions_{$this->id}_$context";
265 $cache = CRM_Utils_Cache
::singleton();
266 $options = $cache->get($cacheKey);
267 if (!isset($options)) {
268 if (!$this->data_type ||
!$this->custom_group_id
) {
272 // This will hold the list of options in format key => label
275 if (!empty($this->option_group_id
)) {
276 $options = CRM_Core_OptionGroup
::valuesByID(
277 $this->option_group_id
, FALSE, FALSE, FALSE, 'label', !($context == 'validate' ||
$context == 'get')
280 elseif ($this->data_type
=== 'StateProvince') {
281 $options = CRM_Core_PseudoConstant
::stateProvince();
283 elseif ($this->data_type
=== 'Country') {
284 $options = $context == 'validate' ? CRM_Core_PseudoConstant
::countryIsoCode() : CRM_Core_PseudoConstant
::country();
286 elseif ($this->data_type
=== 'Boolean') {
287 $options = $context == 'validate' ?
[0, 1] : CRM_Core_SelectValues
::boolean();
289 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
290 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, ['context' => $context]);
291 $cache->set($cacheKey, $options);
297 * Store and return an array of all active custom fields.
299 * @param string $customDataType
300 * Type of Custom Data; 'ANY' is a synonym for "all contact data types".
301 * @param bool $showAll
302 * If true returns all fields (includes disabled fields).
303 * @param bool $inline
304 * If true returns all inline fields (includes disabled fields).
305 * @param int $customDataSubType
306 * Custom Data sub type value.
307 * @param int $customDataSubName
308 * Custom Data sub name value.
309 * @param bool $onlyParent
310 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
311 * @param bool $onlySubType
312 * Return only custom data for subtype.
313 * @param bool $checkPermission
314 * If false, do not include permissioning clause.
317 * an array of active custom fields.
319 public static function &getFields(
320 $customDataType = 'Individual',
323 $customDataSubType = NULL,
324 $customDataSubName = NULL,
326 $onlySubType = FALSE,
327 $checkPermission = TRUE
329 if (empty($customDataType)) {
330 $customDataType = ['Contact', 'Individual', 'Organization', 'Household'];
332 if ($customDataType === 'ANY') {
333 // NULL should have been respected but the line above broke that.
334 // boo for us not having enough unit tests back them.
335 $customDataType = NULL;
337 if ($customDataType && !is_array($customDataType)) {
339 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
340 // This is the case when getFieldsForImport() requires fields
341 // limited strictly to a subtype.
342 $customDataSubType = $customDataType;
343 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
347 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
348 // this makes the method flexible to support retrieving fields
349 // for multiple extends value.
350 $customDataType = [$customDataType];
354 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
356 if (is_array($customDataType)) {
357 $cacheKey = implode('_', $customDataType);
360 $cacheKey = $customDataType;
363 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
364 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
365 $cacheKey .= $showAll ?
'_1' : '_0';
366 $cacheKey .= $inline ?
'_1_' : '_0_';
367 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
368 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
369 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
370 $cacheKey .= '_' . CRM_Core_Config
::domainID() . '_';
372 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
374 // also get the permission stuff here
375 if ($checkPermission) {
376 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
381 $permissionClause = '(1)';
384 // lets md5 permission clause and take first 8 characters
385 $cacheKey .= substr(md5($permissionClause), 0, 8);
387 if (strlen($cacheKey) > 40) {
388 $cacheKey = md5($cacheKey);
391 if (!self
::$_importFields ||
392 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
394 if (!self
::$_importFields) {
395 self
::$_importFields = [];
398 // check if we can retrieve from database cache
399 $fields = Civi
::Cache('fields')->get("custom importableFields $cacheKey");
401 if ($fields === NULL) {
402 $cfTable = self
::getTableName();
405 if (is_array($customDataType)) {
407 foreach ($customDataType as $dataType) {
408 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
409 if (in_array($dataType, ['Individual', 'Household', 'Organization'])) {
410 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
413 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
415 $value = $value ?
$value . ", {$val}" : $val;
419 $extends = "AND $cgTable.extends IN ( $value ) ";
423 if (!empty($customDataType) && empty($extends)) {
424 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
425 self
::$_importFields[$cacheKey] = [];
426 return self
::$_importFields[$cacheKey];
430 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
433 $query = "SELECT $cfTable.id, $cfTable.label,
437 $cfTable.default_value,
438 $cfTable.options_per_line, $cfTable.text_length,
439 $cfTable.custom_group_id,
440 $cfTable.is_required,
441 $cfTable.column_name,
442 $cgTable.extends, $cfTable.is_search_range,
443 $cgTable.extends_entity_column_value,
444 $cgTable.extends_entity_column_id,
446 $cfTable.option_group_id,
447 $cfTable.date_format,
448 $cfTable.time_format,
449 $cgTable.is_multiple,
451 og.name as option_group_name
454 ON $cfTable.custom_group_id = $cgTable.id
455 LEFT JOIN civicrm_option_group og
456 ON $cfTable.option_group_id = og.id
460 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
464 $query .= " AND $cgTable.style = 'Inline' ";
467 //get the custom fields for specific type in
468 //combination with fields those support any type.
469 if (!empty($customDataSubType)) {
471 foreach ($customDataSubType as $subtype) {
472 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($subtype, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
;
473 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
476 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
478 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
481 if ($customDataSubName) {
482 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
485 // also get the permission stuff here
486 if ($checkPermission) {
487 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
492 $permissionClause = '(1)';
495 $query .= " $extends AND $permissionClause
496 ORDER BY $cgTable.weight, $cgTable.title,
497 $cfTable.weight, $cfTable.label";
499 $dao = CRM_Core_DAO
::executeQuery($query);
502 while (($dao->fetch()) != NULL) {
503 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
504 $fields[$dao->id
]['id'] = $dao->id
;
505 $fields[$dao->id
]['label'] = $dao->label
;
506 // This seems broken, but not in a new way.
507 $fields[$dao->id
]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
508 // To support the consolidation of various functions & their expectations.
509 $fields[$dao->id
]['title'] = $dao->label
;
510 $fields[$dao->id
]['custom_field_id'] = $dao->id
;
511 $fields[$dao->id
]['groupTitle'] = $dao->title
;
512 $fields[$dao->id
]['data_type'] = $dao->data_type
;
513 $fields[$dao->id
]['name'] = 'custom_' . $dao->id
;
514 $fields[$dao->id
]['type'] = CRM_Utils_Array
::value($dao->data_type
, self
::dataToType());
515 $fields[$dao->id
]['html_type'] = $dao->html_type
;
516 $fields[$dao->id
]['default_value'] = $dao->default_value
;
517 $fields[$dao->id
]['text_length'] = $dao->text_length
;
518 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
519 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
520 $fields[$dao->id
]['extends'] = $dao->extends;
521 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
522 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
523 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
524 $fields[$dao->id
]['is_view'] = $dao->is_view
;
525 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
526 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
527 $fields[$dao->id
]['date_format'] = $dao->date_format
;
528 $fields[$dao->id
]['time_format'] = $dao->time_format
;
529 $fields[$dao->id
]['is_required'] = $dao->is_required
;
530 $fields[$dao->id
]['table_name'] = $dao->table_name
;
531 $fields[$dao->id
]['column_name'] = $dao->column_name
;
532 $fields[$dao->id
]['where'] = $dao->table_name
. '.' . $dao->column_name
;
533 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
534 $fields[$dao->id
]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery
::$extendsMap) ? CRM_Core_BAO_CustomQuery
::$extendsMap[$dao->extends] : '';
535 if (in_array($dao->extends, CRM_Contact_BAO_ContactType
::subTypes())) {
536 // if $extends is a subtype, refer contact table
537 $fields[$dao->id
]['extends_table'] = 'civicrm_contact';
539 // Search table is used by query object searches..
540 $fields[$dao->id
]['search_table'] = ($fields[$dao->id
]['extends_table'] == 'civicrm_contact') ?
'contact_a' : $fields[$dao->id
]['extends_table'];
541 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
544 Civi
::cache('fields')->set("custom importableFields $cacheKey", $fields);
546 self
::$_importFields[$cacheKey] = $fields;
549 return self
::$_importFields[$cacheKey];
553 * Return the field ids and names (with groups) for import purpose.
555 * @param int|string $contactType Contact type
556 * @param bool $showAll
557 * If true returns all fields (includes disabled fields).
558 * @param bool $onlyParent
559 * Return fields ONLY related to basic types.
560 * @param bool $search
561 * When called from search and multiple records need to be returned.
562 * @param bool $checkPermission
563 * If false, do not include permissioning clause.
565 * @param bool $withMultiple
569 public static function getFieldsForImport(
570 $contactType = 'Individual',
574 $checkPermission = TRUE,
575 $withMultiple = FALSE
577 // Note: there are situations when we want getFieldsForImport() return fields related
578 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
579 $fields = &self
::getFields($contactType,
589 $importableFields = [];
590 foreach ($fields as $id => $values) {
591 // for now we should not allow multiple fields in profile / export etc, hence unsetting
593 (!empty($values['is_multiple']) && !$withMultiple)
597 if (!empty($values['text_length'])) {
598 $values['maxlength'] = (int) $values['text_length'];
601 /* generate the key for the fields array */
604 $importableFields[$key] = $values;
605 $importableFields[$key]['import'] = 1;
608 return $importableFields;
612 * Get the field id from an import key.
622 public static function getKeyID($key, $all = FALSE) {
624 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
631 CRM_Utils_Array
::value(2, $match),
635 return $all ?
[NULL, NULL] : NULL;
639 * Use the cache to get all values of a specific custom field.
641 * @param int $fieldID
642 * The custom field ID.
644 * @return CRM_Core_BAO_CustomField
647 public static function getFieldObject($fieldID) {
648 $field = new CRM_Core_BAO_CustomField();
650 // check if we can get the field values from the system cache
651 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
652 $cache = CRM_Utils_Cache
::singleton();
653 $fieldValues = $cache->get($cacheKey);
654 if (empty($fieldValues)) {
655 $field->id
= $fieldID;
656 if (!$field->find(TRUE)) {
657 CRM_Core_Error
::fatal();
661 CRM_Core_DAO
::storeValues($field, $fieldValues);
663 $cache->set($cacheKey, $fieldValues);
666 $field->copyValues($fieldValues);
673 * Add a custom field to an existing form.
675 * @param CRM_Core_Form $qf
676 * Form object (reference).
677 * @param string $elementName
678 * Name of the custom field.
679 * @param int $fieldId
680 * @param bool $useRequired
681 * True if required else false.
682 * @param bool $search
683 * True if used for search else false.
684 * @param string $label
685 * Label for custom field.
686 * @return \HTML_QuickForm_Element|null
687 * @throws \CiviCRM_API3_Exception
689 public static function addQuickFormElement(
690 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
692 $field = self
::getFieldObject($fieldId);
693 $widget = $field->html_type
;
695 $customFieldAttributes = [];
697 // Custom field HTML should indicate group+field name
698 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
699 $dataCrmCustomVal = $groupName . ':' . $field->name
;
700 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
701 $field->attributes
.= $dataCrmCustomAttr;
703 // Fixed for Issue CRM-2183
704 if ($widget == 'TextArea' && $search) {
708 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
710 // FIXME: Why are select state/country separate widget types?
711 $isSelect = (in_array($widget, [
714 'Select State/Province',
715 'Multi-Select State/Province',
717 'Multi-Select Country',
723 $options = $field->getOptions($search ?
'search' : 'create');
725 // Consolidate widget types to simplify the below switch statement
726 if ($search ||
(strpos($widget, 'Select') !== FALSE)) {
730 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
731 $selectAttributes = ['class' => 'crm-select2'];
733 // Search field is always multi-select
734 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
735 $selectAttributes['class'] .= ' huge';
736 $selectAttributes['multiple'] = 'multiple';
737 $selectAttributes['placeholder'] = $placeholder;
740 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
741 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
742 if ($field->option_group_id
&& !$search && $isSelect && $canEditOptions) {
743 $customFieldAttributes +
= [
744 'data-api-entity' => $field->getEntity(),
745 'data-api-field' => 'custom_' . $field->id
,
746 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
748 $selectAttributes +
= $customFieldAttributes;
752 $rangeDataTypes = ['Int', 'Float', 'Money'];
754 if (!isset($label)) {
755 $label = $field->label
;
758 // at some point in time we might want to split the below into small functions
763 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
764 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
765 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
768 if ($field->text_length
) {
769 $field->attributes
.= ' maxlength=' . $field->text_length
;
770 if ($field->text_length
< 20) {
771 $field->attributes
.= ' size=' . $field->text_length
;
774 $element = $qf->add('text', $elementName, $label,
776 $useRequired && !$search
782 $attributes = $dataCrmCustomAttr;
783 if ($field->note_rows
) {
784 $attributes .= 'rows=' . $field->note_rows
;
787 $attributes .= 'rows=4';
789 if ($field->note_columns
) {
790 $attributes .= ' cols=' . $field->note_columns
;
793 $attributes .= ' cols=60';
795 if ($field->text_length
) {
796 $attributes .= ' maxlength=' . $field->text_length
;
798 $element = $qf->add('textarea',
802 $useRequired && !$search
807 $attr = ['data-crm-custom' => $dataCrmCustomVal];
808 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
809 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
810 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
813 'date' => $field->date_format
,
814 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
815 //CRM-18487 - max date should be the last date of the year.
816 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
817 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
819 if ($field->is_search_range
&& $search) {
820 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
821 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
824 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
829 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
830 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
831 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
835 parse_str($field->attributes
, $radioAttributes);
836 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
838 foreach ($options as $v => $l) {
839 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
841 $element = $qf->addGroup($choice, $elementName, $label);
842 $optionEditKey = 'data-option-edit-path';
843 if (isset($selectAttributes[$optionEditKey])) {
844 $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
847 if ($useRequired && !$search) {
848 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
851 $element->setAttribute('allowClear', TRUE);
856 // For all select elements
858 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
859 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
860 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
863 if (empty($selectAttributes['multiple'])) {
864 $options = ['' => $placeholder] +
$options;
866 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
868 // Add and/or option for fields that store multiple values
869 if ($search && self
::isSerialized($field)) {
872 $qf->createElement('radio', NULL, '', ts('Any'), 'or', ['title' => ts('Results may contain any of the selected options')]),
873 $qf->createElement('radio', NULL, '', ts('All'), 'and', ['title' => ts('Results must have all of the selected options')]),
875 $qf->addGroup($operators, $elementName . '_operator');
876 $qf->setDefaults([$elementName . '_operator' => 'or']);
883 foreach ($options as $v => $l) {
884 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
887 $group = $element = $qf->addGroup($check, $elementName, $label);
888 $optionEditKey = 'data-option-edit-path';
889 if (isset($customFieldAttributes[$optionEditKey])) {
890 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
893 if ($useRequired && !$search) {
894 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
899 // we should not build upload file in search mode
904 strtolower($field->html_type
),
908 $useRequired && !$search
910 $qf->addUploadElement($elementName);
913 case 'RichTextEditor':
915 'rows' => $field->note_rows
,
916 'cols' => $field->note_columns
,
917 'data-crm-custom' => $dataCrmCustomVal,
919 if ($field->text_length
) {
920 $attributes['maxlength'] = $field->text_length
;
922 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
925 case 'Autocomplete-Select':
926 static $customUrls = [];
927 // Fixme: why is this a string in the first place??
928 $attributes = array();
929 if ($field->attributes
) {
930 foreach (explode(' ', $field->attributes
) as $at) {
931 if (strpos($at, '=')) {
932 list($k, $v) = explode('=', $at);
933 $attributes[$k] = trim($v, ' "');
937 if ($field->data_type
== 'ContactReference') {
938 // break if contact does not have permission to access ContactReference
939 if (!CRM_Core_Permission
::check('access contact reference fields')) {
942 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
943 $attributes['data-api-entity'] = 'Contact';
944 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
946 $urlParams = "context=customfield&id={$field->id}";
947 $idOfelement = $elementName;
948 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
949 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
950 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
951 // rather than layering on more hacks.
952 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
953 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') +
1)), 0, -1);
955 $customUrls[$idOfelement] = CRM_Utils_System
::url('civicrm/ajax/contactref',
962 // FIXME: This won't work with customFieldOptions hook
964 'entity' => 'OptionValue',
965 'placeholder' => $placeholder,
966 'multiple' => $search,
968 'params' => ['option_group_id' => $field->option_group_id
, 'is_active' => 1],
971 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
974 $qf->assign('customUrls', $customUrls);
978 switch ($field->data_type
) {
980 // integers will have numeric rule applied to them.
981 if ($field->is_search_range
&& $search) {
982 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', [1 => $label]), 'integer');
983 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', [1 => $label]), 'integer');
985 elseif ($widget == 'Text') {
986 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', [1 => $label]), 'integer');
991 if ($field->is_search_range
&& $search) {
992 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', [1 => $label]), 'numeric');
993 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', [1 => $label]), 'numeric');
995 elseif ($widget == 'Text') {
996 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', [1 => $label]), 'numeric');
1001 if ($field->is_search_range
&& $search) {
1002 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
1003 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
1005 elseif ($widget == 'Text') {
1006 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', [1 => $label]), 'money');
1011 $element->setAttribute('class', "url");
1012 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1015 if ($field->is_view
&& !$search) {
1016 $qf->freeze($elementName);
1022 * Delete the Custom Field.
1024 * @param object $field
1027 public static function deleteField($field) {
1028 CRM_Utils_System
::flushCache();
1030 // first delete the custom option group and values associated with this field
1031 if ($field->option_group_id
) {
1032 //check if option group is related to any other field, if
1033 //not delete the option group and related option values
1034 self
::checkOptionGroup($field->option_group_id
);
1037 // next drop the column from the custom value table
1038 self
::createField($field, 'delete');
1041 CRM_Core_BAO_UFField
::delUFField($field->id
);
1042 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1044 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
1048 * @param string|int|array|null $value
1049 * @param CRM_Core_BAO_CustomField|int|array|string $field
1050 * @param int $entityId
1054 * @throws \CRM_Core_Exception
1056 public static function displayValue($value, $field, $entityId = NULL) {
1057 $field = is_array($field) ?
$field['id'] : $field;
1058 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1061 throw new CRM_Core_Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1064 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1065 $field = self
::getFieldObject($fieldId);
1068 $fieldInfo = ['options' => $field->getOptions()] +
(array) $field;
1070 $displayValue = self
::formatDisplayValue($value, $fieldInfo, $entityId);
1072 // Call hook to alter display value.
1073 CRM_Utils_Hook
::alterCustomFieldDisplayValue($displayValue, $value, $entityId, $fieldInfo);
1075 return $displayValue;
1079 * Lower-level logic for rendering a custom field value
1081 * @param string|array $value
1082 * @param array $field
1083 * @param int|null $entityId
1087 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1089 if (self
::isSerialized($field) && !is_array($value)) {
1090 $value = CRM_Utils_Array
::explodePadded($value);
1093 if ($field['html_type'] == 'CheckBox' && $value) {
1094 $value = CRM_Utils_Array
::convertCheckboxFormatToArray($value);
1097 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1099 switch ($field['html_type']) {
1102 case 'Autocomplete-Select':
1104 case 'Select Country':
1105 case 'Select State/Province':
1107 case 'Multi-Select':
1108 case 'Multi-Select State/Province':
1109 case 'Multi-Select Country':
1110 if ($field['data_type'] == 'ContactReference' && $value) {
1111 if (is_numeric($value)) {
1112 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1118 elseif (is_array($value)) {
1120 foreach ($value as $key => $val) {
1121 $v[] = $field['options'][$val] ??
NULL;
1123 $display = implode(', ', $v);
1126 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1131 $customFormat = NULL;
1133 // FIXME: Are there any legitimate reasons why $value would be an array?
1134 // Or should we throw an exception here if it is?
1135 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1137 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1138 $format = $field['date_format'] ??
NULL;
1141 if (array_key_exists($format, $actualPHPFormats)) {
1142 $customTimeFormat = (array) $actualPHPFormats[$format];
1143 switch (CRM_Utils_Array
::value('time_format', $field)) {
1145 $customTimeFormat[] = 'g:iA';
1149 $customTimeFormat[] = 'G:i';
1153 //If time is not selected remove time from value.
1154 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1156 $customFormat = implode(" ", $customTimeFormat);
1159 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1163 // In the context of displaying a profile, show file/image
1166 if (CRM_Utils_Rule
::positiveInteger($value)) {
1170 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1172 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1174 $display = $url['file_url'];
1178 // In other contexts show a paperclip icon
1179 if (CRM_Utils_Rule
::integer($value)) {
1180 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1182 $file_description = '';
1184 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1186 catch (CiviCRM_API3_Exception
$dontcare) {
1190 $display = "{$icons[$value]}{$file_description}";
1193 //CRM-18396, if filename is passed instead
1201 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1205 $display = nl2br($display);
1209 if ($field['data_type'] == 'Money' && isset($value)) {
1210 // $value can also be an array(while using IN operator from search builder or api).
1211 foreach ((array) $value as $val) {
1212 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1214 $display = implode(', ', $disp);
1222 * Set default values for custom data used in profile.
1224 * @param int $customFieldId
1226 * @param string $elementName
1227 * Custom field name.
1228 * @param array $defaults
1229 * Associated array of fields.
1230 * @param int $contactId
1234 * @param mixed $value
1235 * If passed - dont fetch value from db,.
1236 * just format the given value
1238 public static function setProfileDefaults(
1246 //get the type of custom field
1247 $customField = new CRM_Core_BAO_CustomField();
1248 $customField->id
= $customFieldId;
1249 $customField->find(TRUE);
1252 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1253 $value = $customField->default_value
;
1257 if (!isset($value)) {
1258 $info = self
::getTableColumnGroup($customFieldId);
1259 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1260 $result = CRM_Core_DAO
::executeQuery($query);
1261 if ($result->fetch()) {
1262 $value = $result->value
;
1266 if ($customField->data_type
== 'Country') {
1268 $config = CRM_Core_Config
::singleton();
1269 if ($config->defaultContactCountry
) {
1270 $value = CRM_Core_BAO_Country
::defaultContactCountry();
1276 //set defaults if mode is registration
1277 if (!trim($value) &&
1279 (!in_array($mode, [CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
]))
1281 $value = $customField->default_value
;
1284 if ($customField->data_type
== 'Money' && isset($value)) {
1285 $value = number_format($value, 2);
1287 switch ($customField->html_type
) {
1289 case 'Multi-Select':
1290 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1291 $defaults[$elementName] = [];
1292 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1293 substr($value, 1, -1)
1295 foreach ($customOption as $val) {
1296 if (in_array($val['value'], $checkedValue)) {
1297 if ($customField->html_type
== 'CheckBox') {
1298 $defaults[$elementName][$val['value']] = 1;
1300 elseif ($customField->html_type
== 'Multi-Select') {
1301 $defaults[$elementName][$val['value']] = $val['value'];
1308 $defaults[$elementName] = $value;
1315 * @param int $contactID
1317 * @param int $fileID
1318 * @param bool $absolute
1320 * @param string $multiRecordWhereClause
1324 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1327 $params = ['id' => $cfID];
1329 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1330 $columnName = $defaults['column_name'];
1332 //table name of custom data
1333 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1334 $defaults['custom_group_id'],
1338 //query to fetch id from civicrm_file
1339 if ($multiRecordWhereClause) {
1340 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1343 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1345 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1350 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1355 $result['file_id'] = $fileID;
1357 if ($fileType == 'image/jpeg' ||
1358 $fileType == 'image/pjpeg' ||
1359 $fileType == 'image/gif' ||
1360 $fileType == 'image/x-png' ||
1361 $fileType == 'image/png'
1363 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1368 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1369 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1370 $url = CRM_Utils_System
::url('civicrm/file',
1371 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1372 $absolute, NULL, TRUE, TRUE
1374 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1376 // for non image files
1378 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1382 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1383 $url = CRM_Utils_System
::url('civicrm/file',
1384 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1385 $absolute, NULL, TRUE, TRUE
1387 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1395 * Format custom fields before inserting.
1397 * @param int $customFieldId
1399 * @param array $customFormatted
1401 * @param mixed $value
1402 * Value of custom field.
1403 * @param string $customFieldExtend
1404 * Custom field extends.
1405 * @param int $customValueId
1406 * Custom option value id.
1407 * @param int $entityId
1408 * Entity id (contribution, membership...).
1409 * @param bool $inline
1410 * Consider inline custom groups only.
1411 * @param bool $checkPermission
1412 * If false, do not include permissioning clause.
1413 * @param bool $includeViewOnly
1414 * If true, fields marked 'View Only' are included. Required for APIv3.
1416 * @return array|NULL
1417 * formatted custom field array
1419 public static function formatCustomField(
1420 $customFieldId, &$customFormatted, $value,
1421 $customFieldExtend, $customValueId = NULL,
1424 $checkPermission = TRUE,
1425 $includeViewOnly = FALSE
1427 //get the custom fields for the entity
1428 //subtype and basic type
1429 $customDataSubType = NULL;
1430 if ($customFieldExtend) {
1431 // This is the case when getFieldsForImport() requires fields
1432 // of subtype and its parent.CRM-5143
1433 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1434 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1435 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1436 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1437 if (is_array($customFieldExtend)) {
1438 $customFieldExtend = array_unique(array_values($customFieldExtend));
1443 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1453 if (!array_key_exists($customFieldId, $customFields)) {
1457 // return if field is a 'code' field
1458 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1462 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1464 if (!$customValueId &&
1465 // we always create new entites for is_multiple unless specified
1466 !$customFields[$customFieldId]['is_multiple'] &&
1472 WHERE entity_id={$entityId}";
1474 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1477 //fix checkbox, now check box always submits values
1478 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1480 // Note that only during merge this is not an array, and you can directly use value
1481 if (is_array($value)) {
1482 $selectedValues = [];
1483 foreach ($value as $selId => $val) {
1485 $selectedValues[] = $selId;
1488 if (!empty($selectedValues)) {
1489 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1491 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1500 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select') {
1502 $value = CRM_Utils_Array
::implodePadded($value);
1509 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1510 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1512 $customFields[$customFieldId]['data_type'] == 'String' &&
1513 !empty($customFields[$customFieldId]['text_length']) &&
1516 // lets make sure that value is less than the length, else we'll
1517 // be losing some data, CRM-7481
1518 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1519 // need to do a few things here
1521 // 1. lets find a new length
1522 $newLength = $customFields[$customFieldId]['text_length'];
1523 $minLength = strlen($value);
1524 while ($newLength < $minLength) {
1525 $newLength = $newLength * 2;
1528 // set the custom field meta data to have a length larger than value
1529 // alter the custom value table column to match this length
1530 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1535 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1536 if (!CRM_Utils_System
::isNull($value)) {
1537 $format = $customFields[$customFieldId]['date_format'];
1538 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1543 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1544 $customFields[$customFieldId]['data_type'] == 'Money'
1550 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1551 $value = CRM_Utils_Rule
::cleanMoney($value);
1555 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1556 $customFields[$customFieldId]['data_type'] == 'Country'
1566 if ($customFields[$customFieldId]['data_type'] == 'File') {
1567 if (empty($value)) {
1571 $config = CRM_Core_Config
::singleton();
1573 // If we are already passing the file id as a value then retrieve and set the file data
1574 if (CRM_Utils_Rule
::integer($value)) {
1575 $fileDAO = new CRM_Core_DAO_File();
1576 $fileDAO->id
= $value;
1577 $fileDAO->find(TRUE);
1580 $fName = $fileDAO->uri
;
1581 $mimeType = $fileDAO->mime_type
;
1585 $fName = $value['name'];
1586 $mimeType = $value['type'];
1589 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1591 // rename this file to go into the secure directory only if
1592 // user has uploaded new file not existing verfied on the basis of $fileID
1593 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1594 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1597 if ($customValueId && empty($fileID)) {
1602 $params = [1 => [$customValueId, 'Integer']];
1603 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1606 $fileDAO = new CRM_Core_DAO_File();
1609 $fileDAO->id
= $fileID;
1612 $fileDAO->uri
= $filename;
1613 $fileDAO->mime_type
= $mimeType;
1614 $fileDAO->upload_date
= date('YmdHis');
1616 $fileID = $fileDAO->id
;
1620 if (!is_array($customFormatted)) {
1621 $customFormatted = [];
1624 if (!array_key_exists($customFieldId, $customFormatted)) {
1625 $customFormatted[$customFieldId] = [];
1629 if ($customValueId) {
1630 $index = $customValueId;
1633 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1634 $customFormatted[$customFieldId][$index] = [];
1636 $customFormatted[$customFieldId][$index] = [
1637 'id' => $customValueId > 0 ?
$customValueId : NULL,
1639 'type' => $customFields[$customFieldId]['data_type'],
1640 'custom_field_id' => $customFieldId,
1641 'custom_group_id' => $groupID,
1642 'table_name' => $tableName,
1643 'column_name' => $columnName,
1644 'file_id' => $fileID,
1645 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1648 //we need to sort so that custom fields are created in the order of entry
1649 krsort($customFormatted[$customFieldId]);
1650 return $customFormatted;
1654 * Get default custom table schema.
1656 * @param array $params
1660 public static function defaultCustomTableSchema($params) {
1661 // add the id and extends_id
1663 'name' => $params['name'],
1664 'is_multiple' => $params['is_multiple'],
1665 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1669 'type' => 'int unsigned',
1672 'attributes' => 'AUTO_INCREMENT',
1673 'comment' => 'Default MySQL primary key',
1676 'name' => 'entity_id',
1677 'type' => 'int unsigned',
1679 'comment' => 'Table that this extends',
1680 'fk_table_name' => $params['extends_name'],
1681 'fk_field_name' => 'id',
1682 'fk_attributes' => 'ON DELETE CASCADE',
1687 if (!$params['is_multiple']) {
1688 $table['indexes'] = [
1691 'field_name_1' => 'entity_id',
1699 * Create custom field.
1701 * @param CRM_Core_DAO_CustomField $field
1702 * @param string $operation
1704 public static function createField($field, $operation) {
1705 $sql = str_repeat(' ', 8);
1706 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1707 $sql .= "ALTER TABLE " . $tableName;
1708 $sql .= self
::getAlterFieldSQL($field, $operation);
1710 // CRM-7007: do not i18n-rewrite this query
1711 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1713 $config = CRM_Core_Config
::singleton();
1714 if ($config->logging
) {
1715 // CRM-16717 not sure why this was originally limited to add.
1716 // For example custom tables can have field length changes - which need to flow through to logging.
1717 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1718 if ($operation === 'add' ||
$operation === 'modify') {
1719 $logging = new CRM_Logging_Schema();
1720 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name
]]);
1724 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
1728 * @param CRM_Core_DAO_CustomField $field
1729 * @param string $operation
1733 public static function getAlterFieldSQL($field, $operation) {
1734 $indexExist = $operation === 'add' ?
FALSE : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $field->id
, 'is_searchable');
1735 $params = self
::prepareCreateParams($field, $operation);
1736 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1737 // a function only used by Custom Field creation...
1738 $params['required'] = FALSE;
1739 return CRM_Core_BAO_SchemaHandler
::getFieldAlterSQL($params, $indexExist);
1743 * Determine whether it would be safe to move a field.
1745 * @param int $fieldID
1746 * FK to civicrm_custom_field.
1747 * @param int $newGroupID
1748 * FK to civicrm_custom_group.
1751 * array(string) or TRUE
1753 public static function _moveFieldValidate($fieldID, $newGroupID) {
1756 $field = new CRM_Core_DAO_CustomField();
1757 $field->id
= $fieldID;
1758 if (!$field->find(TRUE)) {
1759 $errors['fieldID'] = 'Invalid ID for custom field';
1763 $oldGroup = new CRM_Core_DAO_CustomGroup();
1764 $oldGroup->id
= $field->custom_group_id
;
1765 if (!$oldGroup->find(TRUE)) {
1766 $errors['fieldID'] = 'Invalid ID for old custom group';
1770 $newGroup = new CRM_Core_DAO_CustomGroup();
1771 $newGroup->id
= $newGroupID;
1772 if (!$newGroup->find(TRUE)) {
1773 $errors['newGroupID'] = 'Invalid ID for new custom group';
1779 FROM civicrm_custom_field a
1780 INNER JOIN civicrm_custom_field b
1782 AND a.label = b.label
1783 AND b.custom_group_id = %2
1786 1 => [$field->id
, 'Integer'],
1787 2 => [$newGroup->id
, 'Integer'],
1789 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1791 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1794 $tableName = $oldGroup->table_name
;
1795 $columnName = $field->column_name
;
1800 WHERE $columnName is not null
1802 $count = CRM_Core_DAO
::singleValueQuery($query);
1806 FROM civicrm_custom_group
1807 WHERE id IN ( %1, %2 )
1810 1 => [$oldGroup->id
, 'Integer'],
1811 2 => [$newGroup->id
, 'Integer'],
1814 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1816 while ($dao->fetch()) {
1817 $extends[] = $dao->extends;
1819 if ($extends[0] != $extends[1]) {
1820 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1824 return empty($errors) ?
TRUE : $errors;
1828 * Move a custom data field from one group (table) to another.
1830 * @param int $fieldID
1831 * FK to civicrm_custom_field.
1832 * @param int $newGroupID
1833 * FK to civicrm_custom_group.
1835 public static function moveField($fieldID, $newGroupID) {
1836 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1837 if (TRUE !== $validation) {
1838 CRM_Core_Error
::fatal(implode(' ', $validation));
1840 $field = new CRM_Core_DAO_CustomField();
1841 $field->id
= $fieldID;
1844 $newGroup = new CRM_Core_DAO_CustomGroup();
1845 $newGroup->id
= $newGroupID;
1846 $newGroup->find(TRUE);
1848 $oldGroup = new CRM_Core_DAO_CustomGroup();
1849 $oldGroup->id
= $field->custom_group_id
;
1850 $oldGroup->find(TRUE);
1853 $add->custom_group_id
= $newGroup->id
;
1854 self
::createField($add, 'add');
1856 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1857 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1858 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1860 CRM_Core_DAO
::executeQuery($sql);
1863 $del->custom_group_id
= $oldGroup->id
;
1864 self
::createField($del, 'delete');
1868 CRM_Utils_System
::flushCache();
1872 * Create an option value for a custom field option group ID.
1874 * @param array $params
1875 * @param string $value
1876 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1877 * @param string $optionName
1878 * @param string $dataType
1880 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $optionName, $dataType) {
1881 if (strlen(trim($value))) {
1882 $optionValue = new CRM_Core_DAO_OptionValue();
1883 $optionValue->option_group_id
= $optionGroup->id
;
1884 $optionValue->label
= $params['option_label'][$optionName];
1885 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$optionName]);
1886 switch ($dataType) {
1888 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1892 $optionValue->value
= intval($value);
1896 $optionValue->value
= floatval($value);
1900 $optionValue->value
= trim($value);
1903 $optionValue->weight
= $params['option_weight'][$optionName];
1904 $optionValue->is_active
= CRM_Utils_Array
::value($optionName, $params['option_status'], FALSE);
1905 $optionValue->save();
1910 * Prepare for the create operation.
1912 * Munge params, create the option values if needed.
1914 * This could be called by a single create or a batchCreate.
1916 * @param array $params
1920 protected static function prepareCreate($params) {
1921 $op = empty($params['id']) ?
'create' : 'edit';
1922 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1923 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1924 if ($op === 'create') {
1925 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1926 if (!isset($params['column_name'])) {
1927 // if add mode & column_name not present, calculate it.
1928 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1930 if (!isset($params['name'])) {
1931 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1935 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1941 switch (CRM_Utils_Array
::value('html_type', $params)) {
1943 if (empty($params['date_format'])) {
1944 $config = CRM_Core_Config
::singleton();
1945 $params['date_format'] = $config->dateInputFormat
;
1950 case 'Multi-Select':
1951 if (isset($params['default_checkbox_option'])) {
1952 $tempArray = array_keys($params['default_checkbox_option']);
1954 foreach ($tempArray as $k => $v) {
1955 if ($params['option_value'][$v]) {
1956 $defaultArray[] = $params['option_value'][$v];
1960 if (!empty($defaultArray)) {
1961 // also add the separator before and after the value per new convention (CRM-1604)
1962 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1966 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
1968 $params['default_value'] = $params['option_value'][$params['default_option']];
1974 $htmlType = $params['html_type'] ??
NULL;
1975 $dataType = $params['data_type'] ??
NULL;
1976 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1978 // create any option group & values if required
1979 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)
1981 //CRM-16659: if option_value then create an option group for this custom field.
1982 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
1983 // first create an option group for this custom group
1984 $optionGroup = new CRM_Core_DAO_OptionGroup();
1985 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
1986 $optionGroup->title
= $params['label'];
1987 $optionGroup->is_active
= 1;
1988 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1989 $optionGroup->is_reserved
= 0;
1990 $optionGroup->data_type
= $dataType;
1991 $optionGroup->save();
1992 $params['option_group_id'] = $optionGroup->id
;
1993 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1994 foreach ($params['option_value'] as $k => $v) {
1995 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
2001 // check for orphan option groups
2002 if (!empty($params['option_group_id'])) {
2003 if (!empty($params['id'])) {
2004 self
::fixOptionGroups($params['id'], $params['option_group_id']);
2007 // if we do not have a default value
2008 // retrieve it from one of the other custom fields which use this option group
2009 if (empty($params['default_value'])) {
2010 //don't insert only value separator as default value, CRM-4579
2011 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
2015 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2019 $params['default_value'] = $defaultValue;
2024 // since we need to save option group id :)
2025 if (!isset($params['attributes']) && strtolower($htmlType) == 'textarea') {
2026 $params['attributes'] = 'rows=4, cols=60';
2032 * Create database entry for custom field and related option groups.
2034 * @param array $params
2036 * @return CRM_Core_DAO_CustomField
2038 protected static function createCustomFieldRecord($params) {
2039 $transaction = new CRM_Core_Transaction();
2040 $params = self
::prepareCreate($params);
2042 $customField = new CRM_Core_DAO_CustomField();
2043 $customField->copyValues($params);
2044 $customField->save();
2046 //create/drop the index when we toggle the is_searchable flag
2047 $op = empty($params['id']) ?
'add' : 'modify';
2048 if ($op !== 'modify') {
2049 if ($params['is_append_field_id_to_column_name']) {
2050 $params['column_name'] .= "_{$customField->id}";
2052 $customField->column_name
= $params['column_name'];
2053 $customField->save();
2056 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
2057 $transaction->commit();
2059 // make sure all values are present in the object for further processing
2060 $customField->find(TRUE);
2061 return $customField;
2065 * Move custom data from one contact to another.
2067 * This is currently the start of a refactoring. The theory is each
2068 * entity could have a 'move' function with a DAO default one to fall back on.
2070 * At the moment this only does a small part of the process - ie deleting a file field that
2071 * is about to be overwritten. However, the goal is the whole process around the move for
2072 * custom data should be in here.
2074 * This is currently called by the merge class but it makes sense that api could
2075 * expose move actions as moving (e.g) contributions feels like a common
2076 * ask that should be handled by the form layer.
2078 * @param int $oldContactID
2079 * @param int $newContactID
2080 * @param int[] $fieldIDs
2081 * Optional list field ids to move.
2083 * @throws \CiviCRM_API3_Exception
2084 * @throws \Exception
2086 public function move($oldContactID, $newContactID, $fieldIDs) {
2087 if (empty($fieldIDs)) {
2090 $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'];
2092 foreach ($fieldIDs as $fieldID) {
2093 $return[] = 'custom_' . $fieldID;
2095 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2096 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2098 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2099 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2100 $fieldTypesNotHandledInMergeAttempt = ['File'];
2101 foreach ($fields as $field) {
2102 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2103 if ($field['data_type'] === 'File' && !$isMultiple) {
2104 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2105 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2107 if (!empty($oldContact['custom_' . $field['id']])) {
2108 CRM_Core_DAO
::executeQuery("
2109 UPDATE civicrm_entity_file
2110 SET entity_id = $newContactID
2111 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2115 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2116 CRM_Core_DAO
::executeQuery(
2117 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2118 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2119 ON DUPLICATE KEY UPDATE
2120 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2127 * Get the database table name and column name for a custom field.
2129 * @param int $fieldID
2130 * The fieldID of the custom field.
2131 * @param bool $force
2132 * Force the sql to be run again (primarily used for tests).
2135 * fatal is fieldID does not exists, else array of tableName, columnName
2136 * @throws \Exception
2138 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2139 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2140 $cache = CRM_Utils_Cache
::singleton();
2141 $fieldValues = $cache->get($cacheKey);
2142 if (empty($fieldValues) ||
$force) {
2144 SELECT cg.table_name, cf.column_name, cg.id
2145 FROM civicrm_custom_group cg,
2146 civicrm_custom_field cf
2147 WHERE cf.custom_group_id = cg.id
2149 $params = [1 => [$fieldID, 'Integer']];
2150 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2152 if (!$dao->fetch()) {
2153 CRM_Core_Error
::fatal();
2155 $fieldValues = [$dao->table_name
, $dao->column_name
, $dao->id
];
2156 $cache->set($cacheKey, $fieldValues);
2158 return $fieldValues;
2162 * Get custom option groups.
2164 * @deprecated Use the API OptionGroup.get
2166 * @param array $includeFieldIds
2167 * Ids of custom fields for which option groups must be included.
2169 * Currently this is required in the cases where option groups are to be included
2170 * for inactive fields : CRM-5369
2174 public static function customOptionGroup($includeFieldIds = NULL) {
2175 static $customOptionGroup = NULL;
2177 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2178 if ($cacheKey == 'force') {
2179 $customOptionGroup[$cacheKey] = NULL;
2182 if (empty($customOptionGroup[$cacheKey])) {
2183 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2185 //support for single as well as array format.
2186 if (!empty($includeFieldIds)) {
2187 if (is_array($includeFieldIds)) {
2188 $includeFieldIds = implode(',', $includeFieldIds);
2190 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2194 SELECT g.id, g.title
2195 FROM civicrm_option_group g
2196 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2197 WHERE {$whereClause}";
2199 $dao = CRM_Core_DAO
::executeQuery($query);
2200 while ($dao->fetch()) {
2201 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2205 return $customOptionGroup[$cacheKey];
2209 * Get defaults for new entity.
2213 public static function getDefaults() {
2215 'is_required' => FALSE,
2216 'is_searchable' => FALSE,
2217 'in_selector' => FALSE,
2218 'is_search_range' => FALSE,
2219 //CRM-15792 - Custom field gets disabled if is_active not set
2220 // this would ideally be a mysql default.
2221 'is_active' => TRUE,
2227 * Fix orphan groups.
2229 * @param int $customFieldId
2231 * @param int $optionGroupId
2234 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2235 // check if option group belongs to any custom Field else delete
2236 // get the current option group
2237 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2241 // get the updated option group
2242 // if both are same return
2243 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2247 // check if option group is related to any other field
2248 self
::checkOptionGroup($currentOptionGroupId);
2252 * Check if option group is related to more than one custom field.
2254 * @param int $optionGroupId
2257 public static function checkOptionGroup($optionGroupId) {
2260 FROM civicrm_custom_field
2261 WHERE option_group_id = {$optionGroupId}";
2263 $count = CRM_Core_DAO
::singleValueQuery($query);
2266 //delete the option group
2267 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2272 * Get option group default.
2274 * @param int $optionGroupId
2275 * @param string $htmlType
2277 * @return null|string
2279 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2281 SELECT default_value, html_type
2282 FROM civicrm_custom_field
2283 WHERE option_group_id = {$optionGroupId}
2284 AND default_value IS NOT NULL
2285 ORDER BY html_type";
2287 $dao = CRM_Core_DAO
::executeQuery($query);
2288 $defaultValue = NULL;
2289 $defaultHTMLType = NULL;
2290 while ($dao->fetch()) {
2291 if ($dao->html_type
== $htmlType) {
2292 return $dao->default_value
;
2294 if ($defaultValue == NULL) {
2295 $defaultValue = $dao->default_value
;
2296 $defaultHTMLType = $dao->html_type
;
2300 // some conversions are needed if either the old or new has a html type which has potential
2301 // multiple default values.
2302 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2303 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2305 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2307 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2308 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2310 $defaultValue = substr($defaultValue, 1, -1);
2311 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2312 substr($defaultValue, 1, -1)
2314 $defaultValue = $values[0];
2317 return $defaultValue;
2321 * Post process function.
2323 * @param array $params
2324 * @param int $entityID
2325 * @param string $customFieldExtends
2326 * @param bool $inline
2327 * @param bool $checkPermissions
2331 public static function postProcess(
2334 $customFieldExtends,
2336 $checkPermissions = TRUE
2340 foreach ($params as $key => $value) {
2341 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2343 // for autocomplete transfer hidden value instead of label
2344 if ($params[$key] && isset($params[$key . '_id'])) {
2345 $value = $params[$key . '_id'];
2348 // we need to append time with date
2349 if ($params[$key] && isset($params[$key . '_time'])) {
2350 $value .= ' ' . $params[$key . '_time'];
2353 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2356 $customFieldExtends,
2357 $customFieldInfo[1],
2368 * Get custom field ID from field/group name/title.
2370 * @param string $fieldName Field name or label
2371 * @param string|null $groupName (Optional) Group name or label
2372 * @param bool $fullString Whether to return "custom_123" or "123"
2374 * @return string|int|null
2375 * @throws \CiviCRM_API3_Exception
2377 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2378 $cacheKey = $groupName . '.' . $fieldName;
2379 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2380 $customFieldParams = [
2381 'name' => $fieldName,
2382 'label' => $fieldName,
2383 'options' => ['or' => [["name", "label"]]],
2387 $customFieldParams['custom_group_id.name'] = $groupName;
2388 $customFieldParams['custom_group_id.title'] = $groupName;
2389 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2392 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2394 if (empty($field['id'])) {
2395 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2396 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2399 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2400 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2405 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2407 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2411 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2417 public static function getNameFromID($ids) {
2418 if (is_array($ids)) {
2419 $ids = implode(',', $ids);
2422 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2423 FROM civicrm_custom_field f
2424 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2425 WHERE f.id IN ($ids)";
2427 $dao = CRM_Core_DAO
::executeQuery($sql);
2429 while ($dao->fetch()) {
2430 $result[$dao->id
] = [
2431 'field_name' => $dao->field_name
,
2432 'field_label' => $dao->field_label
,
2433 'group_name' => $dao->group_name
,
2434 'group_title' => $dao->group_title
,
2441 * Validate custom data.
2443 * @param array $params
2444 * Custom data submitted.
2445 * ie array( 'custom_1' => 'validate me' );
2448 * validation errors.
2450 public static function validateCustomData($params) {
2452 if (!is_array($params) ||
empty($params)) {
2456 //pick up profile fields.
2457 $profileFields = [];
2458 $ufGroupId = $params['ufGroupId'] ??
NULL;
2460 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2462 CRM_Core_Action
::VIEW
2466 //lets start w/ params.
2467 foreach ($params as $key => $value) {
2468 $customFieldID = self
::getKeyID($key);
2469 if (!$customFieldID) {
2473 //load the structural info for given field.
2474 $field = new CRM_Core_DAO_CustomField();
2475 $field->id
= $customFieldID;
2476 if (!$field->find(TRUE)) {
2479 $dataType = $field->data_type
;
2481 $profileField = CRM_Utils_Array
::value($key, $profileFields, []);
2482 $fieldTitle = $profileField['title'] ??
NULL;
2483 $isRequired = $profileField['is_required'] ??
NULL;
2485 $fieldTitle = $field->label
;
2488 //no need to validate.
2489 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2493 //lets validate first for required field.
2494 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2495 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
2499 //now time to take care of custom field form rules.
2500 $ruleName = $errorMsg = NULL;
2501 switch ($dataType) {
2503 $ruleName = 'integer';
2504 $errorMsg = ts('%1 must be an integer (whole number).',
2505 array(1 => $fieldTitle)
2510 $ruleName = 'money';
2511 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2512 array(1 => $fieldTitle)
2517 $ruleName = 'numeric';
2518 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2519 array(1 => $fieldTitle)
2524 $ruleName = 'wikiURL';
2525 $errorMsg = ts('%1 must be valid Website.',
2526 array(1 => $fieldTitle)
2531 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2533 $funName = "CRM_Utils_Rule::{$ruleName}";
2534 if (is_callable($funName)) {
2535 $valid = call_user_func($funName, $value);
2538 $errors[$key] = $errorMsg;
2547 * Is this field a multi record field.
2549 * @param int $customId
2553 public static function isMultiRecordField($customId) {
2554 $isMultipleWithGid = FALSE;
2555 if (!is_numeric($customId)) {
2556 $customId = self
::getKeyID($customId);
2558 if (is_numeric($customId)) {
2559 $sql = "SELECT cg.id cgId
2560 FROM civicrm_custom_group cg
2561 INNER JOIN civicrm_custom_field cf
2562 ON cg.id = cf.custom_group_id
2563 WHERE cf.id = %1 AND cg.is_multiple = 1";
2564 $params[1] = [$customId, 'Integer'];
2565 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2566 if ($dao->fetch()) {
2568 $isMultipleWithGid = $dao->cgId
;
2573 return $isMultipleWithGid;
2577 * Does this field type have any select options?
2579 * @param array $field
2583 public static function hasOptions($field) {
2584 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2585 $field = (array) $field;
2586 // This will include boolean fields with Yes/No options.
2587 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2590 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2591 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2592 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2595 if (strpos($field['html_type'], 'Select') !== FALSE) {
2598 return !empty($field['option_group_id']);
2602 * Does this field store a serialized string?
2604 * @param array|object $field
2608 public static function isSerialized($field) {
2609 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2610 $html_type = is_object($field) ?
$field->html_type
: $field['html_type'];
2611 // FIXME: Currently the only way to know if data is serialized is by looking at the html_type. It would be cleaner to decouple this.
2612 return ($html_type === 'CheckBox' ||
strpos($html_type, 'Multi') !== FALSE);
2616 * Get api entity for this field
2620 public function getEntity() {
2621 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2622 return in_array($entity, ['Individual', 'Household', 'Organization']) ?
'Contact' : $entity;
2626 * Set pseudoconstant properties for field metadata.
2628 * @param array $field
2629 * @param string|null $optionGroupName
2631 private static function getOptionsForField(&$field, $optionGroupName) {
2632 if ($optionGroupName) {
2633 $field['pseudoconstant'] = [
2634 'optionGroupName' => $optionGroupName,
2635 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2638 elseif ($field['data_type'] == 'Boolean') {
2639 $field['pseudoconstant'] = [
2640 'callback' => 'CRM_Core_SelectValues::boolean',
2643 elseif ($field['data_type'] == 'Country') {
2644 $field['pseudoconstant'] = [
2645 'table' => 'civicrm_country',
2646 'keyColumn' => 'id',
2647 'labelColumn' => 'name',
2648 'nameColumn' => 'iso_code',
2651 elseif ($field['data_type'] == 'StateProvince') {
2652 $field['pseudoconstant'] = [
2653 'table' => 'civicrm_state_province',
2654 'keyColumn' => 'id',
2655 'labelColumn' => 'name',
2661 * @param CRM_Core_DAO_CustomField $field
2662 * @param 'add|modify' $operation
2666 protected static function prepareCreateParams($field, $operation) {
2667 $tableName = CRM_Core_DAO
::getFieldValue(
2668 'CRM_Core_DAO_CustomGroup',
2669 $field->custom_group_id
,
2674 'table_name' => $tableName,
2675 'operation' => $operation,
2676 'name' => $field->column_name
,
2677 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2681 'required' => $field->is_required
,
2682 'searchable' => $field->is_searchable
,
2685 if ($operation == 'delete') {
2686 $fkName = "{$tableName}_{$field->column_name}";
2687 if (strlen($fkName) >= 48) {
2688 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2690 $params['fkName'] = $fkName;
2692 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
2693 $params['fk_table_name'] = 'civicrm_country';
2694 $params['fk_field_name'] = 'id';
2695 $params['fk_attributes'] = 'ON DELETE SET NULL';
2697 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
2698 $params['type'] = 'varchar(255)';
2700 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
2701 $params['fk_table_name'] = 'civicrm_state_province';
2702 $params['fk_field_name'] = 'id';
2703 $params['fk_attributes'] = 'ON DELETE SET NULL';
2705 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
2706 $params['type'] = 'varchar(255)';
2708 elseif ($field->data_type
== 'File') {
2709 $params['fk_table_name'] = 'civicrm_file';
2710 $params['fk_field_name'] = 'id';
2711 $params['fk_attributes'] = 'ON DELETE SET NULL';
2713 elseif ($field->data_type
== 'ContactReference') {
2714 $params['fk_table_name'] = 'civicrm_contact';
2715 $params['fk_field_name'] = 'id';
2716 $params['fk_attributes'] = 'ON DELETE SET NULL';
2718 if (isset($field->default_value
)) {
2719 $params['default'] = "'{$field->default_value}'";