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 return self
::formatDisplayValue($value, $fieldInfo, $entityId);
1074 * Lower-level logic for rendering a custom field value
1076 * @param string|array $value
1077 * @param array $field
1078 * @param int|null $entityId
1082 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1084 if (self
::isSerialized($field) && !is_array($value)) {
1085 $value = CRM_Utils_Array
::explodePadded($value);
1088 if ($field['html_type'] == 'CheckBox' && $value) {
1089 $value = CRM_Utils_Array
::convertCheckboxFormatToArray($value);
1092 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1094 switch ($field['html_type']) {
1097 case 'Autocomplete-Select':
1099 case 'Select Country':
1100 case 'Select State/Province':
1102 case 'Multi-Select':
1103 case 'Multi-Select State/Province':
1104 case 'Multi-Select Country':
1105 if ($field['data_type'] == 'ContactReference' && $value) {
1106 if (is_numeric($value)) {
1107 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1113 elseif (is_array($value)) {
1115 foreach ($value as $key => $val) {
1116 $v[] = CRM_Utils_Array
::value($val, $field['options']);
1118 $display = implode(', ', $v);
1121 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1126 $customFormat = NULL;
1128 // FIXME: Are there any legitimate reasons why $value would be an array?
1129 // Or should we throw an exception here if it is?
1130 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1132 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1133 $format = CRM_Utils_Array
::value('date_format', $field);
1136 if (array_key_exists($format, $actualPHPFormats)) {
1137 $customTimeFormat = (array) $actualPHPFormats[$format];
1138 switch (CRM_Utils_Array
::value('time_format', $field)) {
1140 $customTimeFormat[] = 'g:iA';
1144 $customTimeFormat[] = 'G:i';
1148 //If time is not selected remove time from value.
1149 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1151 $customFormat = implode(" ", $customTimeFormat);
1154 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1158 // In the context of displaying a profile, show file/image
1161 if (CRM_Utils_Rule
::positiveInteger($value)) {
1165 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1167 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1169 $display = $url['file_url'];
1173 // In other contexts show a paperclip icon
1174 if (CRM_Utils_Rule
::integer($value)) {
1175 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1177 $file_description = '';
1179 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1181 catch (CiviCRM_API3_Exception
$dontcare) {
1185 $display = "{$icons[$value]}{$file_description}";
1188 //CRM-18396, if filename is passed instead
1196 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1200 $display = nl2br($display);
1204 if ($field['data_type'] == 'Money' && isset($value)) {
1205 // $value can also be an array(while using IN operator from search builder or api).
1206 foreach ((array) $value as $val) {
1207 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1209 $display = implode(', ', $disp);
1217 * Set default values for custom data used in profile.
1219 * @param int $customFieldId
1221 * @param string $elementName
1222 * Custom field name.
1223 * @param array $defaults
1224 * Associated array of fields.
1225 * @param int $contactId
1229 * @param mixed $value
1230 * If passed - dont fetch value from db,.
1231 * just format the given value
1233 public static function setProfileDefaults(
1241 //get the type of custom field
1242 $customField = new CRM_Core_BAO_CustomField();
1243 $customField->id
= $customFieldId;
1244 $customField->find(TRUE);
1247 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1248 $value = $customField->default_value
;
1252 if (!isset($value)) {
1253 $info = self
::getTableColumnGroup($customFieldId);
1254 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1255 $result = CRM_Core_DAO
::executeQuery($query);
1256 if ($result->fetch()) {
1257 $value = $result->value
;
1261 if ($customField->data_type
== 'Country') {
1263 $config = CRM_Core_Config
::singleton();
1264 if ($config->defaultContactCountry
) {
1265 $value = CRM_Core_BAO_Country
::defaultContactCountry();
1271 //set defaults if mode is registration
1272 if (!trim($value) &&
1274 (!in_array($mode, [CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
]))
1276 $value = $customField->default_value
;
1279 if ($customField->data_type
== 'Money' && isset($value)) {
1280 $value = number_format($value, 2);
1282 switch ($customField->html_type
) {
1284 case 'Multi-Select':
1285 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1286 $defaults[$elementName] = [];
1287 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1288 substr($value, 1, -1)
1290 foreach ($customOption as $val) {
1291 if (in_array($val['value'], $checkedValue)) {
1292 if ($customField->html_type
== 'CheckBox') {
1293 $defaults[$elementName][$val['value']] = 1;
1295 elseif ($customField->html_type
== 'Multi-Select') {
1296 $defaults[$elementName][$val['value']] = $val['value'];
1303 $defaults[$elementName] = $value;
1310 * @param int $contactID
1312 * @param int $fileID
1313 * @param bool $absolute
1315 * @param string $multiRecordWhereClause
1319 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1322 $params = ['id' => $cfID];
1324 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1325 $columnName = $defaults['column_name'];
1327 //table name of custom data
1328 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1329 $defaults['custom_group_id'],
1333 //query to fetch id from civicrm_file
1334 if ($multiRecordWhereClause) {
1335 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1338 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1340 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1345 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1350 $result['file_id'] = $fileID;
1352 if ($fileType == 'image/jpeg' ||
1353 $fileType == 'image/pjpeg' ||
1354 $fileType == 'image/gif' ||
1355 $fileType == 'image/x-png' ||
1356 $fileType == 'image/png'
1358 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1363 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1364 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1365 $url = CRM_Utils_System
::url('civicrm/file',
1366 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1367 $absolute, NULL, TRUE, TRUE
1369 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1371 // for non image files
1373 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1377 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1378 $url = CRM_Utils_System
::url('civicrm/file',
1379 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1380 $absolute, NULL, TRUE, TRUE
1382 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1390 * Format custom fields before inserting.
1392 * @param int $customFieldId
1394 * @param array $customFormatted
1396 * @param mixed $value
1397 * Value of custom field.
1398 * @param string $customFieldExtend
1399 * Custom field extends.
1400 * @param int $customValueId
1401 * Custom option value id.
1402 * @param int $entityId
1403 * Entity id (contribution, membership...).
1404 * @param bool $inline
1405 * Consider inline custom groups only.
1406 * @param bool $checkPermission
1407 * If false, do not include permissioning clause.
1408 * @param bool $includeViewOnly
1409 * If true, fields marked 'View Only' are included. Required for APIv3.
1411 * @return array|NULL
1412 * formatted custom field array
1414 public static function formatCustomField(
1415 $customFieldId, &$customFormatted, $value,
1416 $customFieldExtend, $customValueId = NULL,
1419 $checkPermission = TRUE,
1420 $includeViewOnly = FALSE
1422 //get the custom fields for the entity
1423 //subtype and basic type
1424 $customDataSubType = NULL;
1425 if ($customFieldExtend) {
1426 // This is the case when getFieldsForImport() requires fields
1427 // of subtype and its parent.CRM-5143
1428 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1429 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1430 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1431 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1432 if (is_array($customFieldExtend)) {
1433 $customFieldExtend = array_unique(array_values($customFieldExtend));
1438 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1448 if (!array_key_exists($customFieldId, $customFields)) {
1452 // return if field is a 'code' field
1453 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1457 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1459 if (!$customValueId &&
1460 // we always create new entites for is_multiple unless specified
1461 !$customFields[$customFieldId]['is_multiple'] &&
1467 WHERE entity_id={$entityId}";
1469 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1472 //fix checkbox, now check box always submits values
1473 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1475 // Note that only during merge this is not an array, and you can directly use value
1476 if (is_array($value)) {
1477 $selectedValues = [];
1478 foreach ($value as $selId => $val) {
1480 $selectedValues[] = $selId;
1483 if (!empty($selectedValues)) {
1484 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1486 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1495 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select') {
1497 $value = CRM_Utils_Array
::implodePadded($value);
1504 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1505 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1507 $customFields[$customFieldId]['data_type'] == 'String' &&
1508 !empty($customFields[$customFieldId]['text_length']) &&
1511 // lets make sure that value is less than the length, else we'll
1512 // be losing some data, CRM-7481
1513 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1514 // need to do a few things here
1516 // 1. lets find a new length
1517 $newLength = $customFields[$customFieldId]['text_length'];
1518 $minLength = strlen($value);
1519 while ($newLength < $minLength) {
1520 $newLength = $newLength * 2;
1523 // set the custom field meta data to have a length larger than value
1524 // alter the custom value table column to match this length
1525 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1530 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1531 if (!CRM_Utils_System
::isNull($value)) {
1532 $format = $customFields[$customFieldId]['date_format'];
1533 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1538 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1539 $customFields[$customFieldId]['data_type'] == 'Money'
1545 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1546 $value = CRM_Utils_Rule
::cleanMoney($value);
1550 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1551 $customFields[$customFieldId]['data_type'] == 'Country'
1561 if ($customFields[$customFieldId]['data_type'] == 'File') {
1562 if (empty($value)) {
1566 $config = CRM_Core_Config
::singleton();
1568 // If we are already passing the file id as a value then retrieve and set the file data
1569 if (CRM_Utils_Rule
::integer($value)) {
1570 $fileDAO = new CRM_Core_DAO_File();
1571 $fileDAO->id
= $value;
1572 $fileDAO->find(TRUE);
1575 $fName = $fileDAO->uri
;
1576 $mimeType = $fileDAO->mime_type
;
1580 $fName = $value['name'];
1581 $mimeType = $value['type'];
1584 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1586 // rename this file to go into the secure directory only if
1587 // user has uploaded new file not existing verfied on the basis of $fileID
1588 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1589 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1592 if ($customValueId && empty($fileID)) {
1597 $params = [1 => [$customValueId, 'Integer']];
1598 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1601 $fileDAO = new CRM_Core_DAO_File();
1604 $fileDAO->id
= $fileID;
1607 $fileDAO->uri
= $filename;
1608 $fileDAO->mime_type
= $mimeType;
1609 $fileDAO->upload_date
= date('YmdHis');
1611 $fileID = $fileDAO->id
;
1615 if (!is_array($customFormatted)) {
1616 $customFormatted = [];
1619 if (!array_key_exists($customFieldId, $customFormatted)) {
1620 $customFormatted[$customFieldId] = [];
1624 if ($customValueId) {
1625 $index = $customValueId;
1628 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1629 $customFormatted[$customFieldId][$index] = [];
1631 $customFormatted[$customFieldId][$index] = [
1632 'id' => $customValueId > 0 ?
$customValueId : NULL,
1634 'type' => $customFields[$customFieldId]['data_type'],
1635 'custom_field_id' => $customFieldId,
1636 'custom_group_id' => $groupID,
1637 'table_name' => $tableName,
1638 'column_name' => $columnName,
1639 'file_id' => $fileID,
1640 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1643 //we need to sort so that custom fields are created in the order of entry
1644 krsort($customFormatted[$customFieldId]);
1645 return $customFormatted;
1649 * Get default custom table schema.
1651 * @param array $params
1655 public static function defaultCustomTableSchema($params) {
1656 // add the id and extends_id
1658 'name' => $params['name'],
1659 'is_multiple' => $params['is_multiple'],
1660 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1664 'type' => 'int unsigned',
1667 'attributes' => 'AUTO_INCREMENT',
1668 'comment' => 'Default MySQL primary key',
1671 'name' => 'entity_id',
1672 'type' => 'int unsigned',
1674 'comment' => 'Table that this extends',
1675 'fk_table_name' => $params['extends_name'],
1676 'fk_field_name' => 'id',
1677 'fk_attributes' => 'ON DELETE CASCADE',
1682 if (!$params['is_multiple']) {
1683 $table['indexes'] = [
1686 'field_name_1' => 'entity_id',
1694 * Create custom field.
1696 * @param CRM_Core_DAO_CustomField $field
1697 * @param string $operation
1699 public static function createField($field, $operation) {
1700 $sql = str_repeat(' ', 8);
1701 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1702 $sql .= "ALTER TABLE " . $tableName;
1703 $sql .= self
::getAlterFieldSQL($field, $operation);
1705 // CRM-7007: do not i18n-rewrite this query
1706 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1708 $config = CRM_Core_Config
::singleton();
1709 if ($config->logging
) {
1710 // CRM-16717 not sure why this was originally limited to add.
1711 // For example custom tables can have field length changes - which need to flow through to logging.
1712 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1713 if ($operation === 'add' ||
$operation === 'modify') {
1714 $logging = new CRM_Logging_Schema();
1715 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name
]]);
1719 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
1723 * @param CRM_Core_DAO_CustomField $field
1724 * @param string $operation
1728 public static function getAlterFieldSQL($field, $operation) {
1729 $indexExist = $operation === 'add' ?
FALSE : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $field->id
, 'is_searchable');
1730 $params = self
::prepareCreateParams($field, $operation);
1731 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1732 // a function only used by Custom Field creation...
1733 $params['required'] = FALSE;
1734 return CRM_Core_BAO_SchemaHandler
::getFieldAlterSQL($params, $indexExist);
1738 * Determine whether it would be safe to move a field.
1740 * @param int $fieldID
1741 * FK to civicrm_custom_field.
1742 * @param int $newGroupID
1743 * FK to civicrm_custom_group.
1746 * array(string) or TRUE
1748 public static function _moveFieldValidate($fieldID, $newGroupID) {
1751 $field = new CRM_Core_DAO_CustomField();
1752 $field->id
= $fieldID;
1753 if (!$field->find(TRUE)) {
1754 $errors['fieldID'] = 'Invalid ID for custom field';
1758 $oldGroup = new CRM_Core_DAO_CustomGroup();
1759 $oldGroup->id
= $field->custom_group_id
;
1760 if (!$oldGroup->find(TRUE)) {
1761 $errors['fieldID'] = 'Invalid ID for old custom group';
1765 $newGroup = new CRM_Core_DAO_CustomGroup();
1766 $newGroup->id
= $newGroupID;
1767 if (!$newGroup->find(TRUE)) {
1768 $errors['newGroupID'] = 'Invalid ID for new custom group';
1774 FROM civicrm_custom_field a
1775 INNER JOIN civicrm_custom_field b
1777 AND a.label = b.label
1778 AND b.custom_group_id = %2
1781 1 => [$field->id
, 'Integer'],
1782 2 => [$newGroup->id
, 'Integer'],
1784 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1786 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1789 $tableName = $oldGroup->table_name
;
1790 $columnName = $field->column_name
;
1795 WHERE $columnName is not null
1797 $count = CRM_Core_DAO
::singleValueQuery($query);
1801 FROM civicrm_custom_group
1802 WHERE id IN ( %1, %2 )
1805 1 => [$oldGroup->id
, 'Integer'],
1806 2 => [$newGroup->id
, 'Integer'],
1809 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1811 while ($dao->fetch()) {
1812 $extends[] = $dao->extends;
1814 if ($extends[0] != $extends[1]) {
1815 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1819 return empty($errors) ?
TRUE : $errors;
1823 * Move a custom data field from one group (table) to another.
1825 * @param int $fieldID
1826 * FK to civicrm_custom_field.
1827 * @param int $newGroupID
1828 * FK to civicrm_custom_group.
1830 public static function moveField($fieldID, $newGroupID) {
1831 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1832 if (TRUE !== $validation) {
1833 CRM_Core_Error
::fatal(implode(' ', $validation));
1835 $field = new CRM_Core_DAO_CustomField();
1836 $field->id
= $fieldID;
1839 $newGroup = new CRM_Core_DAO_CustomGroup();
1840 $newGroup->id
= $newGroupID;
1841 $newGroup->find(TRUE);
1843 $oldGroup = new CRM_Core_DAO_CustomGroup();
1844 $oldGroup->id
= $field->custom_group_id
;
1845 $oldGroup->find(TRUE);
1848 $add->custom_group_id
= $newGroup->id
;
1849 self
::createField($add, 'add');
1851 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1852 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1853 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1855 CRM_Core_DAO
::executeQuery($sql);
1858 $del->custom_group_id
= $oldGroup->id
;
1859 self
::createField($del, 'delete');
1863 CRM_Utils_System
::flushCache();
1867 * Create an option value for a custom field option group ID.
1869 * @param array $params
1870 * @param string $value
1871 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1872 * @param string $optionName
1873 * @param string $dataType
1875 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $optionName, $dataType) {
1876 if (strlen(trim($value))) {
1877 $optionValue = new CRM_Core_DAO_OptionValue();
1878 $optionValue->option_group_id
= $optionGroup->id
;
1879 $optionValue->label
= $params['option_label'][$optionName];
1880 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$optionName]);
1881 switch ($dataType) {
1883 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1887 $optionValue->value
= intval($value);
1891 $optionValue->value
= floatval($value);
1895 $optionValue->value
= trim($value);
1898 $optionValue->weight
= $params['option_weight'][$optionName];
1899 $optionValue->is_active
= CRM_Utils_Array
::value($optionName, $params['option_status'], FALSE);
1900 $optionValue->save();
1905 * Prepare for the create operation.
1907 * Munge params, create the option values if needed.
1909 * This could be called by a single create or a batchCreate.
1911 * @param array $params
1915 protected static function prepareCreate($params) {
1916 $op = empty($params['id']) ?
'create' : 'edit';
1917 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1918 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1919 if ($op === 'create') {
1920 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1921 if (!isset($params['column_name'])) {
1922 // if add mode & column_name not present, calculate it.
1923 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1925 if (!isset($params['name'])) {
1926 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1930 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1936 switch (CRM_Utils_Array
::value('html_type', $params)) {
1938 if (empty($params['date_format'])) {
1939 $config = CRM_Core_Config
::singleton();
1940 $params['date_format'] = $config->dateInputFormat
;
1945 case 'Multi-Select':
1946 if (isset($params['default_checkbox_option'])) {
1947 $tempArray = array_keys($params['default_checkbox_option']);
1949 foreach ($tempArray as $k => $v) {
1950 if ($params['option_value'][$v]) {
1951 $defaultArray[] = $params['option_value'][$v];
1955 if (!empty($defaultArray)) {
1956 // also add the separator before and after the value per new convention (CRM-1604)
1957 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1961 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
1963 $params['default_value'] = $params['option_value'][$params['default_option']];
1969 $htmlType = CRM_Utils_Array
::value('html_type', $params);
1970 $dataType = CRM_Utils_Array
::value('data_type', $params);
1971 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1973 // create any option group & values if required
1974 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)
1976 //CRM-16659: if option_value then create an option group for this custom field.
1977 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
1978 // first create an option group for this custom group
1979 $optionGroup = new CRM_Core_DAO_OptionGroup();
1980 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
1981 $optionGroup->title
= $params['label'];
1982 $optionGroup->is_active
= 1;
1983 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1984 $optionGroup->is_reserved
= 0;
1985 $optionGroup->data_type
= $dataType;
1986 $optionGroup->save();
1987 $params['option_group_id'] = $optionGroup->id
;
1988 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1989 foreach ($params['option_value'] as $k => $v) {
1990 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1996 // check for orphan option groups
1997 if (!empty($params['option_group_id'])) {
1998 if (!empty($params['id'])) {
1999 self
::fixOptionGroups($params['id'], $params['option_group_id']);
2002 // if we do not have a default value
2003 // retrieve it from one of the other custom fields which use this option group
2004 if (empty($params['default_value'])) {
2005 //don't insert only value separator as default value, CRM-4579
2006 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
2010 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2014 $params['default_value'] = $defaultValue;
2019 // since we need to save option group id :)
2020 if (!isset($params['attributes']) && strtolower($htmlType) == 'textarea') {
2021 $params['attributes'] = 'rows=4, cols=60';
2027 * Create database entry for custom field and related option groups.
2029 * @param array $params
2031 * @return CRM_Core_DAO_CustomField
2033 protected static function createCustomFieldRecord($params) {
2034 $transaction = new CRM_Core_Transaction();
2035 $params = self
::prepareCreate($params);
2037 $customField = new CRM_Core_DAO_CustomField();
2038 $customField->copyValues($params);
2039 $customField->save();
2041 //create/drop the index when we toggle the is_searchable flag
2042 $op = empty($params['id']) ?
'add' : 'modify';
2043 if ($op !== 'modify') {
2044 if ($params['is_append_field_id_to_column_name']) {
2045 $params['column_name'] .= "_{$customField->id}";
2047 $customField->column_name
= $params['column_name'];
2048 $customField->save();
2051 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
2052 $transaction->commit();
2054 // make sure all values are present in the object for further processing
2055 $customField->find(TRUE);
2056 return $customField;
2060 * Move custom data from one contact to another.
2062 * This is currently the start of a refactoring. The theory is each
2063 * entity could have a 'move' function with a DAO default one to fall back on.
2065 * At the moment this only does a small part of the process - ie deleting a file field that
2066 * is about to be overwritten. However, the goal is the whole process around the move for
2067 * custom data should be in here.
2069 * This is currently called by the merge class but it makes sense that api could
2070 * expose move actions as moving (e.g) contributions feels like a common
2071 * ask that should be handled by the form layer.
2073 * @param int $oldContactID
2074 * @param int $newContactID
2075 * @param int[] $fieldIDs
2076 * Optional list field ids to move.
2078 * @throws \CiviCRM_API3_Exception
2079 * @throws \Exception
2081 public function move($oldContactID, $newContactID, $fieldIDs) {
2082 if (empty($fieldIDs)) {
2085 $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'];
2087 foreach ($fieldIDs as $fieldID) {
2088 $return[] = 'custom_' . $fieldID;
2090 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2091 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2093 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2094 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2095 $fieldTypesNotHandledInMergeAttempt = ['File'];
2096 foreach ($fields as $field) {
2097 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2098 if ($field['data_type'] === 'File' && !$isMultiple) {
2099 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2100 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2102 if (!empty($oldContact['custom_' . $field['id']])) {
2103 CRM_Core_DAO
::executeQuery("
2104 UPDATE civicrm_entity_file
2105 SET entity_id = $newContactID
2106 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2110 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2111 CRM_Core_DAO
::executeQuery(
2112 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2113 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2114 ON DUPLICATE KEY UPDATE
2115 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2122 * Get the database table name and column name for a custom field.
2124 * @param int $fieldID
2125 * The fieldID of the custom field.
2126 * @param bool $force
2127 * Force the sql to be run again (primarily used for tests).
2130 * fatal is fieldID does not exists, else array of tableName, columnName
2131 * @throws \Exception
2133 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2134 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2135 $cache = CRM_Utils_Cache
::singleton();
2136 $fieldValues = $cache->get($cacheKey);
2137 if (empty($fieldValues) ||
$force) {
2139 SELECT cg.table_name, cf.column_name, cg.id
2140 FROM civicrm_custom_group cg,
2141 civicrm_custom_field cf
2142 WHERE cf.custom_group_id = cg.id
2144 $params = [1 => [$fieldID, 'Integer']];
2145 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2147 if (!$dao->fetch()) {
2148 CRM_Core_Error
::fatal();
2150 $fieldValues = [$dao->table_name
, $dao->column_name
, $dao->id
];
2151 $cache->set($cacheKey, $fieldValues);
2153 return $fieldValues;
2157 * Get custom option groups.
2159 * @deprecated Use the API OptionGroup.get
2161 * @param array $includeFieldIds
2162 * Ids of custom fields for which option groups must be included.
2164 * Currently this is required in the cases where option groups are to be included
2165 * for inactive fields : CRM-5369
2169 public static function customOptionGroup($includeFieldIds = NULL) {
2170 static $customOptionGroup = NULL;
2172 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2173 if ($cacheKey == 'force') {
2174 $customOptionGroup[$cacheKey] = NULL;
2177 if (empty($customOptionGroup[$cacheKey])) {
2178 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2180 //support for single as well as array format.
2181 if (!empty($includeFieldIds)) {
2182 if (is_array($includeFieldIds)) {
2183 $includeFieldIds = implode(',', $includeFieldIds);
2185 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2189 SELECT g.id, g.title
2190 FROM civicrm_option_group g
2191 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2192 WHERE {$whereClause}";
2194 $dao = CRM_Core_DAO
::executeQuery($query);
2195 while ($dao->fetch()) {
2196 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2200 return $customOptionGroup[$cacheKey];
2204 * Get defaults for new entity.
2208 public static function getDefaults() {
2210 'is_required' => FALSE,
2211 'is_searchable' => FALSE,
2212 'in_selector' => FALSE,
2213 'is_search_range' => FALSE,
2214 //CRM-15792 - Custom field gets disabled if is_active not set
2215 // this would ideally be a mysql default.
2216 'is_active' => TRUE,
2222 * Fix orphan groups.
2224 * @param int $customFieldId
2226 * @param int $optionGroupId
2229 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2230 // check if option group belongs to any custom Field else delete
2231 // get the current option group
2232 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2236 // get the updated option group
2237 // if both are same return
2238 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2242 // check if option group is related to any other field
2243 self
::checkOptionGroup($currentOptionGroupId);
2247 * Check if option group is related to more than one custom field.
2249 * @param int $optionGroupId
2252 public static function checkOptionGroup($optionGroupId) {
2255 FROM civicrm_custom_field
2256 WHERE option_group_id = {$optionGroupId}";
2258 $count = CRM_Core_DAO
::singleValueQuery($query);
2261 //delete the option group
2262 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2267 * Get option group default.
2269 * @param int $optionGroupId
2270 * @param string $htmlType
2272 * @return null|string
2274 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2276 SELECT default_value, html_type
2277 FROM civicrm_custom_field
2278 WHERE option_group_id = {$optionGroupId}
2279 AND default_value IS NOT NULL
2280 ORDER BY html_type";
2282 $dao = CRM_Core_DAO
::executeQuery($query);
2283 $defaultValue = NULL;
2284 $defaultHTMLType = NULL;
2285 while ($dao->fetch()) {
2286 if ($dao->html_type
== $htmlType) {
2287 return $dao->default_value
;
2289 if ($defaultValue == NULL) {
2290 $defaultValue = $dao->default_value
;
2291 $defaultHTMLType = $dao->html_type
;
2295 // some conversions are needed if either the old or new has a html type which has potential
2296 // multiple default values.
2297 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2298 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2300 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2302 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2303 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2305 $defaultValue = substr($defaultValue, 1, -1);
2306 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2307 substr($defaultValue, 1, -1)
2309 $defaultValue = $values[0];
2312 return $defaultValue;
2316 * Post process function.
2318 * @param array $params
2319 * @param int $entityID
2320 * @param string $customFieldExtends
2321 * @param bool $inline
2322 * @param bool $checkPermissions
2326 public static function postProcess(
2329 $customFieldExtends,
2331 $checkPermissions = TRUE
2335 foreach ($params as $key => $value) {
2336 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2338 // for autocomplete transfer hidden value instead of label
2339 if ($params[$key] && isset($params[$key . '_id'])) {
2340 $value = $params[$key . '_id'];
2343 // we need to append time with date
2344 if ($params[$key] && isset($params[$key . '_time'])) {
2345 $value .= ' ' . $params[$key . '_time'];
2348 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2351 $customFieldExtends,
2352 $customFieldInfo[1],
2363 * Get custom field ID from field/group name/title.
2365 * @param string $fieldName Field name or label
2366 * @param string|null $groupName (Optional) Group name or label
2367 * @param bool $fullString Whether to return "custom_123" or "123"
2369 * @return string|int|null
2370 * @throws \CiviCRM_API3_Exception
2372 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2373 $cacheKey = $groupName . '.' . $fieldName;
2374 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2375 $customFieldParams = [
2376 'name' => $fieldName,
2377 'label' => $fieldName,
2378 'options' => ['or' => [["name", "label"]]],
2382 $customFieldParams['custom_group_id.name'] = $groupName;
2383 $customFieldParams['custom_group_id.title'] = $groupName;
2384 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2387 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2389 if (empty($field['id'])) {
2390 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2391 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2394 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2395 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2400 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2402 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2406 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2412 public static function getNameFromID($ids) {
2413 if (is_array($ids)) {
2414 $ids = implode(',', $ids);
2417 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2418 FROM civicrm_custom_field f
2419 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2420 WHERE f.id IN ($ids)";
2422 $dao = CRM_Core_DAO
::executeQuery($sql);
2424 while ($dao->fetch()) {
2425 $result[$dao->id
] = [
2426 'field_name' => $dao->field_name
,
2427 'field_label' => $dao->field_label
,
2428 'group_name' => $dao->group_name
,
2429 'group_title' => $dao->group_title
,
2436 * Validate custom data.
2438 * @param array $params
2439 * Custom data submitted.
2440 * ie array( 'custom_1' => 'validate me' );
2443 * validation errors.
2445 public static function validateCustomData($params) {
2447 if (!is_array($params) ||
empty($params)) {
2451 //pick up profile fields.
2452 $profileFields = [];
2453 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2455 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2457 CRM_Core_Action
::VIEW
2461 //lets start w/ params.
2462 foreach ($params as $key => $value) {
2463 $customFieldID = self
::getKeyID($key);
2464 if (!$customFieldID) {
2468 //load the structural info for given field.
2469 $field = new CRM_Core_DAO_CustomField();
2470 $field->id
= $customFieldID;
2471 if (!$field->find(TRUE)) {
2474 $dataType = $field->data_type
;
2476 $profileField = CRM_Utils_Array
::value($key, $profileFields, []);
2477 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2478 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2480 $fieldTitle = $field->label
;
2483 //no need to validate.
2484 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2488 //lets validate first for required field.
2489 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2490 $errors[$key] = ts('%1 is a required field.', [1 => $fieldTitle]);
2494 //now time to take care of custom field form rules.
2495 $ruleName = $errorMsg = NULL;
2496 switch ($dataType) {
2498 $ruleName = 'integer';
2499 $errorMsg = ts('%1 must be an integer (whole number).',
2500 array(1 => $fieldTitle)
2505 $ruleName = 'money';
2506 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2507 array(1 => $fieldTitle)
2512 $ruleName = 'numeric';
2513 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2514 array(1 => $fieldTitle)
2519 $ruleName = 'wikiURL';
2520 $errorMsg = ts('%1 must be valid Website.',
2521 array(1 => $fieldTitle)
2526 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2528 $funName = "CRM_Utils_Rule::{$ruleName}";
2529 if (is_callable($funName)) {
2530 $valid = call_user_func($funName, $value);
2533 $errors[$key] = $errorMsg;
2542 * Is this field a multi record field.
2544 * @param int $customId
2548 public static function isMultiRecordField($customId) {
2549 $isMultipleWithGid = FALSE;
2550 if (!is_numeric($customId)) {
2551 $customId = self
::getKeyID($customId);
2553 if (is_numeric($customId)) {
2554 $sql = "SELECT cg.id cgId
2555 FROM civicrm_custom_group cg
2556 INNER JOIN civicrm_custom_field cf
2557 ON cg.id = cf.custom_group_id
2558 WHERE cf.id = %1 AND cg.is_multiple = 1";
2559 $params[1] = [$customId, 'Integer'];
2560 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2561 if ($dao->fetch()) {
2563 $isMultipleWithGid = $dao->cgId
;
2568 return $isMultipleWithGid;
2572 * Does this field type have any select options?
2574 * @param array $field
2578 public static function hasOptions($field) {
2579 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2580 $field = (array) $field;
2581 // This will include boolean fields with Yes/No options.
2582 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2585 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2586 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2587 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2590 if (strpos($field['html_type'], 'Select') !== FALSE) {
2593 return !empty($field['option_group_id']);
2597 * Does this field store a serialized string?
2599 * @param array|object $field
2603 public static function isSerialized($field) {
2604 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2605 $html_type = is_object($field) ?
$field->html_type
: $field['html_type'];
2606 // 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.
2607 return ($html_type === 'CheckBox' ||
strpos($html_type, 'Multi') !== FALSE);
2611 * Get api entity for this field
2615 public function getEntity() {
2616 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2617 return in_array($entity, ['Individual', 'Household', 'Organization']) ?
'Contact' : $entity;
2621 * Set pseudoconstant properties for field metadata.
2623 * @param array $field
2624 * @param string|null $optionGroupName
2626 private static function getOptionsForField(&$field, $optionGroupName) {
2627 if ($optionGroupName) {
2628 $field['pseudoconstant'] = [
2629 'optionGroupName' => $optionGroupName,
2630 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2633 elseif ($field['data_type'] == 'Boolean') {
2634 $field['pseudoconstant'] = [
2635 'callback' => 'CRM_Core_SelectValues::boolean',
2638 elseif ($field['data_type'] == 'Country') {
2639 $field['pseudoconstant'] = [
2640 'table' => 'civicrm_country',
2641 'keyColumn' => 'id',
2642 'labelColumn' => 'name',
2643 'nameColumn' => 'iso_code',
2646 elseif ($field['data_type'] == 'StateProvince') {
2647 $field['pseudoconstant'] = [
2648 'table' => 'civicrm_state_province',
2649 'keyColumn' => 'id',
2650 'labelColumn' => 'name',
2656 * @param CRM_Core_DAO_CustomField $field
2657 * @param 'add|modify' $operation
2661 protected static function prepareCreateParams($field, $operation) {
2662 $tableName = CRM_Core_DAO
::getFieldValue(
2663 'CRM_Core_DAO_CustomGroup',
2664 $field->custom_group_id
,
2669 'table_name' => $tableName,
2670 'operation' => $operation,
2671 'name' => $field->column_name
,
2672 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2676 'required' => $field->is_required
,
2677 'searchable' => $field->is_searchable
,
2680 if ($operation == 'delete') {
2681 $fkName = "{$tableName}_{$field->column_name}";
2682 if (strlen($fkName) >= 48) {
2683 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2685 $params['fkName'] = $fkName;
2687 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
2688 $params['fk_table_name'] = 'civicrm_country';
2689 $params['fk_field_name'] = 'id';
2690 $params['fk_attributes'] = 'ON DELETE SET NULL';
2692 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
2693 $params['type'] = 'varchar(255)';
2695 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
2696 $params['fk_table_name'] = 'civicrm_state_province';
2697 $params['fk_field_name'] = 'id';
2698 $params['fk_attributes'] = 'ON DELETE SET NULL';
2700 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
2701 $params['type'] = 'varchar(255)';
2703 elseif ($field->data_type
== 'File') {
2704 $params['fk_table_name'] = 'civicrm_file';
2705 $params['fk_field_name'] = 'id';
2706 $params['fk_attributes'] = 'ON DELETE SET NULL';
2708 elseif ($field->data_type
== 'ContactReference') {
2709 $params['fk_table_name'] = 'civicrm_contact';
2710 $params['fk_field_name'] = 'id';
2711 $params['fk_attributes'] = 'ON DELETE SET NULL';
2713 if (isset($field->default_value
)) {
2714 $params['default'] = "'{$field->default_value}'";