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, CRM_Utils_Array
::value('triggerRebuild', $params, TRUE));
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) {
182 foreach ($bulkParams as $fieldParams) {
183 $params = array_merge($defaults, $fieldParams);
184 $operation = empty($params['id']) ?
'add' : 'modify';
185 $customField = self
::createCustomFieldRecord($params);
186 $fieldSQL = self
::getAlterFieldSQL($customField, $operation);
187 if (!isset($params['custom_group_id'])) {
188 $params['custom_group_id'] = civicrm_api3('CustomField', 'getvalue', ['id' => $customField->id
, 'return' => 'custom_group_id']);
190 if (!isset($params['table_name'])) {
191 if (!isset($tables[$params['custom_group_id']])) {
192 $tables[$params['custom_group_id']] = civicrm_api3('CustomGroup', 'getvalue', [
193 'id' => $params['custom_group_id'],
194 'return' => 'table_name',
197 $params['table_name'] = $tables[$params['custom_group_id']];
199 $sql[$params['table_name']][] = $fieldSQL;
200 $customFields[] = $customField;
202 foreach ($sql as $tableName => $statements) {
203 // CRM-7007: do not i18n-rewrite this query
204 CRM_Core_DAO
::executeQuery("ALTER TABLE $tableName " . implode(', ', $statements), [], TRUE, NULL, FALSE, FALSE);
205 Civi
::service('sql_triggers')->rebuild($params['table_name'], TRUE);
207 CRM_Utils_System
::flushCache();
208 foreach ($customFields as $customField) {
209 CRM_Utils_Hook
::post($operation === 'add' ?
'create' : 'edit', 'CustomField', $customField->id
, $customField);
214 * Fetch object based on array of properties.
216 * @param array $params
217 * (reference ) an assoc array of name/value pairs.
218 * @param array $defaults
219 * (reference ) an assoc array to hold the flattened values.
221 * @return CRM_Core_DAO_CustomField
223 public static function retrieve(&$params, &$defaults) {
224 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
228 * Update the is_active flag in the db.
231 * Id of the database record.
232 * @param bool $is_active
233 * Value we want to set the is_active field.
236 * true if we found and updated the object, else false
238 public static function setIsActive($id, $is_active) {
240 CRM_Utils_System
::flushCache();
242 //enable-disable CustomField
243 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
244 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
248 * Get the field title.
256 public static function getTitle($id) {
257 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
261 * @param string $context
264 public function getOptions($context = NULL) {
265 CRM_Core_DAO
::buildOptionsContext($context);
270 if (!$this->data_type ||
!$this->custom_group_id
) {
274 // This will hold the list of options in format key => label
277 if (!empty($this->option_group_id
)) {
278 $options = CRM_Core_OptionGroup
::valuesByID(
279 $this->option_group_id
,
284 !($context == 'validate' ||
$context == 'get')
287 elseif ($this->data_type
=== 'StateProvince') {
288 $options = CRM_Core_PseudoConstant
::stateProvince();
290 elseif ($this->data_type
=== 'Country') {
291 $options = $context == 'validate' ? CRM_Core_PseudoConstant
::countryIsoCode() : CRM_Core_PseudoConstant
::country();
293 elseif ($this->data_type
=== 'Boolean') {
294 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
296 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
297 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, array('context' => $context));
302 * Store and return an array of all active custom fields.
304 * @param string $customDataType
305 * Type of Custom Data; 'ANY' is a synonym for "all contact data types".
306 * @param bool $showAll
307 * If true returns all fields (includes disabled fields).
308 * @param bool $inline
309 * If true returns all inline fields (includes disabled fields).
310 * @param int $customDataSubType
311 * Custom Data sub type value.
312 * @param int $customDataSubName
313 * Custom Data sub name value.
314 * @param bool $onlyParent
315 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
316 * @param bool $onlySubType
317 * Return only custom data for subtype.
318 * @param bool $checkPermission
319 * If false, do not include permissioning clause.
322 * an array of active custom fields.
324 public static function &getFields(
325 $customDataType = 'Individual',
328 $customDataSubType = NULL,
329 $customDataSubName = NULL,
331 $onlySubType = FALSE,
332 $checkPermission = TRUE
334 if (empty($customDataType)) {
335 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
337 if ($customDataType === 'ANY') {
338 // NULL should have been respected but the line above broke that.
339 // boo for us not having enough unit tests back them.
340 $customDataType = NULL;
342 if ($customDataType && !is_array($customDataType)) {
344 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
345 // This is the case when getFieldsForImport() requires fields
346 // limited strictly to a subtype.
347 $customDataSubType = $customDataType;
348 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
352 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
353 // this makes the method flexible to support retrieving fields
354 // for multiple extends value.
355 $customDataType = array($customDataType);
359 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
361 if (is_array($customDataType)) {
362 $cacheKey = implode('_', $customDataType);
365 $cacheKey = $customDataType;
368 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
369 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
370 $cacheKey .= $showAll ?
'_1' : '_0';
371 $cacheKey .= $inline ?
'_1_' : '_0_';
372 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
373 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
374 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
375 $cacheKey .= '_' . CRM_Core_Config
::domainID() . '_';
377 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
379 // also get the permission stuff here
380 if ($checkPermission) {
381 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
386 $permissionClause = '(1)';
389 // lets md5 permission clause and take first 8 characters
390 $cacheKey .= substr(md5($permissionClause), 0, 8);
392 if (strlen($cacheKey) > 40) {
393 $cacheKey = md5($cacheKey);
396 if (!self
::$_importFields ||
397 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
399 if (!self
::$_importFields) {
400 self
::$_importFields = array();
403 // check if we can retrieve from database cache
404 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
406 if ($fields === NULL) {
407 $cfTable = self
::getTableName();
410 if (is_array($customDataType)) {
412 foreach ($customDataType as $dataType) {
413 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
414 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
415 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
418 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
420 $value = $value ?
$value . ", {$val}" : $val;
424 $extends = "AND $cgTable.extends IN ( $value ) ";
428 if (!empty($customDataType) && empty($extends)) {
429 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
430 self
::$_importFields[$cacheKey] = array();
431 return self
::$_importFields[$cacheKey];
435 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
438 $query = "SELECT $cfTable.id, $cfTable.label,
442 $cfTable.default_value,
443 $cfTable.options_per_line, $cfTable.text_length,
444 $cfTable.custom_group_id,
445 $cfTable.is_required,
446 $cfTable.column_name,
447 $cgTable.extends, $cfTable.is_search_range,
448 $cgTable.extends_entity_column_value,
449 $cgTable.extends_entity_column_id,
451 $cfTable.option_group_id,
452 $cfTable.date_format,
453 $cfTable.time_format,
454 $cgTable.is_multiple,
456 og.name as option_group_name
459 ON $cfTable.custom_group_id = $cgTable.id
460 LEFT JOIN civicrm_option_group og
461 ON $cfTable.option_group_id = og.id
465 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
469 $query .= " AND $cgTable.style = 'Inline' ";
472 //get the custom fields for specific type in
473 //combination with fields those support any type.
474 if (!empty($customDataSubType)) {
475 $subtypeClause = array();
476 foreach ($customDataSubType as $subtype) {
477 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($subtype, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
;
478 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
481 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
483 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
486 if ($customDataSubName) {
487 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
490 // also get the permission stuff here
491 if ($checkPermission) {
492 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
497 $permissionClause = '(1)';
500 $query .= " $extends AND $permissionClause
501 ORDER BY $cgTable.weight, $cgTable.title,
502 $cfTable.weight, $cfTable.label";
504 $dao = CRM_Core_DAO
::executeQuery($query);
507 while (($dao->fetch()) != NULL) {
508 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
509 $fields[$dao->id
]['id'] = $dao->id
;
510 $fields[$dao->id
]['label'] = $dao->label
;
511 // This seems broken, but not in a new way.
512 $fields[$dao->id
]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
513 // To support the consolidation of various functions & their expectations.
514 $fields[$dao->id
]['title'] = $dao->label
;
515 $fields[$dao->id
]['custom_field_id'] = $dao->id
;
516 $fields[$dao->id
]['groupTitle'] = $dao->title
;
517 $fields[$dao->id
]['data_type'] = $dao->data_type
;
518 $fields[$dao->id
]['name'] = 'custom_' . $dao->id
;
519 $fields[$dao->id
]['type'] = CRM_Utils_Array
::value($dao->data_type
, self
::dataToType());
520 $fields[$dao->id
]['html_type'] = $dao->html_type
;
521 $fields[$dao->id
]['default_value'] = $dao->default_value
;
522 $fields[$dao->id
]['text_length'] = $dao->text_length
;
523 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
524 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
525 $fields[$dao->id
]['extends'] = $dao->extends;
526 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
527 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
528 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
529 $fields[$dao->id
]['is_view'] = $dao->is_view
;
530 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
531 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
532 $fields[$dao->id
]['date_format'] = $dao->date_format
;
533 $fields[$dao->id
]['time_format'] = $dao->time_format
;
534 $fields[$dao->id
]['is_required'] = $dao->is_required
;
535 $fields[$dao->id
]['table_name'] = $dao->table_name
;
536 $fields[$dao->id
]['column_name'] = $dao->column_name
;
537 $fields[$dao->id
]['where'] = $dao->table_name
. '.' . $dao->column_name
;
538 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
539 $fields[$dao->id
]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery
::$extendsMap) ? CRM_Core_BAO_CustomQuery
::$extendsMap[$dao->extends] : '';
540 if (in_array($dao->extends, CRM_Contact_BAO_ContactType
::subTypes())) {
541 // if $extends is a subtype, refer contact table
542 $fields[$dao->id
]['extends_table'] = 'civicrm_contact';
544 // Search table is used by query object searches..
545 $fields[$dao->id
]['search_table'] = ($fields[$dao->id
]['extends_table'] == 'civicrm_contact') ?
'contact_a' : $fields[$dao->id
]['extends_table'];
546 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
550 CRM_Core_BAO_Cache
::setItem($fields,
552 "custom importableFields $cacheKey"
555 self
::$_importFields[$cacheKey] = $fields;
558 return self
::$_importFields[$cacheKey];
562 * Return the field ids and names (with groups) for import purpose.
564 * @param int|string $contactType Contact type
565 * @param bool $showAll
566 * If true returns all fields (includes disabled fields).
567 * @param bool $onlyParent
568 * Return fields ONLY related to basic types.
569 * @param bool $search
570 * When called from search and multiple records need to be returned.
571 * @param bool $checkPermission
572 * If false, do not include permissioning clause.
574 * @param bool $withMultiple
578 public static function getFieldsForImport(
579 $contactType = 'Individual',
583 $checkPermission = TRUE,
584 $withMultiple = FALSE
586 // Note: there are situations when we want getFieldsForImport() return fields related
587 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
588 $fields = &self
::getFields($contactType,
598 $importableFields = [];
599 foreach ($fields as $id => $values) {
600 // for now we should not allow multiple fields in profile / export etc, hence unsetting
602 (!empty($values['is_multiple']) && !$withMultiple)
607 /* generate the key for the fields array */
610 $importableFields[$key] = $values;
611 $importableFields[$key]['import'] = 1;
614 return $importableFields;
618 * Get the field id from an import key.
628 public static function getKeyID($key, $all = FALSE) {
630 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
637 CRM_Utils_Array
::value(2, $match),
641 return $all ?
array(NULL, NULL) : NULL;
645 * Use the cache to get all values of a specific custom field.
647 * @param int $fieldID
648 * The custom field ID.
650 * @return CRM_Core_BAO_CustomField
653 public static function getFieldObject($fieldID) {
654 $field = new CRM_Core_BAO_CustomField();
656 // check if we can get the field values from the system cache
657 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
658 $cache = CRM_Utils_Cache
::singleton();
659 $fieldValues = $cache->get($cacheKey);
660 if (empty($fieldValues)) {
661 $field->id
= $fieldID;
662 if (!$field->find(TRUE)) {
663 CRM_Core_Error
::fatal();
666 $fieldValues = array();
667 CRM_Core_DAO
::storeValues($field, $fieldValues);
669 $cache->set($cacheKey, $fieldValues);
672 $field->copyValues($fieldValues);
679 * Add a custom field to an existing form.
681 * @param CRM_Core_Form $qf
682 * Form object (reference).
683 * @param string $elementName
684 * Name of the custom field.
685 * @param int $fieldId
686 * @param bool $useRequired
687 * True if required else false.
688 * @param bool $search
689 * True if used for search else false.
690 * @param string $label
691 * Label for custom field.
692 * @return \HTML_QuickForm_Element|null
693 * @throws \CiviCRM_API3_Exception
695 public static function addQuickFormElement(
696 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
698 $field = self
::getFieldObject($fieldId);
699 $widget = $field->html_type
;
701 $customFieldAttributes = array();
703 // Custom field HTML should indicate group+field name
704 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
705 $dataCrmCustomVal = $groupName . ':' . $field->name
;
706 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
707 $field->attributes
.= $dataCrmCustomAttr;
709 // Fixed for Issue CRM-2183
710 if ($widget == 'TextArea' && $search) {
714 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
716 // FIXME: Why are select state/country separate widget types?
717 $isSelect = (in_array($widget, array(
720 'Select State/Province',
721 'Multi-Select State/Province',
723 'Multi-Select Country',
729 $options = $field->getOptions($search ?
'search' : 'create');
731 // Consolidate widget types to simplify the below switch statement
732 if ($search ||
(strpos($widget, 'Select') !== FALSE)) {
736 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
737 $selectAttributes = array('class' => 'crm-select2');
739 // Search field is always multi-select
740 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
741 $selectAttributes['class'] .= ' huge';
742 $selectAttributes['multiple'] = 'multiple';
743 $selectAttributes['placeholder'] = $placeholder;
746 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
747 $isSupportedWidget = in_array($widget, ['Select', 'Radio']);
748 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
749 if ($field->option_group_id
&& !$search && $isSelect && $canEditOptions) {
750 $customFieldAttributes +
= array(
751 'data-api-entity' => $field->getEntity(),
752 'data-api-field' => 'custom_' . $field->id
,
753 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
755 $selectAttributes +
= $customFieldAttributes;
759 $rangeDataTypes = ['Int', 'Float', 'Money'];
761 if (!isset($label)) {
762 $label = $field->label
;
765 // at some point in time we might want to split the below into small functions
770 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
771 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
772 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
775 if ($field->text_length
) {
776 $field->attributes
.= ' maxlength=' . $field->text_length
;
777 if ($field->text_length
< 20) {
778 $field->attributes
.= ' size=' . $field->text_length
;
781 $element = $qf->add('text', $elementName, $label,
783 $useRequired && !$search
789 $attributes = $dataCrmCustomAttr;
790 if ($field->note_rows
) {
791 $attributes .= 'rows=' . $field->note_rows
;
794 $attributes .= 'rows=4';
796 if ($field->note_columns
) {
797 $attributes .= ' cols=' . $field->note_columns
;
800 $attributes .= ' cols=60';
802 if ($field->text_length
) {
803 $attributes .= ' maxlength=' . $field->text_length
;
805 $element = $qf->add('textarea',
809 $useRequired && !$search
814 $attr = array('data-crm-custom' => $dataCrmCustomVal);
815 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
816 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
817 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
820 'date' => $field->date_format
,
821 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
822 //CRM-18487 - max date should be the last date of the year.
823 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
824 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
826 if ($field->is_search_range
&& $search) {
827 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
828 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
831 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
836 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
837 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
838 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
842 parse_str($field->attributes
, $radioAttributes);
843 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
845 foreach ($options as $v => $l) {
846 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
848 $element = $qf->addGroup($choice, $elementName, $label);
849 $optionEditKey = 'data-option-edit-path';
850 if (isset($selectAttributes[$optionEditKey])) {
851 $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
854 if ($useRequired && !$search) {
855 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
858 $element->setAttribute('allowClear', TRUE);
863 // For all select elements
865 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
866 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
867 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
870 if (empty($selectAttributes['multiple'])) {
871 $options = array('' => $placeholder) +
$options;
873 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
875 // Add and/or option for fields that store multiple values
876 if ($search && self
::isSerialized($field)) {
879 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
880 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
882 $qf->addGroup($operators, $elementName . '_operator');
883 $qf->setDefaults(array($elementName . '_operator' => 'or'));
890 foreach ($options as $v => $l) {
891 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
894 $group = $element = $qf->addGroup($check, $elementName, $label);
895 $optionEditKey = 'data-option-edit-path';
896 if (isset($customFieldAttributes[$optionEditKey])) {
897 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
900 if ($useRequired && !$search) {
901 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
906 // we should not build upload file in search mode
911 strtolower($field->html_type
),
915 $useRequired && !$search
917 $qf->addUploadElement($elementName);
920 case 'RichTextEditor':
922 'rows' => $field->note_rows
,
923 'cols' => $field->note_columns
,
924 'data-crm-custom' => $dataCrmCustomVal,
926 if ($field->text_length
) {
927 $attributes['maxlength'] = $field->text_length
;
929 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
932 case 'Autocomplete-Select':
933 static $customUrls = array();
934 // Fixme: why is this a string in the first place??
935 $attributes = array();
936 if ($field->attributes
) {
937 foreach (explode(' ', $field->attributes
) as $at) {
938 if (strpos($at, '=')) {
939 list($k, $v) = explode('=', $at);
940 $attributes[$k] = trim($v, ' "');
944 if ($field->data_type
== 'ContactReference') {
945 // break if contact does not have permission to access ContactReference
946 if (!CRM_Core_Permission
::check('access contact reference fields')) {
949 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
950 $attributes['data-api-entity'] = 'Contact';
951 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
953 $urlParams = "context=customfield&id={$field->id}";
954 $idOfelement = $elementName;
955 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
956 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
957 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
958 // rather than layering on more hacks.
959 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
960 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') +
1)), 0, -1);
962 $customUrls[$idOfelement] = CRM_Utils_System
::url('civicrm/ajax/contactref',
969 // FIXME: This won't work with customFieldOptions hook
970 $attributes +
= array(
971 'entity' => 'OptionValue',
972 'placeholder' => $placeholder,
973 'multiple' => $search,
975 'params' => array('option_group_id' => $field->option_group_id
, 'is_active' => 1),
978 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
981 $qf->assign('customUrls', $customUrls);
985 switch ($field->data_type
) {
987 // integers will have numeric rule applied to them.
988 if ($field->is_search_range
&& $search) {
989 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
990 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
992 elseif ($widget == 'Text') {
993 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
998 if ($field->is_search_range
&& $search) {
999 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1000 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1002 elseif ($widget == 'Text') {
1003 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1008 if ($field->is_search_range
&& $search) {
1009 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1010 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1012 elseif ($widget == 'Text') {
1013 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1018 $element->setAttribute('class', "url");
1019 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1022 if ($field->is_view
&& !$search) {
1023 $qf->freeze($elementName);
1029 * Delete the Custom Field.
1031 * @param object $field
1034 public static function deleteField($field) {
1035 CRM_Utils_System
::flushCache();
1037 // first delete the custom option group and values associated with this field
1038 if ($field->option_group_id
) {
1039 //check if option group is related to any other field, if
1040 //not delete the option group and related option values
1041 self
::checkOptionGroup($field->option_group_id
);
1044 // next drop the column from the custom value table
1045 self
::createField($field, 'delete');
1048 CRM_Core_BAO_UFField
::delUFField($field->id
);
1049 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1051 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
1055 * @param string|int|array|null $value
1056 * @param CRM_Core_BAO_CustomField|int|array|string $field
1057 * @param int $entityId
1060 * @throws \Exception
1062 public static function displayValue($value, $field, $entityId = NULL) {
1063 $field = is_array($field) ?
$field['id'] : $field;
1064 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1067 throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1070 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1071 $field = self
::getFieldObject($fieldId);
1074 $fieldInfo = array('options' => $field->getOptions()) +
(array) $field;
1076 return self
::formatDisplayValue($value, $fieldInfo, $entityId);
1080 * Lower-level logic for rendering a custom field value
1082 * @param string|array $value
1083 * @param array $field
1084 * @param int|null $entityId
1088 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1090 if (self
::isSerialized($field) && !is_array($value)) {
1091 $value = CRM_Utils_Array
::explodePadded($value);
1094 if ($field['html_type'] == 'CheckBox' && $value) {
1095 $value = CRM_Utils_Array
::convertCheckboxFormatToArray($value);
1098 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1100 switch ($field['html_type']) {
1103 case 'Autocomplete-Select':
1105 case 'Select Country':
1106 case 'Select State/Province':
1108 case 'Multi-Select':
1109 case 'Multi-Select State/Province':
1110 case 'Multi-Select Country':
1111 if ($field['data_type'] == 'ContactReference' && $value) {
1112 if (is_numeric($value)) {
1113 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1119 elseif (is_array($value)) {
1121 foreach ($value as $key => $val) {
1122 $v[] = CRM_Utils_Array
::value($val, $field['options']);
1124 $display = implode(', ', $v);
1127 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1132 $customFormat = NULL;
1134 // FIXME: Are there any legitimate reasons why $value would be an array?
1135 // Or should we throw an exception here if it is?
1136 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1138 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1139 $format = CRM_Utils_Array
::value('date_format', $field);
1142 if (array_key_exists($format, $actualPHPFormats)) {
1143 $customTimeFormat = (array) $actualPHPFormats[$format];
1144 switch (CRM_Utils_Array
::value('time_format', $field)) {
1146 $customTimeFormat[] = 'g:iA';
1150 $customTimeFormat[] = 'G:i';
1154 //If time is not selected remove time from value.
1155 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1157 $customFormat = implode(" ", $customTimeFormat);
1160 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1164 // In the context of displaying a profile, show file/image
1167 if (CRM_Utils_Rule
::positiveInteger($value)) {
1171 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1173 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1175 $display = $url['file_url'];
1179 // In other contexts show a paperclip icon
1180 if (CRM_Utils_Rule
::integer($value)) {
1181 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1182 $display = $icons[$value] . civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1185 //CRM-18396, if filename is passed instead
1193 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1197 $display = nl2br($display);
1201 if ($field['data_type'] == 'Money' && isset($value)) {
1202 // $value can also be an array(while using IN operator from search builder or api).
1203 foreach ((array) $value as $val) {
1204 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1206 $display = implode(', ', $disp);
1214 * Set default values for custom data used in profile.
1216 * @param int $customFieldId
1218 * @param string $elementName
1219 * Custom field name.
1220 * @param array $defaults
1221 * Associated array of fields.
1222 * @param int $contactId
1226 * @param mixed $value
1227 * If passed - dont fetch value from db,.
1228 * just format the given value
1230 public static function setProfileDefaults(
1238 //get the type of custom field
1239 $customField = new CRM_Core_BAO_CustomField();
1240 $customField->id
= $customFieldId;
1241 $customField->find(TRUE);
1244 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1245 $value = $customField->default_value
;
1249 if (!isset($value)) {
1250 $info = self
::getTableColumnGroup($customFieldId);
1251 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1252 $result = CRM_Core_DAO
::executeQuery($query);
1253 if ($result->fetch()) {
1254 $value = $result->value
;
1258 if ($customField->data_type
== 'Country') {
1260 $config = CRM_Core_Config
::singleton();
1261 if ($config->defaultContactCountry
) {
1262 $value = $config->defaultContactCountry();
1268 //set defaults if mode is registration
1269 if (!trim($value) &&
1271 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1273 $value = $customField->default_value
;
1276 if ($customField->data_type
== 'Money' && isset($value)) {
1277 $value = number_format($value, 2);
1279 switch ($customField->html_type
) {
1281 case 'Multi-Select':
1282 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1283 $defaults[$elementName] = array();
1284 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1285 substr($value, 1, -1)
1287 foreach ($customOption as $val) {
1288 if (in_array($val['value'], $checkedValue)) {
1289 if ($customField->html_type
== 'CheckBox') {
1290 $defaults[$elementName][$val['value']] = 1;
1292 elseif ($customField->html_type
== 'Multi-Select') {
1293 $defaults[$elementName][$val['value']] = $val['value'];
1300 $defaults[$elementName] = $value;
1307 * @param int $contactID
1309 * @param int $fileID
1310 * @param bool $absolute
1312 * @param string $multiRecordWhereClause
1316 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1319 $params = array('id' => $cfID);
1320 $defaults = array();
1321 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1322 $columnName = $defaults['column_name'];
1324 //table name of custom data
1325 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1326 $defaults['custom_group_id'],
1330 //query to fetch id from civicrm_file
1331 if ($multiRecordWhereClause) {
1332 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1335 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1337 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1342 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1347 $result['file_id'] = $fileID;
1349 if ($fileType == 'image/jpeg' ||
1350 $fileType == 'image/pjpeg' ||
1351 $fileType == 'image/gif' ||
1352 $fileType == 'image/x-png' ||
1353 $fileType == 'image/png'
1355 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1360 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1361 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1362 $url = CRM_Utils_System
::url('civicrm/file',
1363 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1364 $absolute, NULL, TRUE, TRUE
1366 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1368 // for non image files
1370 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1374 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1375 $url = CRM_Utils_System
::url('civicrm/file',
1376 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1377 $absolute, NULL, TRUE, TRUE
1379 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1387 * Format custom fields before inserting.
1389 * @param int $customFieldId
1391 * @param array $customFormatted
1393 * @param mixed $value
1394 * Value of custom field.
1395 * @param string $customFieldExtend
1396 * Custom field extends.
1397 * @param int $customValueId
1398 * Custom option value id.
1399 * @param int $entityId
1400 * Entity id (contribution, membership...).
1401 * @param bool $inline
1402 * Consider inline custom groups only.
1403 * @param bool $checkPermission
1404 * If false, do not include permissioning clause.
1405 * @param bool $includeViewOnly
1406 * If true, fields marked 'View Only' are included. Required for APIv3.
1408 * @return array|NULL
1409 * formatted custom field array
1411 public static function formatCustomField(
1412 $customFieldId, &$customFormatted, $value,
1413 $customFieldExtend, $customValueId = NULL,
1416 $checkPermission = TRUE,
1417 $includeViewOnly = FALSE
1419 //get the custom fields for the entity
1420 //subtype and basic type
1421 $customDataSubType = NULL;
1422 if ($customFieldExtend) {
1423 // This is the case when getFieldsForImport() requires fields
1424 // of subtype and its parent.CRM-5143
1425 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1426 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1427 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1428 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1429 if (is_array($customFieldExtend)) {
1430 $customFieldExtend = array_unique(array_values($customFieldExtend));
1435 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1445 if (!array_key_exists($customFieldId, $customFields)) {
1449 // return if field is a 'code' field
1450 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1454 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1456 if (!$customValueId &&
1457 // we always create new entites for is_multiple unless specified
1458 !$customFields[$customFieldId]['is_multiple'] &&
1464 WHERE entity_id={$entityId}";
1466 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1469 //fix checkbox, now check box always submits values
1470 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1472 // Note that only during merge this is not an array, and you can directly use value
1473 if (is_array($value)) {
1474 $selectedValues = array();
1475 foreach ($value as $selId => $val) {
1477 $selectedValues[] = $selId;
1480 if (!empty($selectedValues)) {
1481 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1483 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1492 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select') {
1494 $value = CRM_Utils_Array
::implodePadded($value);
1501 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1502 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1504 $customFields[$customFieldId]['data_type'] == 'String' &&
1505 !empty($customFields[$customFieldId]['text_length']) &&
1508 // lets make sure that value is less than the length, else we'll
1509 // be losing some data, CRM-7481
1510 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1511 // need to do a few things here
1513 // 1. lets find a new length
1514 $newLength = $customFields[$customFieldId]['text_length'];
1515 $minLength = strlen($value);
1516 while ($newLength < $minLength) {
1517 $newLength = $newLength * 2;
1520 // set the custom field meta data to have a length larger than value
1521 // alter the custom value table column to match this length
1522 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1527 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1528 if (!CRM_Utils_System
::isNull($value)) {
1529 $format = $customFields[$customFieldId]['date_format'];
1530 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1535 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1536 $customFields[$customFieldId]['data_type'] == 'Money'
1542 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1543 $value = CRM_Utils_Rule
::cleanMoney($value);
1547 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1548 $customFields[$customFieldId]['data_type'] == 'Country'
1558 if ($customFields[$customFieldId]['data_type'] == 'File') {
1559 if (empty($value)) {
1563 $config = CRM_Core_Config
::singleton();
1565 // If we are already passing the file id as a value then retrieve and set the file data
1566 if (CRM_Utils_Rule
::integer($value)) {
1567 $fileDAO = new CRM_Core_DAO_File();
1568 $fileDAO->id
= $value;
1569 $fileDAO->find(TRUE);
1572 $fName = $fileDAO->uri
;
1573 $mimeType = $fileDAO->mime_type
;
1577 $fName = $value['name'];
1578 $mimeType = $value['type'];
1581 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1583 // rename this file to go into the secure directory only if
1584 // user has uploaded new file not existing verfied on the basis of $fileID
1585 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1586 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1589 if ($customValueId && empty($fileID)) {
1594 $params = array(1 => array($customValueId, 'Integer'));
1595 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1598 $fileDAO = new CRM_Core_DAO_File();
1601 $fileDAO->id
= $fileID;
1604 $fileDAO->uri
= $filename;
1605 $fileDAO->mime_type
= $mimeType;
1606 $fileDAO->upload_date
= date('YmdHis');
1608 $fileID = $fileDAO->id
;
1612 if (!is_array($customFormatted)) {
1613 $customFormatted = array();
1616 if (!array_key_exists($customFieldId, $customFormatted)) {
1617 $customFormatted[$customFieldId] = array();
1621 if ($customValueId) {
1622 $index = $customValueId;
1625 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1626 $customFormatted[$customFieldId][$index] = array();
1628 $customFormatted[$customFieldId][$index] = array(
1629 'id' => $customValueId > 0 ?
$customValueId : NULL,
1631 'type' => $customFields[$customFieldId]['data_type'],
1632 'custom_field_id' => $customFieldId,
1633 'custom_group_id' => $groupID,
1634 'table_name' => $tableName,
1635 'column_name' => $columnName,
1636 'file_id' => $fileID,
1637 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1640 //we need to sort so that custom fields are created in the order of entry
1641 krsort($customFormatted[$customFieldId]);
1642 return $customFormatted;
1646 * Get default custom table schema.
1648 * @param array $params
1652 public static function defaultCustomTableSchema($params) {
1653 // add the id and extends_id
1655 'name' => $params['name'],
1656 'is_multiple' => $params['is_multiple'],
1657 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1661 'type' => 'int unsigned',
1664 'attributes' => 'AUTO_INCREMENT',
1665 'comment' => 'Default MySQL primary key',
1668 'name' => 'entity_id',
1669 'type' => 'int unsigned',
1671 'comment' => 'Table that this extends',
1672 'fk_table_name' => $params['extends_name'],
1673 'fk_field_name' => 'id',
1674 'fk_attributes' => 'ON DELETE CASCADE',
1679 if (!$params['is_multiple']) {
1680 $table['indexes'] = array(
1683 'field_name_1' => 'entity_id',
1691 * Create custom field.
1693 * @param CRM_Core_DAO_CustomField $field
1694 * @param string $operation
1695 * @param bool $triggerRebuild
1697 public static function createField($field, $operation, $triggerRebuild = TRUE) {
1698 $sql = str_repeat(' ', 8);
1699 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1700 $sql .= "ALTER TABLE " . $tableName;
1701 $sql .= self
::getAlterFieldSQL($field, $operation);
1703 // CRM-7007: do not i18n-rewrite this query
1704 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1706 $config = CRM_Core_Config
::singleton();
1707 if ($config->logging
) {
1708 // CRM-16717 not sure why this was originally limited to add.
1709 // For example custom tables can have field length changes - which need to flow through to logging.
1710 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1711 if ($operation === 'add' ||
$operation === 'modify') {
1712 $logging = new CRM_Logging_Schema();
1713 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name
]]);
1717 if ($triggerRebuild) {
1718 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
1724 * @param CRM_Core_DAO_CustomField $field
1725 * @param string $operation
1729 public static function getAlterFieldSQL($field, $operation) {
1730 $indexExist = $operation === 'add' ?
FALSE : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $field->id
, 'is_searchable');
1731 $params = self
::prepareCreateParams($field, $operation);
1732 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1733 // a function only used by Custom Field creation...
1734 $params['required'] = FALSE;
1735 return CRM_Core_BAO_SchemaHandler
::getFieldAlterSQL($params, $indexExist);
1739 * Determine whether it would be safe to move a field.
1741 * @param int $fieldID
1742 * FK to civicrm_custom_field.
1743 * @param int $newGroupID
1744 * FK to civicrm_custom_group.
1747 * array(string) or TRUE
1749 public static function _moveFieldValidate($fieldID, $newGroupID) {
1752 $field = new CRM_Core_DAO_CustomField();
1753 $field->id
= $fieldID;
1754 if (!$field->find(TRUE)) {
1755 $errors['fieldID'] = 'Invalid ID for custom field';
1759 $oldGroup = new CRM_Core_DAO_CustomGroup();
1760 $oldGroup->id
= $field->custom_group_id
;
1761 if (!$oldGroup->find(TRUE)) {
1762 $errors['fieldID'] = 'Invalid ID for old custom group';
1766 $newGroup = new CRM_Core_DAO_CustomGroup();
1767 $newGroup->id
= $newGroupID;
1768 if (!$newGroup->find(TRUE)) {
1769 $errors['newGroupID'] = 'Invalid ID for new custom group';
1775 FROM civicrm_custom_field a
1776 INNER JOIN civicrm_custom_field b
1778 AND a.label = b.label
1779 AND b.custom_group_id = %2
1782 1 => array($field->id
, 'Integer'),
1783 2 => array($newGroup->id
, 'Integer'),
1785 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1787 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1790 $tableName = $oldGroup->table_name
;
1791 $columnName = $field->column_name
;
1796 WHERE $columnName is not null
1798 $count = CRM_Core_DAO
::singleValueQuery($query);
1802 FROM civicrm_custom_group
1803 WHERE id IN ( %1, %2 )
1806 1 => array($oldGroup->id
, 'Integer'),
1807 2 => array($newGroup->id
, 'Integer'),
1810 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1812 while ($dao->fetch()) {
1813 $extends[] = $dao->extends;
1815 if ($extends[0] != $extends[1]) {
1816 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1820 return empty($errors) ?
TRUE : $errors;
1824 * Move a custom data field from one group (table) to another.
1826 * @param int $fieldID
1827 * FK to civicrm_custom_field.
1828 * @param int $newGroupID
1829 * FK to civicrm_custom_group.
1831 public static function moveField($fieldID, $newGroupID) {
1832 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1833 if (TRUE !== $validation) {
1834 CRM_Core_Error
::fatal(implode(' ', $validation));
1836 $field = new CRM_Core_DAO_CustomField();
1837 $field->id
= $fieldID;
1840 $newGroup = new CRM_Core_DAO_CustomGroup();
1841 $newGroup->id
= $newGroupID;
1842 $newGroup->find(TRUE);
1844 $oldGroup = new CRM_Core_DAO_CustomGroup();
1845 $oldGroup->id
= $field->custom_group_id
;
1846 $oldGroup->find(TRUE);
1849 $add->custom_group_id
= $newGroup->id
;
1850 self
::createField($add, 'add');
1852 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1853 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1854 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1856 CRM_Core_DAO
::executeQuery($sql);
1859 $del->custom_group_id
= $oldGroup->id
;
1860 self
::createField($del, 'delete');
1864 CRM_Utils_System
::flushCache();
1868 * Create an option value for a custom field option group ID.
1870 * @param array $params
1871 * @param string $value
1872 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1873 * @param string $optionName
1874 * @param string $dataType
1876 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $optionName, $dataType) {
1877 if (strlen(trim($value))) {
1878 $optionValue = new CRM_Core_DAO_OptionValue();
1879 $optionValue->option_group_id
= $optionGroup->id
;
1880 $optionValue->label
= $params['option_label'][$optionName];
1881 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$optionName]);
1882 switch ($dataType) {
1884 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1888 $optionValue->value
= intval($value);
1892 $optionValue->value
= floatval($value);
1896 $optionValue->value
= trim($value);
1899 $optionValue->weight
= $params['option_weight'][$optionName];
1900 $optionValue->is_active
= CRM_Utils_Array
::value($optionName, $params['option_status'], FALSE);
1901 $optionValue->save();
1906 * Prepare for the create operation.
1908 * Munge params, create the option values if needed.
1910 * This could be called by a single create or a batchCreate.
1912 * @param array $params
1916 protected static function prepareCreate($params) {
1917 $op = empty($params['id']) ?
'create' : 'edit';
1918 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1919 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1920 if ($op === 'create') {
1921 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1922 if (!isset($params['column_name'])) {
1923 // if add mode & column_name not present, calculate it.
1924 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1926 if (!isset($params['name'])) {
1927 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1931 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1937 switch (CRM_Utils_Array
::value('html_type', $params)) {
1939 if (empty($params['date_format'])) {
1940 $config = CRM_Core_Config
::singleton();
1941 $params['date_format'] = $config->dateInputFormat
;
1946 case 'Multi-Select':
1947 if (isset($params['default_checkbox_option'])) {
1948 $tempArray = array_keys($params['default_checkbox_option']);
1950 foreach ($tempArray as $k => $v) {
1951 if ($params['option_value'][$v]) {
1952 $defaultArray[] = $params['option_value'][$v];
1956 if (!empty($defaultArray)) {
1957 // also add the separator before and after the value per new convention (CRM-1604)
1958 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1962 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
1964 $params['default_value'] = $params['option_value'][$params['default_option']];
1970 $htmlType = CRM_Utils_Array
::value('html_type', $params);
1971 $dataType = CRM_Utils_Array
::value('data_type', $params);
1972 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1974 // create any option group & values if required
1975 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)
1977 //CRM-16659: if option_value then create an option group for this custom field.
1978 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
1979 // first create an option group for this custom group
1980 $optionGroup = new CRM_Core_DAO_OptionGroup();
1981 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
1982 $optionGroup->title
= $params['label'];
1983 $optionGroup->is_active
= 1;
1984 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1985 $optionGroup->is_reserved
= 0;
1986 $optionGroup->data_type
= $dataType;
1987 $optionGroup->save();
1988 $params['option_group_id'] = $optionGroup->id
;
1989 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1990 foreach ($params['option_value'] as $k => $v) {
1991 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1997 // check for orphan option groups
1998 if (!empty($params['option_group_id'])) {
1999 if (!empty($params['id'])) {
2000 self
::fixOptionGroups($params['id'], $params['option_group_id']);
2003 // if we do not have a default value
2004 // retrieve it from one of the other custom fields which use this option group
2005 if (empty($params['default_value'])) {
2006 //don't insert only value separator as default value, CRM-4579
2007 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
2011 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2015 $params['default_value'] = $defaultValue;
2020 // since we need to save option group id :)
2021 if (!isset($params['attributes']) && strtolower($htmlType) == 'textarea') {
2022 $params['attributes'] = 'rows=4, cols=60';
2028 * Create database entry for custom field and related option groups.
2030 * @param array $params
2032 * @return CRM_Core_DAO_CustomField
2034 protected static function createCustomFieldRecord($params) {
2035 $transaction = new CRM_Core_Transaction();
2036 $params = self
::prepareCreate($params);
2038 $customField = new CRM_Core_DAO_CustomField();
2039 $customField->copyValues($params);
2040 $customField->save();
2042 //create/drop the index when we toggle the is_searchable flag
2043 $op = empty($params['id']) ?
'add' : 'modify';
2044 if ($op !== 'modify') {
2045 if ($params['is_append_field_id_to_column_name']) {
2046 $params['column_name'] .= "_{$customField->id}";
2048 $customField->column_name
= $params['column_name'];
2049 $customField->save();
2052 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
2053 $transaction->commit();
2055 // make sure all values are present in the object for further processing
2056 $customField->find(TRUE);
2057 return $customField;
2061 * Move custom data from one contact to another.
2063 * This is currently the start of a refactoring. The theory is each
2064 * entity could have a 'move' function with a DAO default one to fall back on.
2066 * At the moment this only does a small part of the process - ie deleting a file field that
2067 * is about to be overwritten. However, the goal is the whole process around the move for
2068 * custom data should be in here.
2070 * This is currently called by the merge class but it makes sense that api could
2071 * expose move actions as moving (e.g) contributions feels like a common
2072 * ask that should be handled by the form layer.
2074 * @param int $oldContactID
2075 * @param int $newContactID
2076 * @param int[] $fieldIDs
2077 * Optional list field ids to move.
2079 * @throws \CiviCRM_API3_Exception
2080 * @throws \Exception
2082 public function move($oldContactID, $newContactID, $fieldIDs) {
2083 if (empty($fieldIDs)) {
2086 $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'];
2088 foreach ($fieldIDs as $fieldID) {
2089 $return[] = 'custom_' . $fieldID;
2091 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2092 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2094 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2095 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2096 $fieldTypesNotHandledInMergeAttempt = ['File'];
2097 foreach ($fields as $field) {
2098 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2099 if ($field['data_type'] === 'File' && !$isMultiple) {
2100 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2101 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2103 if (!empty($oldContact['custom_' . $field['id']])) {
2104 CRM_Core_DAO
::executeQuery("
2105 UPDATE civicrm_entity_file
2106 SET entity_id = $newContactID
2107 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2111 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2112 CRM_Core_DAO
::executeQuery(
2113 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2114 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2115 ON DUPLICATE KEY UPDATE
2116 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2123 * Get the database table name and column name for a custom field.
2125 * @param int $fieldID
2126 * The fieldID of the custom field.
2127 * @param bool $force
2128 * Force the sql to be run again (primarily used for tests).
2131 * fatal is fieldID does not exists, else array of tableName, columnName
2132 * @throws \Exception
2134 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2135 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2136 $cache = CRM_Utils_Cache
::singleton();
2137 $fieldValues = $cache->get($cacheKey);
2138 if (empty($fieldValues) ||
$force) {
2140 SELECT cg.table_name, cf.column_name, cg.id
2141 FROM civicrm_custom_group cg,
2142 civicrm_custom_field cf
2143 WHERE cf.custom_group_id = cg.id
2145 $params = array(1 => array($fieldID, 'Integer'));
2146 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2148 if (!$dao->fetch()) {
2149 CRM_Core_Error
::fatal();
2151 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2152 $cache->set($cacheKey, $fieldValues);
2154 return $fieldValues;
2158 * Get custom option groups.
2160 * @deprecated Use the API OptionGroup.get
2162 * @param array $includeFieldIds
2163 * Ids of custom fields for which option groups must be included.
2165 * Currently this is required in the cases where option groups are to be included
2166 * for inactive fields : CRM-5369
2170 public static function customOptionGroup($includeFieldIds = NULL) {
2171 static $customOptionGroup = NULL;
2173 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2174 if ($cacheKey == 'force') {
2175 $customOptionGroup[$cacheKey] = NULL;
2178 if (empty($customOptionGroup[$cacheKey])) {
2179 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2181 //support for single as well as array format.
2182 if (!empty($includeFieldIds)) {
2183 if (is_array($includeFieldIds)) {
2184 $includeFieldIds = implode(',', $includeFieldIds);
2186 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2190 SELECT g.id, g.title
2191 FROM civicrm_option_group g
2192 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2193 WHERE {$whereClause}";
2195 $dao = CRM_Core_DAO
::executeQuery($query);
2196 while ($dao->fetch()) {
2197 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2201 return $customOptionGroup[$cacheKey];
2205 * Get defaults for new entity.
2209 public static function getDefaults() {
2211 'is_required' => FALSE,
2212 'is_searchable' => FALSE,
2213 'in_selector' => FALSE,
2214 'is_search_range' => FALSE,
2215 //CRM-15792 - Custom field gets disabled if is_active not set
2216 // this would ideally be a mysql default.
2217 'is_active' => TRUE,
2223 * Fix orphan groups.
2225 * @param int $customFieldId
2227 * @param int $optionGroupId
2230 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2231 // check if option group belongs to any custom Field else delete
2232 // get the current option group
2233 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2237 // get the updated option group
2238 // if both are same return
2239 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2243 // check if option group is related to any other field
2244 self
::checkOptionGroup($currentOptionGroupId);
2248 * Check if option group is related to more than one custom field.
2250 * @param int $optionGroupId
2253 public static function checkOptionGroup($optionGroupId) {
2256 FROM civicrm_custom_field
2257 WHERE option_group_id = {$optionGroupId}";
2259 $count = CRM_Core_DAO
::singleValueQuery($query);
2262 //delete the option group
2263 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2268 * Get option group default.
2270 * @param int $optionGroupId
2271 * @param string $htmlType
2273 * @return null|string
2275 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2277 SELECT default_value, html_type
2278 FROM civicrm_custom_field
2279 WHERE option_group_id = {$optionGroupId}
2280 AND default_value IS NOT NULL
2281 ORDER BY html_type";
2283 $dao = CRM_Core_DAO
::executeQuery($query);
2284 $defaultValue = NULL;
2285 $defaultHTMLType = NULL;
2286 while ($dao->fetch()) {
2287 if ($dao->html_type
== $htmlType) {
2288 return $dao->default_value
;
2290 if ($defaultValue == NULL) {
2291 $defaultValue = $dao->default_value
;
2292 $defaultHTMLType = $dao->html_type
;
2296 // some conversions are needed if either the old or new has a html type which has potential
2297 // multiple default values.
2298 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2299 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2301 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2303 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2304 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2306 $defaultValue = substr($defaultValue, 1, -1);
2307 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2308 substr($defaultValue, 1, -1)
2310 $defaultValue = $values[0];
2313 return $defaultValue;
2317 * Post process function.
2319 * @param array $params
2320 * @param int $entityID
2321 * @param string $customFieldExtends
2322 * @param bool $inline
2323 * @param bool $checkPermissions
2327 public static function postProcess(
2330 $customFieldExtends,
2332 $checkPermissions = TRUE
2334 $customData = array();
2336 foreach ($params as $key => $value) {
2337 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2339 // for autocomplete transfer hidden value instead of label
2340 if ($params[$key] && isset($params[$key . '_id'])) {
2341 $value = $params[$key . '_id'];
2344 // we need to append time with date
2345 if ($params[$key] && isset($params[$key . '_time'])) {
2346 $value .= ' ' . $params[$key . '_time'];
2349 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2352 $customFieldExtends,
2353 $customFieldInfo[1],
2364 * Get custom field ID from field/group name/title.
2366 * @param string $fieldName Field name or label
2367 * @param string|null $groupName (Optional) Group name or label
2368 * @param bool $fullString Whether to return "custom_123" or "123"
2370 * @return string|int|null
2371 * @throws \CiviCRM_API3_Exception
2373 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2374 $cacheKey = $groupName . '.' . $fieldName;
2375 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2376 $customFieldParams = [
2377 'name' => $fieldName,
2378 'label' => $fieldName,
2379 'options' => ['or' => [["name", "label"]]],
2383 $customFieldParams['custom_group_id.name'] = $groupName;
2384 $customFieldParams['custom_group_id.title'] = $groupName;
2385 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2388 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2390 if (empty($field['id'])) {
2391 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2392 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2395 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2396 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2401 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2403 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2407 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2413 public static function getNameFromID($ids) {
2414 if (is_array($ids)) {
2415 $ids = implode(',', $ids);
2418 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2419 FROM civicrm_custom_field f
2420 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2421 WHERE f.id IN ($ids)";
2423 $dao = CRM_Core_DAO
::executeQuery($sql);
2425 while ($dao->fetch()) {
2426 $result[$dao->id
] = array(
2427 'field_name' => $dao->field_name
,
2428 'field_label' => $dao->field_label
,
2429 'group_name' => $dao->group_name
,
2430 'group_title' => $dao->group_title
,
2437 * Validate custom data.
2439 * @param array $params
2440 * Custom data submitted.
2441 * ie array( 'custom_1' => 'validate me' );
2444 * validation errors.
2446 public static function validateCustomData($params) {
2448 if (!is_array($params) ||
empty($params)) {
2452 //pick up profile fields.
2453 $profileFields = array();
2454 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2456 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2458 CRM_Core_Action
::VIEW
2462 //lets start w/ params.
2463 foreach ($params as $key => $value) {
2464 $customFieldID = self
::getKeyID($key);
2465 if (!$customFieldID) {
2469 //load the structural info for given field.
2470 $field = new CRM_Core_DAO_CustomField();
2471 $field->id
= $customFieldID;
2472 if (!$field->find(TRUE)) {
2475 $dataType = $field->data_type
;
2477 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2478 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2479 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2481 $fieldTitle = $field->label
;
2484 //no need to validate.
2485 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2489 //lets validate first for required field.
2490 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2491 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2495 //now time to take care of custom field form rules.
2496 $ruleName = $errorMsg = NULL;
2497 switch ($dataType) {
2499 $ruleName = 'integer';
2500 $errorMsg = ts('%1 must be an integer (whole number).',
2501 array(1 => $fieldTitle)
2506 $ruleName = 'money';
2507 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2508 array(1 => $fieldTitle)
2513 $ruleName = 'numeric';
2514 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2515 array(1 => $fieldTitle)
2520 $ruleName = 'wikiURL';
2521 $errorMsg = ts('%1 must be valid Website.',
2522 array(1 => $fieldTitle)
2527 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2529 $funName = "CRM_Utils_Rule::{$ruleName}";
2530 if (is_callable($funName)) {
2531 $valid = call_user_func($funName, $value);
2534 $errors[$key] = $errorMsg;
2543 * Is this field a multi record field.
2545 * @param int $customId
2549 public static function isMultiRecordField($customId) {
2550 $isMultipleWithGid = FALSE;
2551 if (!is_numeric($customId)) {
2552 $customId = self
::getKeyID($customId);
2554 if (is_numeric($customId)) {
2555 $sql = "SELECT cg.id cgId
2556 FROM civicrm_custom_group cg
2557 INNER JOIN civicrm_custom_field cf
2558 ON cg.id = cf.custom_group_id
2559 WHERE cf.id = %1 AND cg.is_multiple = 1";
2560 $params[1] = array($customId, 'Integer');
2561 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2562 if ($dao->fetch()) {
2564 $isMultipleWithGid = $dao->cgId
;
2569 return $isMultipleWithGid;
2573 * Does this field type have any select options?
2575 * @param array $field
2579 public static function hasOptions($field) {
2580 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2581 $field = (array) $field;
2582 // This will include boolean fields with Yes/No options.
2583 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2586 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2587 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2588 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2591 if (strpos($field['html_type'], 'Select') !== FALSE) {
2594 return !empty($field['option_group_id']);
2598 * Does this field store a serialized string?
2600 * @param array $field
2604 public static function isSerialized($field) {
2605 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2606 $field = (array) $field;
2607 // 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.
2608 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2612 * Get api entity for this field
2616 public function getEntity() {
2617 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2618 return in_array($entity, array('Individual', 'Household', 'Organization')) ?
'Contact' : $entity;
2622 * Set pseudoconstant properties for field metadata.
2624 * @param array $field
2625 * @param string|null $optionGroupName
2627 private static function getOptionsForField(&$field, $optionGroupName) {
2628 if ($optionGroupName) {
2629 $field['pseudoconstant'] = array(
2630 'optionGroupName' => $optionGroupName,
2631 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2634 elseif ($field['data_type'] == 'Boolean') {
2635 $field['pseudoconstant'] = array(
2636 'callback' => 'CRM_Core_SelectValues::boolean',
2639 elseif ($field['data_type'] == 'Country') {
2640 $field['pseudoconstant'] = array(
2641 'table' => 'civicrm_country',
2642 'keyColumn' => 'id',
2643 'labelColumn' => 'name',
2644 'nameColumn' => 'iso_code',
2647 elseif ($field['data_type'] == 'StateProvince') {
2648 $field['pseudoconstant'] = array(
2649 'table' => 'civicrm_state_province',
2650 'keyColumn' => 'id',
2651 'labelColumn' => 'name',
2657 * @param CRM_Core_DAO_CustomField $field
2658 * @param 'add|modify' $operation
2662 protected static function prepareCreateParams($field, $operation) {
2663 $tableName = CRM_Core_DAO
::getFieldValue(
2664 'CRM_Core_DAO_CustomGroup',
2665 $field->custom_group_id
,
2670 'table_name' => $tableName,
2671 'operation' => $operation,
2672 'name' => $field->column_name
,
2673 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2677 'required' => $field->is_required
,
2678 'searchable' => $field->is_searchable
,
2681 if ($operation == 'delete') {
2682 $fkName = "{$tableName}_{$field->column_name}";
2683 if (strlen($fkName) >= 48) {
2684 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2686 $params['fkName'] = $fkName;
2688 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
2689 $params['fk_table_name'] = 'civicrm_country';
2690 $params['fk_field_name'] = 'id';
2691 $params['fk_attributes'] = 'ON DELETE SET NULL';
2693 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
2694 $params['type'] = 'varchar(255)';
2696 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
2697 $params['fk_table_name'] = 'civicrm_state_province';
2698 $params['fk_field_name'] = 'id';
2699 $params['fk_attributes'] = 'ON DELETE SET NULL';
2701 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
2702 $params['type'] = 'varchar(255)';
2704 elseif ($field->data_type
== 'File') {
2705 $params['fk_table_name'] = 'civicrm_file';
2706 $params['fk_field_name'] = 'id';
2707 $params['fk_attributes'] = 'ON DELETE SET NULL';
2709 elseif ($field->data_type
== 'ContactReference') {
2710 $params['fk_table_name'] = 'civicrm_contact';
2711 $params['fk_field_name'] = 'id';
2712 $params['fk_attributes'] = 'ON DELETE SET NULL';
2714 if (isset($field->default_value
)) {
2715 $params['default'] = "'{$field->default_value}'";