3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * Business objects for managing custom data fields.
37 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
40 * Array for valid combinations of data_type & descriptions.
44 public static $_dataType = NULL;
47 * Array for valid combinations of data_type & html_type.
51 public static $_dataToHtml = NULL;
54 * Array to hold (formatted) fields for import
58 public static $_importFields = NULL;
61 * Build and retrieve the list of data types and descriptions.
64 * Data type => Description
66 public static function &dataType() {
67 if (!(self
::$_dataType)) {
68 self
::$_dataType = array(
69 'String' => ts('Alphanumeric'),
70 'Int' => ts('Integer'),
71 'Float' => ts('Number'),
72 'Money' => ts('Money'),
75 'Boolean' => ts('Yes or No'),
76 'StateProvince' => ts('State/Province'),
77 'Country' => ts('Country'),
80 'ContactReference' => ts('Contact Reference'),
83 return self
::$_dataType;
87 * Build the map of custom field's data types and there respective Util type
90 * Data data-type => CRM_Utils_Type
92 public static function dataToType() {
94 'String' => CRM_Utils_Type
::T_STRING
,
95 'Int' => CRM_Utils_Type
::T_INT
,
96 'Money' => CRM_Utils_Type
::T_MONEY
,
97 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
98 'Float' => CRM_Utils_Type
::T_FLOAT
,
99 'Date' => CRM_Utils_Type
::T_DATE
,
100 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
101 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
102 'StateProvince' => CRM_Utils_Type
::T_INT
,
103 'File' => CRM_Utils_Type
::T_STRING
,
104 'Link' => CRM_Utils_Type
::T_STRING
,
105 'ContactReference' => CRM_Utils_Type
::T_INT
,
106 'Country' => CRM_Utils_Type
::T_INT
,
111 * Get data to html array.
113 * (Does this caching achieve anything?)
117 public static function dataToHtml() {
118 if (!self
::$_dataToHtml) {
119 self
::$_dataToHtml = array(
122 'Select' => 'Select',
124 'CheckBox' => 'CheckBox',
125 'Multi-Select' => 'Multi-Select',
126 'Autocomplete-Select' => 'Autocomplete-Select',
128 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
129 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
130 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
131 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
132 array('Date' => 'Select Date'),
133 array('Radio' => 'Radio'),
134 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
135 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
136 array('File' => 'File'),
137 array('Link' => 'Link'),
138 array('ContactReference' => 'Autocomplete-Select'),
141 return self
::$_dataToHtml;
145 * Takes an associative array and creates a custom field object.
147 * This function is invoked from within the web form layer and also from the api layer
149 * @param array $params
150 * (reference) an assoc array of name/value pairs.
152 * @return CRM_Core_DAO_CustomField
154 public static function create($params) {
155 $customField = self
::createCustomFieldRecord($params);
156 $op = empty($params['id']) ?
'add' : 'modify';
157 self
::createField($customField, $op);
159 CRM_Utils_Hook
::post(($op === 'add' ?
'create' : 'edit'), 'CustomField', $customField->id
, $customField);
161 CRM_Utils_System
::flushCache();
167 * Create/ update several fields at once in a mysql efficient way.
169 * https://lab.civicrm.org/dev/core/issues/1093
171 * The intention is that apiv4 would expose any BAO with bulkSave as a new action.
173 * @param array $bulkParams
174 * Array of arrays as would be passed into create
175 * @param array $defaults
176 * Default parameters to be be merged into each of the params.
178 public static function bulkSave($bulkParams, $defaults = []) {
179 $sql = $tables = $customFields = [];
180 foreach ($bulkParams as $index => $fieldParams) {
181 $params = array_merge($defaults, $fieldParams);
182 $customField = self
::createCustomFieldRecord($params);
183 $fieldSQL = self
::getAlterFieldSQL($customField, empty($params['id']) ?
'add' : 'modify');
184 if (!isset($params['custom_group_id'])) {
185 $params['custom_group_id'] = civicrm_api3('CustomField', 'getvalue', ['id' => $customField->id
, 'return' => 'custom_group_id']);
187 if (!isset($params['table_name'])) {
188 if (!isset($tables[$params['custom_group_id']])) {
189 $tables[$params['custom_group_id']] = civicrm_api3('CustomGroup', 'getvalue', [
190 'id' => $params['custom_group_id'],
191 'return' => 'table_name',
194 $params['table_name'] = $tables[$params['custom_group_id']];
196 $sql[$params['table_name']][] = $fieldSQL;
197 $customFields[$index] = $customField;
199 foreach ($sql as $tableName => $statements) {
200 // CRM-7007: do not i18n-rewrite this query
201 CRM_Core_DAO
::executeQuery("ALTER TABLE $tableName " . implode(', ', $statements), [], TRUE, NULL, FALSE, FALSE);
202 Civi
::service('sql_triggers')->rebuild($params['table_name'], TRUE);
204 CRM_Utils_System
::flushCache();
205 foreach ($customFields as $index => $customField) {
206 CRM_Utils_Hook
::post(empty($bulkParams[$index]['id']) ?
'create' : 'edit', 'CustomField', $customField->id
, $customField);
211 * Fetch object based on array of properties.
213 * @param array $params
214 * (reference ) an assoc array of name/value pairs.
215 * @param array $defaults
216 * (reference ) an assoc array to hold the flattened values.
218 * @return CRM_Core_DAO_CustomField
220 public static function retrieve(&$params, &$defaults) {
221 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
225 * Update the is_active flag in the db.
228 * Id of the database record.
229 * @param bool $is_active
230 * Value we want to set the is_active field.
233 * true if we found and updated the object, else false
235 public static function setIsActive($id, $is_active) {
237 CRM_Utils_System
::flushCache();
239 //enable-disable CustomField
240 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
241 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
245 * Get the field title.
253 public static function getTitle($id) {
254 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
258 * @param string $context
261 public function getOptions($context = NULL) {
262 CRM_Core_DAO
::buildOptionsContext($context);
267 if (!$this->data_type ||
!$this->custom_group_id
) {
271 // This will hold the list of options in format key => label
274 if (!empty($this->option_group_id
)) {
275 $options = CRM_Core_OptionGroup
::valuesByID(
276 $this->option_group_id
,
281 !($context == 'validate' ||
$context == 'get')
284 elseif ($this->data_type
=== 'StateProvince') {
285 $options = CRM_Core_PseudoConstant
::stateProvince();
287 elseif ($this->data_type
=== 'Country') {
288 $options = $context == 'validate' ? CRM_Core_PseudoConstant
::countryIsoCode() : CRM_Core_PseudoConstant
::country();
290 elseif ($this->data_type
=== 'Boolean') {
291 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
293 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
294 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, array('context' => $context));
299 * Store and return an array of all active custom fields.
301 * @param string $customDataType
302 * Type of Custom Data; 'ANY' is a synonym for "all contact data types".
303 * @param bool $showAll
304 * If true returns all fields (includes disabled fields).
305 * @param bool $inline
306 * If true returns all inline fields (includes disabled fields).
307 * @param int $customDataSubType
308 * Custom Data sub type value.
309 * @param int $customDataSubName
310 * Custom Data sub name value.
311 * @param bool $onlyParent
312 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
313 * @param bool $onlySubType
314 * Return only custom data for subtype.
315 * @param bool $checkPermission
316 * If false, do not include permissioning clause.
319 * an array of active custom fields.
321 public static function &getFields(
322 $customDataType = 'Individual',
325 $customDataSubType = NULL,
326 $customDataSubName = NULL,
328 $onlySubType = FALSE,
329 $checkPermission = TRUE
331 if (empty($customDataType)) {
332 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
334 if ($customDataType === 'ANY') {
335 // NULL should have been respected but the line above broke that.
336 // boo for us not having enough unit tests back them.
337 $customDataType = NULL;
339 if ($customDataType && !is_array($customDataType)) {
341 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
342 // This is the case when getFieldsForImport() requires fields
343 // limited strictly to a subtype.
344 $customDataSubType = $customDataType;
345 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
349 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
350 // this makes the method flexible to support retrieving fields
351 // for multiple extends value.
352 $customDataType = array($customDataType);
356 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
358 if (is_array($customDataType)) {
359 $cacheKey = implode('_', $customDataType);
362 $cacheKey = $customDataType;
365 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
366 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
367 $cacheKey .= $showAll ?
'_1' : '_0';
368 $cacheKey .= $inline ?
'_1_' : '_0_';
369 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
370 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
371 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
372 $cacheKey .= '_' . CRM_Core_Config
::domainID() . '_';
374 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
376 // also get the permission stuff here
377 if ($checkPermission) {
378 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
383 $permissionClause = '(1)';
386 // lets md5 permission clause and take first 8 characters
387 $cacheKey .= substr(md5($permissionClause), 0, 8);
389 if (strlen($cacheKey) > 40) {
390 $cacheKey = md5($cacheKey);
393 if (!self
::$_importFields ||
394 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
396 if (!self
::$_importFields) {
397 self
::$_importFields = array();
400 // check if we can retrieve from database cache
401 $fields = Civi
::Cache('fields')->get("custom importableFields $cacheKey");
403 if ($fields === NULL) {
404 $cfTable = self
::getTableName();
407 if (is_array($customDataType)) {
409 foreach ($customDataType as $dataType) {
410 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
411 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
412 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
415 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
417 $value = $value ?
$value . ", {$val}" : $val;
421 $extends = "AND $cgTable.extends IN ( $value ) ";
425 if (!empty($customDataType) && empty($extends)) {
426 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
427 self
::$_importFields[$cacheKey] = array();
428 return self
::$_importFields[$cacheKey];
432 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
435 $query = "SELECT $cfTable.id, $cfTable.label,
439 $cfTable.default_value,
440 $cfTable.options_per_line, $cfTable.text_length,
441 $cfTable.custom_group_id,
442 $cfTable.is_required,
443 $cfTable.column_name,
444 $cgTable.extends, $cfTable.is_search_range,
445 $cgTable.extends_entity_column_value,
446 $cgTable.extends_entity_column_id,
448 $cfTable.option_group_id,
449 $cfTable.date_format,
450 $cfTable.time_format,
451 $cgTable.is_multiple,
453 og.name as option_group_name
456 ON $cfTable.custom_group_id = $cgTable.id
457 LEFT JOIN civicrm_option_group og
458 ON $cfTable.option_group_id = og.id
462 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
466 $query .= " AND $cgTable.style = 'Inline' ";
469 //get the custom fields for specific type in
470 //combination with fields those support any type.
471 if (!empty($customDataSubType)) {
472 $subtypeClause = array();
473 foreach ($customDataSubType as $subtype) {
474 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($subtype, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
;
475 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
478 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
480 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
483 if ($customDataSubName) {
484 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
487 // also get the permission stuff here
488 if ($checkPermission) {
489 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
494 $permissionClause = '(1)';
497 $query .= " $extends AND $permissionClause
498 ORDER BY $cgTable.weight, $cgTable.title,
499 $cfTable.weight, $cfTable.label";
501 $dao = CRM_Core_DAO
::executeQuery($query);
504 while (($dao->fetch()) != NULL) {
505 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
506 $fields[$dao->id
]['id'] = $dao->id
;
507 $fields[$dao->id
]['label'] = $dao->label
;
508 // This seems broken, but not in a new way.
509 $fields[$dao->id
]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
510 // To support the consolidation of various functions & their expectations.
511 $fields[$dao->id
]['title'] = $dao->label
;
512 $fields[$dao->id
]['custom_field_id'] = $dao->id
;
513 $fields[$dao->id
]['groupTitle'] = $dao->title
;
514 $fields[$dao->id
]['data_type'] = $dao->data_type
;
515 $fields[$dao->id
]['name'] = 'custom_' . $dao->id
;
516 $fields[$dao->id
]['type'] = CRM_Utils_Array
::value($dao->data_type
, self
::dataToType());
517 $fields[$dao->id
]['html_type'] = $dao->html_type
;
518 $fields[$dao->id
]['default_value'] = $dao->default_value
;
519 $fields[$dao->id
]['text_length'] = $dao->text_length
;
520 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
521 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
522 $fields[$dao->id
]['extends'] = $dao->extends;
523 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
524 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
525 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
526 $fields[$dao->id
]['is_view'] = $dao->is_view
;
527 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
528 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
529 $fields[$dao->id
]['date_format'] = $dao->date_format
;
530 $fields[$dao->id
]['time_format'] = $dao->time_format
;
531 $fields[$dao->id
]['is_required'] = $dao->is_required
;
532 $fields[$dao->id
]['table_name'] = $dao->table_name
;
533 $fields[$dao->id
]['column_name'] = $dao->column_name
;
534 $fields[$dao->id
]['where'] = $dao->table_name
. '.' . $dao->column_name
;
535 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
536 $fields[$dao->id
]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery
::$extendsMap) ? CRM_Core_BAO_CustomQuery
::$extendsMap[$dao->extends] : '';
537 if (in_array($dao->extends, CRM_Contact_BAO_ContactType
::subTypes())) {
538 // if $extends is a subtype, refer contact table
539 $fields[$dao->id
]['extends_table'] = 'civicrm_contact';
541 // Search table is used by query object searches..
542 $fields[$dao->id
]['search_table'] = ($fields[$dao->id
]['extends_table'] == 'civicrm_contact') ?
'contact_a' : $fields[$dao->id
]['extends_table'];
543 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
546 Civi
::cache('fields')->set("custom importableFields $cacheKey", $fields);
548 self
::$_importFields[$cacheKey] = $fields;
551 return self
::$_importFields[$cacheKey];
555 * Return the field ids and names (with groups) for import purpose.
557 * @param int|string $contactType Contact type
558 * @param bool $showAll
559 * If true returns all fields (includes disabled fields).
560 * @param bool $onlyParent
561 * Return fields ONLY related to basic types.
562 * @param bool $search
563 * When called from search and multiple records need to be returned.
564 * @param bool $checkPermission
565 * If false, do not include permissioning clause.
567 * @param bool $withMultiple
571 public static function getFieldsForImport(
572 $contactType = 'Individual',
576 $checkPermission = TRUE,
577 $withMultiple = FALSE
579 // Note: there are situations when we want getFieldsForImport() return fields related
580 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
581 $fields = &self
::getFields($contactType,
591 $importableFields = [];
592 foreach ($fields as $id => $values) {
593 // for now we should not allow multiple fields in profile / export etc, hence unsetting
595 (!empty($values['is_multiple']) && !$withMultiple)
599 if (!empty($values['text_length'])) {
600 $values['maxlength'] = (int) $values['text_length'];
603 /* generate the key for the fields array */
606 $importableFields[$key] = $values;
607 $importableFields[$key]['import'] = 1;
610 return $importableFields;
614 * Get the field id from an import key.
624 public static function getKeyID($key, $all = FALSE) {
626 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
633 CRM_Utils_Array
::value(2, $match),
637 return $all ?
array(NULL, NULL) : NULL;
641 * Use the cache to get all values of a specific custom field.
643 * @param int $fieldID
644 * The custom field ID.
646 * @return CRM_Core_BAO_CustomField
649 public static function getFieldObject($fieldID) {
650 $field = new CRM_Core_BAO_CustomField();
652 // check if we can get the field values from the system cache
653 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
654 $cache = CRM_Utils_Cache
::singleton();
655 $fieldValues = $cache->get($cacheKey);
656 if (empty($fieldValues)) {
657 $field->id
= $fieldID;
658 if (!$field->find(TRUE)) {
659 CRM_Core_Error
::fatal();
662 $fieldValues = array();
663 CRM_Core_DAO
::storeValues($field, $fieldValues);
665 $cache->set($cacheKey, $fieldValues);
668 $field->copyValues($fieldValues);
675 * Add a custom field to an existing form.
677 * @param CRM_Core_Form $qf
678 * Form object (reference).
679 * @param string $elementName
680 * Name of the custom field.
681 * @param int $fieldId
682 * @param bool $useRequired
683 * True if required else false.
684 * @param bool $search
685 * True if used for search else false.
686 * @param string $label
687 * Label for custom field.
688 * @return \HTML_QuickForm_Element|null
689 * @throws \CiviCRM_API3_Exception
691 public static function addQuickFormElement(
692 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
694 $field = self
::getFieldObject($fieldId);
695 $widget = $field->html_type
;
697 $customFieldAttributes = array();
699 // Custom field HTML should indicate group+field name
700 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
701 $dataCrmCustomVal = $groupName . ':' . $field->name
;
702 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
703 $field->attributes
.= $dataCrmCustomAttr;
705 // Fixed for Issue CRM-2183
706 if ($widget == 'TextArea' && $search) {
710 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
712 // FIXME: Why are select state/country separate widget types?
713 $isSelect = (in_array($widget, array(
716 'Select State/Province',
717 'Multi-Select State/Province',
719 'Multi-Select Country',
725 $options = $field->getOptions($search ?
'search' : 'create');
727 // Consolidate widget types to simplify the below switch statement
728 if ($search ||
(strpos($widget, 'Select') !== FALSE)) {
732 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
733 $selectAttributes = array('class' => 'crm-select2');
735 // Search field is always multi-select
736 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
737 $selectAttributes['class'] .= ' huge';
738 $selectAttributes['multiple'] = 'multiple';
739 $selectAttributes['placeholder'] = $placeholder;
742 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
743 $isSupportedWidget = in_array($widget, ['Select', 'Radio']);
744 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
745 if ($field->option_group_id
&& !$search && $isSelect && $canEditOptions) {
746 $customFieldAttributes +
= array(
747 'data-api-entity' => $field->getEntity(),
748 'data-api-field' => 'custom_' . $field->id
,
749 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
751 $selectAttributes +
= $customFieldAttributes;
755 $rangeDataTypes = ['Int', 'Float', 'Money'];
757 if (!isset($label)) {
758 $label = $field->label
;
761 // at some point in time we might want to split the below into small functions
766 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
767 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
768 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
771 if ($field->text_length
) {
772 $field->attributes
.= ' maxlength=' . $field->text_length
;
773 if ($field->text_length
< 20) {
774 $field->attributes
.= ' size=' . $field->text_length
;
777 $element = $qf->add('text', $elementName, $label,
779 $useRequired && !$search
785 $attributes = $dataCrmCustomAttr;
786 if ($field->note_rows
) {
787 $attributes .= 'rows=' . $field->note_rows
;
790 $attributes .= 'rows=4';
792 if ($field->note_columns
) {
793 $attributes .= ' cols=' . $field->note_columns
;
796 $attributes .= ' cols=60';
798 if ($field->text_length
) {
799 $attributes .= ' maxlength=' . $field->text_length
;
801 $element = $qf->add('textarea',
805 $useRequired && !$search
810 $attr = array('data-crm-custom' => $dataCrmCustomVal);
811 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
812 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
813 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
816 'date' => $field->date_format
,
817 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
818 //CRM-18487 - max date should be the last date of the year.
819 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
820 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
822 if ($field->is_search_range
&& $search) {
823 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
824 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
827 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
832 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
833 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
834 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
838 parse_str($field->attributes
, $radioAttributes);
839 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
841 foreach ($options as $v => $l) {
842 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
844 $element = $qf->addGroup($choice, $elementName, $label);
845 $optionEditKey = 'data-option-edit-path';
846 if (isset($selectAttributes[$optionEditKey])) {
847 $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
850 if ($useRequired && !$search) {
851 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
854 $element->setAttribute('allowClear', TRUE);
859 // For all select elements
861 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
862 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
863 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
866 if (empty($selectAttributes['multiple'])) {
867 $options = array('' => $placeholder) +
$options;
869 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
871 // Add and/or option for fields that store multiple values
872 if ($search && self
::isSerialized($field)) {
875 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
876 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
878 $qf->addGroup($operators, $elementName . '_operator');
879 $qf->setDefaults(array($elementName . '_operator' => 'or'));
886 foreach ($options as $v => $l) {
887 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
890 $group = $element = $qf->addGroup($check, $elementName, $label);
891 $optionEditKey = 'data-option-edit-path';
892 if (isset($customFieldAttributes[$optionEditKey])) {
893 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
896 if ($useRequired && !$search) {
897 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
902 // we should not build upload file in search mode
907 strtolower($field->html_type
),
911 $useRequired && !$search
913 $qf->addUploadElement($elementName);
916 case 'RichTextEditor':
918 'rows' => $field->note_rows
,
919 'cols' => $field->note_columns
,
920 'data-crm-custom' => $dataCrmCustomVal,
922 if ($field->text_length
) {
923 $attributes['maxlength'] = $field->text_length
;
925 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
928 case 'Autocomplete-Select':
929 static $customUrls = array();
930 // Fixme: why is this a string in the first place??
931 $attributes = array();
932 if ($field->attributes
) {
933 foreach (explode(' ', $field->attributes
) as $at) {
934 if (strpos($at, '=')) {
935 list($k, $v) = explode('=', $at);
936 $attributes[$k] = trim($v, ' "');
940 if ($field->data_type
== 'ContactReference') {
941 // break if contact does not have permission to access ContactReference
942 if (!CRM_Core_Permission
::check('access contact reference fields')) {
945 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
946 $attributes['data-api-entity'] = 'Contact';
947 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
949 $urlParams = "context=customfield&id={$field->id}";
950 $idOfelement = $elementName;
951 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
952 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
953 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
954 // rather than layering on more hacks.
955 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
956 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') +
1)), 0, -1);
958 $customUrls[$idOfelement] = CRM_Utils_System
::url('civicrm/ajax/contactref',
965 // FIXME: This won't work with customFieldOptions hook
966 $attributes +
= array(
967 'entity' => 'OptionValue',
968 'placeholder' => $placeholder,
969 'multiple' => $search,
971 'params' => array('option_group_id' => $field->option_group_id
, 'is_active' => 1),
974 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
977 $qf->assign('customUrls', $customUrls);
981 switch ($field->data_type
) {
983 // integers will have numeric rule applied to them.
984 if ($field->is_search_range
&& $search) {
985 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
986 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
988 elseif ($widget == 'Text') {
989 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
994 if ($field->is_search_range
&& $search) {
995 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
996 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
998 elseif ($widget == 'Text') {
999 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1004 if ($field->is_search_range
&& $search) {
1005 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1006 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1008 elseif ($widget == 'Text') {
1009 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1014 $element->setAttribute('class', "url");
1015 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1018 if ($field->is_view
&& !$search) {
1019 $qf->freeze($elementName);
1025 * Delete the Custom Field.
1027 * @param object $field
1030 public static function deleteField($field) {
1031 CRM_Utils_System
::flushCache();
1033 // first delete the custom option group and values associated with this field
1034 if ($field->option_group_id
) {
1035 //check if option group is related to any other field, if
1036 //not delete the option group and related option values
1037 self
::checkOptionGroup($field->option_group_id
);
1040 // next drop the column from the custom value table
1041 self
::createField($field, 'delete');
1044 CRM_Core_BAO_UFField
::delUFField($field->id
);
1045 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1047 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
1051 * @param string|int|array|null $value
1052 * @param CRM_Core_BAO_CustomField|int|array|string $field
1053 * @param int $entityId
1056 * @throws \Exception
1058 public static function displayValue($value, $field, $entityId = NULL) {
1059 $field = is_array($field) ?
$field['id'] : $field;
1060 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1063 throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1066 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1067 $field = self
::getFieldObject($fieldId);
1070 $fieldInfo = array('options' => $field->getOptions()) +
(array) $field;
1072 return self
::formatDisplayValue($value, $fieldInfo, $entityId);
1076 * Lower-level logic for rendering a custom field value
1078 * @param string|array $value
1079 * @param array $field
1080 * @param int|null $entityId
1084 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1086 if (self
::isSerialized($field) && !is_array($value)) {
1087 $value = CRM_Utils_Array
::explodePadded($value);
1090 if ($field['html_type'] == 'CheckBox' && $value) {
1091 $value = CRM_Utils_Array
::convertCheckboxFormatToArray($value);
1094 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1096 switch ($field['html_type']) {
1099 case 'Autocomplete-Select':
1101 case 'Select Country':
1102 case 'Select State/Province':
1104 case 'Multi-Select':
1105 case 'Multi-Select State/Province':
1106 case 'Multi-Select Country':
1107 if ($field['data_type'] == 'ContactReference' && $value) {
1108 if (is_numeric($value)) {
1109 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1115 elseif (is_array($value)) {
1117 foreach ($value as $key => $val) {
1118 $v[] = CRM_Utils_Array
::value($val, $field['options']);
1120 $display = implode(', ', $v);
1123 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1128 $customFormat = NULL;
1130 // FIXME: Are there any legitimate reasons why $value would be an array?
1131 // Or should we throw an exception here if it is?
1132 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1134 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1135 $format = CRM_Utils_Array
::value('date_format', $field);
1138 if (array_key_exists($format, $actualPHPFormats)) {
1139 $customTimeFormat = (array) $actualPHPFormats[$format];
1140 switch (CRM_Utils_Array
::value('time_format', $field)) {
1142 $customTimeFormat[] = 'g:iA';
1146 $customTimeFormat[] = 'G:i';
1150 //If time is not selected remove time from value.
1151 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1153 $customFormat = implode(" ", $customTimeFormat);
1156 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1160 // In the context of displaying a profile, show file/image
1163 if (CRM_Utils_Rule
::positiveInteger($value)) {
1167 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1169 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1171 $display = $url['file_url'];
1175 // In other contexts show a paperclip icon
1176 if (CRM_Utils_Rule
::integer($value)) {
1177 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1179 $file_description = '';
1181 $file_description = civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1183 catch (CiviCRM_API3_Exception
$dontcare) {
1187 $display = "{$icons[$value]}{$file_description}";
1190 //CRM-18396, if filename is passed instead
1198 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1202 $display = nl2br($display);
1206 if ($field['data_type'] == 'Money' && isset($value)) {
1207 // $value can also be an array(while using IN operator from search builder or api).
1208 foreach ((array) $value as $val) {
1209 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1211 $display = implode(', ', $disp);
1219 * Set default values for custom data used in profile.
1221 * @param int $customFieldId
1223 * @param string $elementName
1224 * Custom field name.
1225 * @param array $defaults
1226 * Associated array of fields.
1227 * @param int $contactId
1231 * @param mixed $value
1232 * If passed - dont fetch value from db,.
1233 * just format the given value
1235 public static function setProfileDefaults(
1243 //get the type of custom field
1244 $customField = new CRM_Core_BAO_CustomField();
1245 $customField->id
= $customFieldId;
1246 $customField->find(TRUE);
1249 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1250 $value = $customField->default_value
;
1254 if (!isset($value)) {
1255 $info = self
::getTableColumnGroup($customFieldId);
1256 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1257 $result = CRM_Core_DAO
::executeQuery($query);
1258 if ($result->fetch()) {
1259 $value = $result->value
;
1263 if ($customField->data_type
== 'Country') {
1265 $config = CRM_Core_Config
::singleton();
1266 if ($config->defaultContactCountry
) {
1267 $value = CRM_Core_BAO_Country
::defaultContactCountry();
1273 //set defaults if mode is registration
1274 if (!trim($value) &&
1276 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1278 $value = $customField->default_value
;
1281 if ($customField->data_type
== 'Money' && isset($value)) {
1282 $value = number_format($value, 2);
1284 switch ($customField->html_type
) {
1286 case 'Multi-Select':
1287 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1288 $defaults[$elementName] = array();
1289 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1290 substr($value, 1, -1)
1292 foreach ($customOption as $val) {
1293 if (in_array($val['value'], $checkedValue)) {
1294 if ($customField->html_type
== 'CheckBox') {
1295 $defaults[$elementName][$val['value']] = 1;
1297 elseif ($customField->html_type
== 'Multi-Select') {
1298 $defaults[$elementName][$val['value']] = $val['value'];
1305 $defaults[$elementName] = $value;
1312 * @param int $contactID
1314 * @param int $fileID
1315 * @param bool $absolute
1317 * @param string $multiRecordWhereClause
1321 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1324 $params = array('id' => $cfID);
1325 $defaults = array();
1326 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1327 $columnName = $defaults['column_name'];
1329 //table name of custom data
1330 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1331 $defaults['custom_group_id'],
1335 //query to fetch id from civicrm_file
1336 if ($multiRecordWhereClause) {
1337 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1340 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1342 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1347 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1352 $result['file_id'] = $fileID;
1354 if ($fileType == 'image/jpeg' ||
1355 $fileType == 'image/pjpeg' ||
1356 $fileType == 'image/gif' ||
1357 $fileType == 'image/x-png' ||
1358 $fileType == 'image/png'
1360 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1365 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1366 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1367 $url = CRM_Utils_System
::url('civicrm/file',
1368 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1369 $absolute, NULL, TRUE, TRUE
1371 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1373 // for non image files
1375 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1379 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1380 $url = CRM_Utils_System
::url('civicrm/file',
1381 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1382 $absolute, NULL, TRUE, TRUE
1384 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1392 * Format custom fields before inserting.
1394 * @param int $customFieldId
1396 * @param array $customFormatted
1398 * @param mixed $value
1399 * Value of custom field.
1400 * @param string $customFieldExtend
1401 * Custom field extends.
1402 * @param int $customValueId
1403 * Custom option value id.
1404 * @param int $entityId
1405 * Entity id (contribution, membership...).
1406 * @param bool $inline
1407 * Consider inline custom groups only.
1408 * @param bool $checkPermission
1409 * If false, do not include permissioning clause.
1410 * @param bool $includeViewOnly
1411 * If true, fields marked 'View Only' are included. Required for APIv3.
1413 * @return array|NULL
1414 * formatted custom field array
1416 public static function formatCustomField(
1417 $customFieldId, &$customFormatted, $value,
1418 $customFieldExtend, $customValueId = NULL,
1421 $checkPermission = TRUE,
1422 $includeViewOnly = FALSE
1424 //get the custom fields for the entity
1425 //subtype and basic type
1426 $customDataSubType = NULL;
1427 if ($customFieldExtend) {
1428 // This is the case when getFieldsForImport() requires fields
1429 // of subtype and its parent.CRM-5143
1430 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1431 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1432 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1433 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1434 if (is_array($customFieldExtend)) {
1435 $customFieldExtend = array_unique(array_values($customFieldExtend));
1440 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1450 if (!array_key_exists($customFieldId, $customFields)) {
1454 // return if field is a 'code' field
1455 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1459 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1461 if (!$customValueId &&
1462 // we always create new entites for is_multiple unless specified
1463 !$customFields[$customFieldId]['is_multiple'] &&
1469 WHERE entity_id={$entityId}";
1471 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1474 //fix checkbox, now check box always submits values
1475 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1477 // Note that only during merge this is not an array, and you can directly use value
1478 if (is_array($value)) {
1479 $selectedValues = array();
1480 foreach ($value as $selId => $val) {
1482 $selectedValues[] = $selId;
1485 if (!empty($selectedValues)) {
1486 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1488 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1497 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select') {
1499 $value = CRM_Utils_Array
::implodePadded($value);
1506 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1507 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1509 $customFields[$customFieldId]['data_type'] == 'String' &&
1510 !empty($customFields[$customFieldId]['text_length']) &&
1513 // lets make sure that value is less than the length, else we'll
1514 // be losing some data, CRM-7481
1515 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1516 // need to do a few things here
1518 // 1. lets find a new length
1519 $newLength = $customFields[$customFieldId]['text_length'];
1520 $minLength = strlen($value);
1521 while ($newLength < $minLength) {
1522 $newLength = $newLength * 2;
1525 // set the custom field meta data to have a length larger than value
1526 // alter the custom value table column to match this length
1527 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1532 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1533 if (!CRM_Utils_System
::isNull($value)) {
1534 $format = $customFields[$customFieldId]['date_format'];
1535 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1540 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1541 $customFields[$customFieldId]['data_type'] == 'Money'
1547 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1548 $value = CRM_Utils_Rule
::cleanMoney($value);
1552 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1553 $customFields[$customFieldId]['data_type'] == 'Country'
1563 if ($customFields[$customFieldId]['data_type'] == 'File') {
1564 if (empty($value)) {
1568 $config = CRM_Core_Config
::singleton();
1570 // If we are already passing the file id as a value then retrieve and set the file data
1571 if (CRM_Utils_Rule
::integer($value)) {
1572 $fileDAO = new CRM_Core_DAO_File();
1573 $fileDAO->id
= $value;
1574 $fileDAO->find(TRUE);
1577 $fName = $fileDAO->uri
;
1578 $mimeType = $fileDAO->mime_type
;
1582 $fName = $value['name'];
1583 $mimeType = $value['type'];
1586 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1588 // rename this file to go into the secure directory only if
1589 // user has uploaded new file not existing verfied on the basis of $fileID
1590 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1591 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1594 if ($customValueId && empty($fileID)) {
1599 $params = array(1 => array($customValueId, 'Integer'));
1600 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1603 $fileDAO = new CRM_Core_DAO_File();
1606 $fileDAO->id
= $fileID;
1609 $fileDAO->uri
= $filename;
1610 $fileDAO->mime_type
= $mimeType;
1611 $fileDAO->upload_date
= date('YmdHis');
1613 $fileID = $fileDAO->id
;
1617 if (!is_array($customFormatted)) {
1618 $customFormatted = array();
1621 if (!array_key_exists($customFieldId, $customFormatted)) {
1622 $customFormatted[$customFieldId] = array();
1626 if ($customValueId) {
1627 $index = $customValueId;
1630 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1631 $customFormatted[$customFieldId][$index] = array();
1633 $customFormatted[$customFieldId][$index] = array(
1634 'id' => $customValueId > 0 ?
$customValueId : NULL,
1636 'type' => $customFields[$customFieldId]['data_type'],
1637 'custom_field_id' => $customFieldId,
1638 'custom_group_id' => $groupID,
1639 'table_name' => $tableName,
1640 'column_name' => $columnName,
1641 'file_id' => $fileID,
1642 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1645 //we need to sort so that custom fields are created in the order of entry
1646 krsort($customFormatted[$customFieldId]);
1647 return $customFormatted;
1651 * Get default custom table schema.
1653 * @param array $params
1657 public static function defaultCustomTableSchema($params) {
1658 // add the id and extends_id
1660 'name' => $params['name'],
1661 'is_multiple' => $params['is_multiple'],
1662 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1666 'type' => 'int unsigned',
1669 'attributes' => 'AUTO_INCREMENT',
1670 'comment' => 'Default MySQL primary key',
1673 'name' => 'entity_id',
1674 'type' => 'int unsigned',
1676 'comment' => 'Table that this extends',
1677 'fk_table_name' => $params['extends_name'],
1678 'fk_field_name' => 'id',
1679 'fk_attributes' => 'ON DELETE CASCADE',
1684 if (!$params['is_multiple']) {
1685 $table['indexes'] = array(
1688 'field_name_1' => 'entity_id',
1696 * Create custom field.
1698 * @param CRM_Core_DAO_CustomField $field
1699 * @param string $operation
1701 public static function createField($field, $operation) {
1702 $sql = str_repeat(' ', 8);
1703 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1704 $sql .= "ALTER TABLE " . $tableName;
1705 $sql .= self
::getAlterFieldSQL($field, $operation);
1707 // CRM-7007: do not i18n-rewrite this query
1708 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1710 $config = CRM_Core_Config
::singleton();
1711 if ($config->logging
) {
1712 // CRM-16717 not sure why this was originally limited to add.
1713 // For example custom tables can have field length changes - which need to flow through to logging.
1714 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1715 if ($operation === 'add' ||
$operation === 'modify') {
1716 $logging = new CRM_Logging_Schema();
1717 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name
]]);
1721 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
1725 * @param CRM_Core_DAO_CustomField $field
1726 * @param string $operation
1730 public static function getAlterFieldSQL($field, $operation) {
1731 $indexExist = $operation === 'add' ?
FALSE : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $field->id
, 'is_searchable');
1732 $params = self
::prepareCreateParams($field, $operation);
1733 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1734 // a function only used by Custom Field creation...
1735 $params['required'] = FALSE;
1736 return CRM_Core_BAO_SchemaHandler
::getFieldAlterSQL($params, $indexExist);
1740 * Determine whether it would be safe to move a field.
1742 * @param int $fieldID
1743 * FK to civicrm_custom_field.
1744 * @param int $newGroupID
1745 * FK to civicrm_custom_group.
1748 * array(string) or TRUE
1750 public static function _moveFieldValidate($fieldID, $newGroupID) {
1753 $field = new CRM_Core_DAO_CustomField();
1754 $field->id
= $fieldID;
1755 if (!$field->find(TRUE)) {
1756 $errors['fieldID'] = 'Invalid ID for custom field';
1760 $oldGroup = new CRM_Core_DAO_CustomGroup();
1761 $oldGroup->id
= $field->custom_group_id
;
1762 if (!$oldGroup->find(TRUE)) {
1763 $errors['fieldID'] = 'Invalid ID for old custom group';
1767 $newGroup = new CRM_Core_DAO_CustomGroup();
1768 $newGroup->id
= $newGroupID;
1769 if (!$newGroup->find(TRUE)) {
1770 $errors['newGroupID'] = 'Invalid ID for new custom group';
1776 FROM civicrm_custom_field a
1777 INNER JOIN civicrm_custom_field b
1779 AND a.label = b.label
1780 AND b.custom_group_id = %2
1783 1 => array($field->id
, 'Integer'),
1784 2 => array($newGroup->id
, 'Integer'),
1786 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1788 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1791 $tableName = $oldGroup->table_name
;
1792 $columnName = $field->column_name
;
1797 WHERE $columnName is not null
1799 $count = CRM_Core_DAO
::singleValueQuery($query);
1803 FROM civicrm_custom_group
1804 WHERE id IN ( %1, %2 )
1807 1 => array($oldGroup->id
, 'Integer'),
1808 2 => array($newGroup->id
, 'Integer'),
1811 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1813 while ($dao->fetch()) {
1814 $extends[] = $dao->extends;
1816 if ($extends[0] != $extends[1]) {
1817 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1821 return empty($errors) ?
TRUE : $errors;
1825 * Move a custom data field from one group (table) to another.
1827 * @param int $fieldID
1828 * FK to civicrm_custom_field.
1829 * @param int $newGroupID
1830 * FK to civicrm_custom_group.
1832 public static function moveField($fieldID, $newGroupID) {
1833 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1834 if (TRUE !== $validation) {
1835 CRM_Core_Error
::fatal(implode(' ', $validation));
1837 $field = new CRM_Core_DAO_CustomField();
1838 $field->id
= $fieldID;
1841 $newGroup = new CRM_Core_DAO_CustomGroup();
1842 $newGroup->id
= $newGroupID;
1843 $newGroup->find(TRUE);
1845 $oldGroup = new CRM_Core_DAO_CustomGroup();
1846 $oldGroup->id
= $field->custom_group_id
;
1847 $oldGroup->find(TRUE);
1850 $add->custom_group_id
= $newGroup->id
;
1851 self
::createField($add, 'add');
1853 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1854 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1855 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1857 CRM_Core_DAO
::executeQuery($sql);
1860 $del->custom_group_id
= $oldGroup->id
;
1861 self
::createField($del, 'delete');
1865 CRM_Utils_System
::flushCache();
1869 * Create an option value for a custom field option group ID.
1871 * @param array $params
1872 * @param string $value
1873 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1874 * @param string $optionName
1875 * @param string $dataType
1877 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $optionName, $dataType) {
1878 if (strlen(trim($value))) {
1879 $optionValue = new CRM_Core_DAO_OptionValue();
1880 $optionValue->option_group_id
= $optionGroup->id
;
1881 $optionValue->label
= $params['option_label'][$optionName];
1882 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$optionName]);
1883 switch ($dataType) {
1885 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1889 $optionValue->value
= intval($value);
1893 $optionValue->value
= floatval($value);
1897 $optionValue->value
= trim($value);
1900 $optionValue->weight
= $params['option_weight'][$optionName];
1901 $optionValue->is_active
= CRM_Utils_Array
::value($optionName, $params['option_status'], FALSE);
1902 $optionValue->save();
1907 * Prepare for the create operation.
1909 * Munge params, create the option values if needed.
1911 * This could be called by a single create or a batchCreate.
1913 * @param array $params
1917 protected static function prepareCreate($params) {
1918 $op = empty($params['id']) ?
'create' : 'edit';
1919 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1920 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1921 if ($op === 'create') {
1922 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1923 if (!isset($params['column_name'])) {
1924 // if add mode & column_name not present, calculate it.
1925 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1927 if (!isset($params['name'])) {
1928 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1932 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1938 switch (CRM_Utils_Array
::value('html_type', $params)) {
1940 if (empty($params['date_format'])) {
1941 $config = CRM_Core_Config
::singleton();
1942 $params['date_format'] = $config->dateInputFormat
;
1947 case 'Multi-Select':
1948 if (isset($params['default_checkbox_option'])) {
1949 $tempArray = array_keys($params['default_checkbox_option']);
1951 foreach ($tempArray as $k => $v) {
1952 if ($params['option_value'][$v]) {
1953 $defaultArray[] = $params['option_value'][$v];
1957 if (!empty($defaultArray)) {
1958 // also add the separator before and after the value per new convention (CRM-1604)
1959 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1963 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
1965 $params['default_value'] = $params['option_value'][$params['default_option']];
1971 $htmlType = CRM_Utils_Array
::value('html_type', $params);
1972 $dataType = CRM_Utils_Array
::value('data_type', $params);
1973 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1975 // create any option group & values if required
1976 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)
1978 //CRM-16659: if option_value then create an option group for this custom field.
1979 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
1980 // first create an option group for this custom group
1981 $optionGroup = new CRM_Core_DAO_OptionGroup();
1982 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
1983 $optionGroup->title
= $params['label'];
1984 $optionGroup->is_active
= 1;
1985 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1986 $optionGroup->is_reserved
= 0;
1987 $optionGroup->data_type
= $dataType;
1988 $optionGroup->save();
1989 $params['option_group_id'] = $optionGroup->id
;
1990 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1991 foreach ($params['option_value'] as $k => $v) {
1992 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1998 // check for orphan option groups
1999 if (!empty($params['option_group_id'])) {
2000 if (!empty($params['id'])) {
2001 self
::fixOptionGroups($params['id'], $params['option_group_id']);
2004 // if we do not have a default value
2005 // retrieve it from one of the other custom fields which use this option group
2006 if (empty($params['default_value'])) {
2007 //don't insert only value separator as default value, CRM-4579
2008 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
2012 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2016 $params['default_value'] = $defaultValue;
2021 // since we need to save option group id :)
2022 if (!isset($params['attributes']) && strtolower($htmlType) == 'textarea') {
2023 $params['attributes'] = 'rows=4, cols=60';
2029 * Create database entry for custom field and related option groups.
2031 * @param array $params
2033 * @return CRM_Core_DAO_CustomField
2035 protected static function createCustomFieldRecord($params) {
2036 $transaction = new CRM_Core_Transaction();
2037 $params = self
::prepareCreate($params);
2039 $customField = new CRM_Core_DAO_CustomField();
2040 $customField->copyValues($params);
2041 $customField->save();
2043 //create/drop the index when we toggle the is_searchable flag
2044 $op = empty($params['id']) ?
'add' : 'modify';
2045 if ($op !== 'modify') {
2046 if ($params['is_append_field_id_to_column_name']) {
2047 $params['column_name'] .= "_{$customField->id}";
2049 $customField->column_name
= $params['column_name'];
2050 $customField->save();
2053 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
2054 $transaction->commit();
2056 // make sure all values are present in the object for further processing
2057 $customField->find(TRUE);
2058 return $customField;
2062 * Move custom data from one contact to another.
2064 * This is currently the start of a refactoring. The theory is each
2065 * entity could have a 'move' function with a DAO default one to fall back on.
2067 * At the moment this only does a small part of the process - ie deleting a file field that
2068 * is about to be overwritten. However, the goal is the whole process around the move for
2069 * custom data should be in here.
2071 * This is currently called by the merge class but it makes sense that api could
2072 * expose move actions as moving (e.g) contributions feels like a common
2073 * ask that should be handled by the form layer.
2075 * @param int $oldContactID
2076 * @param int $newContactID
2077 * @param int[] $fieldIDs
2078 * Optional list field ids to move.
2080 * @throws \CiviCRM_API3_Exception
2081 * @throws \Exception
2083 public function move($oldContactID, $newContactID, $fieldIDs) {
2084 if (empty($fieldIDs)) {
2087 $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'];
2089 foreach ($fieldIDs as $fieldID) {
2090 $return[] = 'custom_' . $fieldID;
2092 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2093 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2095 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2096 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2097 $fieldTypesNotHandledInMergeAttempt = ['File'];
2098 foreach ($fields as $field) {
2099 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2100 if ($field['data_type'] === 'File' && !$isMultiple) {
2101 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2102 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2104 if (!empty($oldContact['custom_' . $field['id']])) {
2105 CRM_Core_DAO
::executeQuery("
2106 UPDATE civicrm_entity_file
2107 SET entity_id = $newContactID
2108 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2112 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2113 CRM_Core_DAO
::executeQuery(
2114 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2115 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2116 ON DUPLICATE KEY UPDATE
2117 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2124 * Get the database table name and column name for a custom field.
2126 * @param int $fieldID
2127 * The fieldID of the custom field.
2128 * @param bool $force
2129 * Force the sql to be run again (primarily used for tests).
2132 * fatal is fieldID does not exists, else array of tableName, columnName
2133 * @throws \Exception
2135 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2136 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2137 $cache = CRM_Utils_Cache
::singleton();
2138 $fieldValues = $cache->get($cacheKey);
2139 if (empty($fieldValues) ||
$force) {
2141 SELECT cg.table_name, cf.column_name, cg.id
2142 FROM civicrm_custom_group cg,
2143 civicrm_custom_field cf
2144 WHERE cf.custom_group_id = cg.id
2146 $params = array(1 => array($fieldID, 'Integer'));
2147 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2149 if (!$dao->fetch()) {
2150 CRM_Core_Error
::fatal();
2152 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2153 $cache->set($cacheKey, $fieldValues);
2155 return $fieldValues;
2159 * Get custom option groups.
2161 * @deprecated Use the API OptionGroup.get
2163 * @param array $includeFieldIds
2164 * Ids of custom fields for which option groups must be included.
2166 * Currently this is required in the cases where option groups are to be included
2167 * for inactive fields : CRM-5369
2171 public static function customOptionGroup($includeFieldIds = NULL) {
2172 static $customOptionGroup = NULL;
2174 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2175 if ($cacheKey == 'force') {
2176 $customOptionGroup[$cacheKey] = NULL;
2179 if (empty($customOptionGroup[$cacheKey])) {
2180 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2182 //support for single as well as array format.
2183 if (!empty($includeFieldIds)) {
2184 if (is_array($includeFieldIds)) {
2185 $includeFieldIds = implode(',', $includeFieldIds);
2187 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2191 SELECT g.id, g.title
2192 FROM civicrm_option_group g
2193 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2194 WHERE {$whereClause}";
2196 $dao = CRM_Core_DAO
::executeQuery($query);
2197 while ($dao->fetch()) {
2198 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2202 return $customOptionGroup[$cacheKey];
2206 * Get defaults for new entity.
2210 public static function getDefaults() {
2212 'is_required' => FALSE,
2213 'is_searchable' => FALSE,
2214 'in_selector' => FALSE,
2215 'is_search_range' => FALSE,
2216 //CRM-15792 - Custom field gets disabled if is_active not set
2217 // this would ideally be a mysql default.
2218 'is_active' => TRUE,
2224 * Fix orphan groups.
2226 * @param int $customFieldId
2228 * @param int $optionGroupId
2231 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2232 // check if option group belongs to any custom Field else delete
2233 // get the current option group
2234 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2238 // get the updated option group
2239 // if both are same return
2240 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2244 // check if option group is related to any other field
2245 self
::checkOptionGroup($currentOptionGroupId);
2249 * Check if option group is related to more than one custom field.
2251 * @param int $optionGroupId
2254 public static function checkOptionGroup($optionGroupId) {
2257 FROM civicrm_custom_field
2258 WHERE option_group_id = {$optionGroupId}";
2260 $count = CRM_Core_DAO
::singleValueQuery($query);
2263 //delete the option group
2264 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2269 * Get option group default.
2271 * @param int $optionGroupId
2272 * @param string $htmlType
2274 * @return null|string
2276 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2278 SELECT default_value, html_type
2279 FROM civicrm_custom_field
2280 WHERE option_group_id = {$optionGroupId}
2281 AND default_value IS NOT NULL
2282 ORDER BY html_type";
2284 $dao = CRM_Core_DAO
::executeQuery($query);
2285 $defaultValue = NULL;
2286 $defaultHTMLType = NULL;
2287 while ($dao->fetch()) {
2288 if ($dao->html_type
== $htmlType) {
2289 return $dao->default_value
;
2291 if ($defaultValue == NULL) {
2292 $defaultValue = $dao->default_value
;
2293 $defaultHTMLType = $dao->html_type
;
2297 // some conversions are needed if either the old or new has a html type which has potential
2298 // multiple default values.
2299 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2300 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2302 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2304 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2305 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2307 $defaultValue = substr($defaultValue, 1, -1);
2308 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2309 substr($defaultValue, 1, -1)
2311 $defaultValue = $values[0];
2314 return $defaultValue;
2318 * Post process function.
2320 * @param array $params
2321 * @param int $entityID
2322 * @param string $customFieldExtends
2323 * @param bool $inline
2324 * @param bool $checkPermissions
2328 public static function postProcess(
2331 $customFieldExtends,
2333 $checkPermissions = TRUE
2335 $customData = array();
2337 foreach ($params as $key => $value) {
2338 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2340 // for autocomplete transfer hidden value instead of label
2341 if ($params[$key] && isset($params[$key . '_id'])) {
2342 $value = $params[$key . '_id'];
2345 // we need to append time with date
2346 if ($params[$key] && isset($params[$key . '_time'])) {
2347 $value .= ' ' . $params[$key . '_time'];
2350 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2353 $customFieldExtends,
2354 $customFieldInfo[1],
2365 * Get custom field ID from field/group name/title.
2367 * @param string $fieldName Field name or label
2368 * @param string|null $groupName (Optional) Group name or label
2369 * @param bool $fullString Whether to return "custom_123" or "123"
2371 * @return string|int|null
2372 * @throws \CiviCRM_API3_Exception
2374 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2375 $cacheKey = $groupName . '.' . $fieldName;
2376 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2377 $customFieldParams = [
2378 'name' => $fieldName,
2379 'label' => $fieldName,
2380 'options' => ['or' => [["name", "label"]]],
2384 $customFieldParams['custom_group_id.name'] = $groupName;
2385 $customFieldParams['custom_group_id.title'] = $groupName;
2386 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2389 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2391 if (empty($field['id'])) {
2392 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2393 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2396 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2397 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2402 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2404 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2408 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2414 public static function getNameFromID($ids) {
2415 if (is_array($ids)) {
2416 $ids = implode(',', $ids);
2419 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2420 FROM civicrm_custom_field f
2421 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2422 WHERE f.id IN ($ids)";
2424 $dao = CRM_Core_DAO
::executeQuery($sql);
2426 while ($dao->fetch()) {
2427 $result[$dao->id
] = array(
2428 'field_name' => $dao->field_name
,
2429 'field_label' => $dao->field_label
,
2430 'group_name' => $dao->group_name
,
2431 'group_title' => $dao->group_title
,
2438 * Validate custom data.
2440 * @param array $params
2441 * Custom data submitted.
2442 * ie array( 'custom_1' => 'validate me' );
2445 * validation errors.
2447 public static function validateCustomData($params) {
2449 if (!is_array($params) ||
empty($params)) {
2453 //pick up profile fields.
2454 $profileFields = array();
2455 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2457 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2459 CRM_Core_Action
::VIEW
2463 //lets start w/ params.
2464 foreach ($params as $key => $value) {
2465 $customFieldID = self
::getKeyID($key);
2466 if (!$customFieldID) {
2470 //load the structural info for given field.
2471 $field = new CRM_Core_DAO_CustomField();
2472 $field->id
= $customFieldID;
2473 if (!$field->find(TRUE)) {
2476 $dataType = $field->data_type
;
2478 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2479 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2480 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2482 $fieldTitle = $field->label
;
2485 //no need to validate.
2486 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2490 //lets validate first for required field.
2491 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2492 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2496 //now time to take care of custom field form rules.
2497 $ruleName = $errorMsg = NULL;
2498 switch ($dataType) {
2500 $ruleName = 'integer';
2501 $errorMsg = ts('%1 must be an integer (whole number).',
2502 array(1 => $fieldTitle)
2507 $ruleName = 'money';
2508 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2509 array(1 => $fieldTitle)
2514 $ruleName = 'numeric';
2515 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2516 array(1 => $fieldTitle)
2521 $ruleName = 'wikiURL';
2522 $errorMsg = ts('%1 must be valid Website.',
2523 array(1 => $fieldTitle)
2528 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2530 $funName = "CRM_Utils_Rule::{$ruleName}";
2531 if (is_callable($funName)) {
2532 $valid = call_user_func($funName, $value);
2535 $errors[$key] = $errorMsg;
2544 * Is this field a multi record field.
2546 * @param int $customId
2550 public static function isMultiRecordField($customId) {
2551 $isMultipleWithGid = FALSE;
2552 if (!is_numeric($customId)) {
2553 $customId = self
::getKeyID($customId);
2555 if (is_numeric($customId)) {
2556 $sql = "SELECT cg.id cgId
2557 FROM civicrm_custom_group cg
2558 INNER JOIN civicrm_custom_field cf
2559 ON cg.id = cf.custom_group_id
2560 WHERE cf.id = %1 AND cg.is_multiple = 1";
2561 $params[1] = array($customId, 'Integer');
2562 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2563 if ($dao->fetch()) {
2565 $isMultipleWithGid = $dao->cgId
;
2570 return $isMultipleWithGid;
2574 * Does this field type have any select options?
2576 * @param array $field
2580 public static function hasOptions($field) {
2581 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2582 $field = (array) $field;
2583 // This will include boolean fields with Yes/No options.
2584 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2587 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2588 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2589 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2592 if (strpos($field['html_type'], 'Select') !== FALSE) {
2595 return !empty($field['option_group_id']);
2599 * Does this field store a serialized string?
2601 * @param array $field
2605 public static function isSerialized($field) {
2606 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2607 $field = (array) $field;
2608 // 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.
2609 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2613 * Get api entity for this field
2617 public function getEntity() {
2618 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2619 return in_array($entity, array('Individual', 'Household', 'Organization')) ?
'Contact' : $entity;
2623 * Set pseudoconstant properties for field metadata.
2625 * @param array $field
2626 * @param string|null $optionGroupName
2628 private static function getOptionsForField(&$field, $optionGroupName) {
2629 if ($optionGroupName) {
2630 $field['pseudoconstant'] = array(
2631 'optionGroupName' => $optionGroupName,
2632 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2635 elseif ($field['data_type'] == 'Boolean') {
2636 $field['pseudoconstant'] = array(
2637 'callback' => 'CRM_Core_SelectValues::boolean',
2640 elseif ($field['data_type'] == 'Country') {
2641 $field['pseudoconstant'] = array(
2642 'table' => 'civicrm_country',
2643 'keyColumn' => 'id',
2644 'labelColumn' => 'name',
2645 'nameColumn' => 'iso_code',
2648 elseif ($field['data_type'] == 'StateProvince') {
2649 $field['pseudoconstant'] = array(
2650 'table' => 'civicrm_state_province',
2651 'keyColumn' => 'id',
2652 'labelColumn' => 'name',
2658 * @param CRM_Core_DAO_CustomField $field
2659 * @param 'add|modify' $operation
2663 protected static function prepareCreateParams($field, $operation) {
2664 $tableName = CRM_Core_DAO
::getFieldValue(
2665 'CRM_Core_DAO_CustomGroup',
2666 $field->custom_group_id
,
2671 'table_name' => $tableName,
2672 'operation' => $operation,
2673 'name' => $field->column_name
,
2674 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2678 'required' => $field->is_required
,
2679 'searchable' => $field->is_searchable
,
2682 if ($operation == 'delete') {
2683 $fkName = "{$tableName}_{$field->column_name}";
2684 if (strlen($fkName) >= 48) {
2685 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2687 $params['fkName'] = $fkName;
2689 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
2690 $params['fk_table_name'] = 'civicrm_country';
2691 $params['fk_field_name'] = 'id';
2692 $params['fk_attributes'] = 'ON DELETE SET NULL';
2694 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
2695 $params['type'] = 'varchar(255)';
2697 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
2698 $params['fk_table_name'] = 'civicrm_state_province';
2699 $params['fk_field_name'] = 'id';
2700 $params['fk_attributes'] = 'ON DELETE SET NULL';
2702 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
2703 $params['type'] = 'varchar(255)';
2705 elseif ($field->data_type
== 'File') {
2706 $params['fk_table_name'] = 'civicrm_file';
2707 $params['fk_field_name'] = 'id';
2708 $params['fk_attributes'] = 'ON DELETE SET NULL';
2710 elseif ($field->data_type
== 'ContactReference') {
2711 $params['fk_table_name'] = 'civicrm_contact';
2712 $params['fk_field_name'] = 'id';
2713 $params['fk_attributes'] = 'ON DELETE SET NULL';
2715 if (isset($field->default_value
)) {
2716 $params['default'] = "'{$field->default_value}'";