3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 'Float' => CRM_Utils_Type
::T_FLOAT
,
97 'Money' => CRM_Utils_Type
::T_FLOAT
,
98 'Memo' => CRM_Utils_Type
::T_TEXT
,
99 'Date' => CRM_Utils_Type
::T_DATE
,
100 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
101 'StateProvince' => CRM_Utils_Type
::T_INT
,
102 'Country' => CRM_Utils_Type
::T_INT
,
103 'Link' => CRM_Utils_Type
::T_STRING
,
104 'ContactReference' => CRM_Utils_Type
::T_INT
,
109 * Get data to html array.
111 * (Does this caching achieve anything?)
115 public static function dataToHtml() {
116 if (!self
::$_dataToHtml) {
117 self
::$_dataToHtml = array(
120 'Select' => 'Select',
122 'CheckBox' => 'CheckBox',
123 'Multi-Select' => 'Multi-Select',
124 'Autocomplete-Select' => 'Autocomplete-Select',
126 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
127 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
128 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
129 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
130 array('Date' => 'Select Date'),
131 array('Radio' => 'Radio'),
132 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
133 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
134 array('File' => 'File'),
135 array('Link' => 'Link'),
136 array('ContactReference' => 'Autocomplete-Select'),
139 return self
::$_dataToHtml;
143 * Takes an associative array and creates a custom field object.
145 * This function is invoked from within the web form layer and also from the api layer
147 * @param array $params
148 * (reference) an assoc array of name/value pairs.
150 * @return CRM_Core_DAO_CustomField
152 public static function create(&$params) {
153 $origParams = array_merge(array(), $params);
155 $op = empty($params['id']) ?
'create' : 'edit';
157 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
159 if ($op == 'create') {
160 if (!isset($params['column_name'])) {
161 // if add mode & column_name not present, calculate it.
162 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
164 if (!isset($params['name'])) {
165 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
169 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
174 $columnName = $params['column_name'];
177 //as during create if field is_searchable we had created index.
178 if (!empty($params['id'])) {
179 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
182 switch (CRM_Utils_Array
::value('html_type', $params)) {
184 if (empty($params['date_format'])) {
185 $config = CRM_Core_Config
::singleton();
186 $params['date_format'] = $config->dateInputFormat
;
192 if (isset($params['default_checkbox_option'])) {
193 $tempArray = array_keys($params['default_checkbox_option']);
194 $defaultArray = array();
195 foreach ($tempArray as $k => $v) {
196 if ($params['option_value'][$v]) {
197 $defaultArray[] = $params['option_value'][$v];
201 if (!empty($defaultArray)) {
202 // also add the separator before and after the value per new convention (CRM-1604)
203 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
207 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
209 $params['default_value'] = $params['option_value'][$params['default_option']];
215 $transaction = new CRM_Core_Transaction();
217 $htmlType = CRM_Utils_Array
::value('html_type', $params);
218 $dataType = CRM_Utils_Array
::value('data_type', $params);
219 $allowedOptionTypes = array('String', 'Int', 'Float', 'Money');
221 // create any option group & values if required
222 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)
224 //CRM-16659: if option_value then create an option group for this custom field.
225 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
226 // first create an option group for this custom group
227 $optionGroup = new CRM_Core_DAO_OptionGroup();
228 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
229 $optionGroup->title
= $params['label'];
230 $optionGroup->is_active
= 1;
231 $optionGroup->data_type
= $dataType;
232 $optionGroup->save();
233 $params['option_group_id'] = $optionGroup->id
;
234 if (!empty($params['option_value']) && is_array($params['option_value'])) {
235 foreach ($params['option_value'] as $k => $v) {
236 if (strlen(trim($v))) {
237 $optionValue = new CRM_Core_DAO_OptionValue();
238 $optionValue->option_group_id
= $optionGroup->id
;
239 $optionValue->label
= $params['option_label'][$k];
240 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
243 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
247 $optionValue->value
= intval($v);
251 $optionValue->value
= floatval($v);
255 $optionValue->value
= trim($v);
258 $optionValue->weight
= $params['option_weight'][$k];
259 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
260 $optionValue->save();
267 // check for orphan option groups
268 if (!empty($params['option_group_id'])) {
269 if (!empty($params['id'])) {
270 self
::fixOptionGroups($params['id'], $params['option_group_id']);
273 // if we do not have a default value
274 // retrieve it from one of the other custom fields which use this option group
275 if (empty($params['default_value'])) {
276 //don't insert only value separator as default value, CRM-4579
277 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
281 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
285 $params['default_value'] = $defaultValue;
290 // since we need to save option group id :)
291 if (!isset($params['attributes']) && strtolower($htmlType) == 'textarea') {
292 $params['attributes'] = 'rows=4, cols=60';
295 $customField = new CRM_Core_DAO_CustomField();
296 $customField->copyValues($params);
297 if ($op == 'create') {
298 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
299 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
300 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $params, FALSE);
301 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
302 //CRM-15792 - Custom field gets disabled if is_active not set
303 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, TRUE);
304 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
306 $customField->save();
308 // make sure all values are present in the object for further processing
309 $customField->find(TRUE);
311 $triggerRebuild = CRM_Utils_Array
::value('triggerRebuild', $params, TRUE);
312 //create/drop the index when we toggle the is_searchable flag
314 self
::createField($customField, 'modify', $indexExist, $triggerRebuild);
317 if (!isset($origParams['column_name'])) {
318 $columnName .= "_{$customField->id}";
319 $params['column_name'] = $columnName;
321 $customField->column_name
= $columnName;
322 $customField->save();
323 // make sure all values are present in the object
324 $customField->find(TRUE);
327 self
::createField($customField, 'add', $indexExist, $triggerRebuild);
330 // complete transaction
331 $transaction->commit();
333 CRM_Utils_Hook
::post($op, 'CustomField', $customField->id
, $customField);
335 CRM_Utils_System
::flushCache();
341 * Fetch object based on array of properties.
343 * @param array $params
344 * (reference ) an assoc array of name/value pairs.
345 * @param array $defaults
346 * (reference ) an assoc array to hold the flattened values.
348 * @return CRM_Core_DAO_CustomField
350 public static function retrieve(&$params, &$defaults) {
351 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
355 * Update the is_active flag in the db.
358 * Id of the database record.
359 * @param bool $is_active
360 * Value we want to set the is_active field.
363 * DAO object on success, null otherwise
365 public static function setIsActive($id, $is_active) {
367 CRM_Utils_System
::flushCache();
369 //enable-disable CustomField
370 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
371 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
375 * Get the field title.
383 public static function getTitle($id) {
384 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
388 * @param string $context
391 public function getOptions($context = NULL) {
392 CRM_Core_DAO
::buildOptionsContext($context);
397 if (!$this->data_type ||
!$this->custom_group_id
) {
401 if (!empty($this->option_group_id
)) {
402 $options = CRM_Core_OptionGroup
::valuesByID(
403 $this->option_group_id
,
408 !($context == 'validate' ||
$context == 'get')
411 elseif ($this->data_type
=== 'StateProvince') {
412 $options = CRM_Core_Pseudoconstant
::stateProvince();
414 elseif ($this->data_type
=== 'Country') {
415 $options = $context == 'validate' ? CRM_Core_Pseudoconstant
::countryIsoCode() : CRM_Core_Pseudoconstant
::country();
417 elseif ($this->data_type
=== 'Boolean') {
418 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
423 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
424 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, array('context' => $context));
429 * Store and return an array of all active custom fields.
431 * @param string $customDataType
432 * Type of Custom Data; empty is a synonym for "all contact data types".
433 * @param bool $showAll
434 * If true returns all fields (includes disabled fields).
435 * @param bool $inline
436 * If true returns all inline fields (includes disabled fields).
437 * @param int $customDataSubType
438 * Custom Data sub type value.
439 * @param int $customDataSubName
440 * Custom Data sub name value.
441 * @param bool $onlyParent
442 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
443 * @param bool $onlySubType
444 * Return only custom data for subtype.
445 * @param bool $checkPermission
446 * If false, do not include permissioning clause.
449 * an array of active custom fields.
451 public static function &getFields(
452 $customDataType = 'Individual',
455 $customDataSubType = NULL,
456 $customDataSubName = NULL,
458 $onlySubType = FALSE,
459 $checkPermission = TRUE
461 if (empty($customDataType)) {
462 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
464 if ($customDataType && !is_array($customDataType)) {
466 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
467 // This is the case when getFieldsForImport() requires fields
468 // limited strictly to a subtype.
469 $customDataSubType = $customDataType;
470 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
474 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
475 // this makes the method flexible to support retrieving fields
476 // for multiple extends value.
477 $customDataType = array($customDataType);
481 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
483 if (is_array($customDataType)) {
484 $cacheKey = implode('_', $customDataType);
487 $cacheKey = $customDataType;
490 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
491 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
492 $cacheKey .= $showAll ?
'_1' : '_0';
493 $cacheKey .= $inline ?
'_1_' : '_0_';
494 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
495 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
496 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
498 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
500 // also get the permission stuff here
501 if ($checkPermission) {
502 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
507 $permissionClause = '(1)';
510 // lets md5 permission clause and take first 8 characters
511 $cacheKey .= substr(md5($permissionClause), 0, 8);
513 if (strlen($cacheKey) > 40) {
514 $cacheKey = md5($cacheKey);
517 if (!self
::$_importFields ||
518 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
520 if (!self
::$_importFields) {
521 self
::$_importFields = array();
524 // check if we can retrieve from database cache
525 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
527 if ($fields === NULL) {
528 $cfTable = self
::getTableName();
531 if (is_array($customDataType)) {
533 foreach ($customDataType as $dataType) {
534 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
535 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
536 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
539 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
541 $value = $value ?
$value . ", {$val}" : $val;
545 $extends = "AND $cgTable.extends IN ( $value ) ";
549 if (!empty($customDataType) && empty($extends)) {
550 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
551 self
::$_importFields[$cacheKey] = array();
552 return self
::$_importFields[$cacheKey];
556 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
559 $query = "SELECT $cfTable.id, $cfTable.label,
563 $cfTable.default_value,
564 $cfTable.options_per_line, $cfTable.text_length,
565 $cfTable.custom_group_id,
566 $cfTable.is_required,
567 $cfTable.column_name,
568 $cgTable.extends, $cfTable.is_search_range,
569 $cgTable.extends_entity_column_value,
570 $cgTable.extends_entity_column_id,
572 $cfTable.option_group_id,
573 $cfTable.date_format,
574 $cfTable.time_format,
575 $cgTable.is_multiple,
577 og.name as option_group_name
580 ON $cfTable.custom_group_id = $cgTable.id
581 LEFT JOIN civicrm_option_group og
582 ON $cfTable.option_group_id = og.id
586 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
590 $query .= " AND $cgTable.style = 'Inline' ";
593 //get the custom fields for specific type in
594 //combination with fields those support any type.
595 if (!empty($customDataSubType)) {
596 $subtypeClause = array();
597 foreach ($customDataSubType as $subtype) {
598 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
599 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
602 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
604 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
607 if ($customDataSubName) {
608 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
611 // also get the permission stuff here
612 if ($checkPermission) {
613 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
618 $permissionClause = '(1)';
621 $query .= " $extends AND $permissionClause
622 ORDER BY $cgTable.weight, $cgTable.title,
623 $cfTable.weight, $cfTable.label";
625 $dao = CRM_Core_DAO
::executeQuery($query);
628 while (($dao->fetch()) != NULL) {
629 $fields[$dao->id
]['label'] = $dao->label
;
630 $fields[$dao->id
]['groupTitle'] = $dao->title
;
631 $fields[$dao->id
]['data_type'] = $dao->data_type
;
632 $fields[$dao->id
]['html_type'] = $dao->html_type
;
633 $fields[$dao->id
]['default_value'] = $dao->default_value
;
634 $fields[$dao->id
]['text_length'] = $dao->text_length
;
635 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
636 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
637 $fields[$dao->id
]['extends'] = $dao->extends;
638 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
639 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
640 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
641 $fields[$dao->id
]['is_view'] = $dao->is_view
;
642 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
643 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
644 $fields[$dao->id
]['date_format'] = $dao->date_format
;
645 $fields[$dao->id
]['time_format'] = $dao->time_format
;
646 $fields[$dao->id
]['is_required'] = $dao->is_required
;
647 $fields[$dao->id
]['table_name'] = $dao->table_name
;
648 $fields[$dao->id
]['column_name'] = $dao->column_name
;
649 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
652 CRM_Core_BAO_Cache
::setItem($fields,
654 "custom importableFields $cacheKey"
657 self
::$_importFields[$cacheKey] = $fields;
660 return self
::$_importFields[$cacheKey];
664 * Return the field ids and names (with groups) for import purpose.
666 * @param int|string $contactType Contact type
667 * @param bool $showAll
668 * If true returns all fields (includes disabled fields).
669 * @param bool $onlyParent
670 * Return fields ONLY related to basic types.
671 * @param bool $search
672 * When called from search and multiple records need to be returned.
673 * @param bool $checkPermission
674 * If false, do not include permissioning clause.
676 * @param bool $withMultiple
680 public static function getFieldsForImport(
681 $contactType = 'Individual',
685 $checkPermission = TRUE,
686 $withMultiple = FALSE
688 // Note: there are situations when we want getFieldsForImport() return fields related
689 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
690 $fields = &self
::getFields($contactType,
700 $importableFields = array();
701 foreach ($fields as $id => $values) {
702 // for now we should not allow multiple fields in profile / export etc, hence unsetting
704 (!empty($values['is_multiple']) && !$withMultiple)
709 /* generate the key for the fields array */
713 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
714 $importableFields[$key] = array(
716 'type' => CRM_Utils_Array
::value(CRM_Utils_Array
::value('data_type', $values), self
::dataToType()),
717 'title' => CRM_Utils_Array
::value('label', $values),
718 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
720 'custom_field_id' => $id,
721 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
722 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
723 'data_type' => CRM_Utils_Array
::value('data_type', $values),
724 'html_type' => CRM_Utils_Array
::value('html_type', $values),
725 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
728 // CRM-6681, pass date and time format when html_type = Select Date
729 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
730 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
731 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
735 return $importableFields;
739 * Get the field id from an import key.
749 public static function getKeyID($key, $all = FALSE) {
751 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
758 CRM_Utils_Array
::value(2, $match),
762 return $all ?
array(NULL, NULL) : NULL;
766 * Use the cache to get all values of a specific custom field.
768 * @param int $fieldID
769 * The custom field ID.
771 * @return CRM_Core_BAO_CustomField
774 public static function getFieldObject($fieldID) {
775 $field = new CRM_Core_BAO_CustomField();
777 // check if we can get the field values from the system cache
778 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
779 $cache = CRM_Utils_Cache
::singleton();
780 $fieldValues = $cache->get($cacheKey);
781 if (empty($fieldValues)) {
782 $field->id
= $fieldID;
783 if (!$field->find(TRUE)) {
784 CRM_Core_Error
::fatal();
787 $fieldValues = array();
788 CRM_Core_DAO
::storeValues($field, $fieldValues);
790 $cache->set($cacheKey, $fieldValues);
793 $field->copyValues($fieldValues);
800 * Add a custom field to an existing form.
802 * @param CRM_Core_Form $qf
803 * Form object (reference).
804 * @param string $elementName
805 * Name of the custom field.
806 * @param int $fieldId
807 * @param bool $useRequired
808 * True if required else false.
809 * @param bool $search
810 * True if used for search else false.
811 * @param string $label
812 * Label for custom field.
813 * @return \HTML_QuickForm_Element|null
814 * @throws \CiviCRM_API3_Exception
816 public static function addQuickFormElement(
817 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
819 $field = self
::getFieldObject($fieldId);
820 $widget = $field->html_type
;
822 $customFieldAttributes = array();
824 // Custom field HTML should indicate group+field name
825 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
826 $dataCrmCustomVal = $groupName . ':' . $field->name
;
827 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
828 $field->attributes
.= $dataCrmCustomAttr;
830 // Fixed for Issue CRM-2183
831 if ($widget == 'TextArea' && $search) {
835 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
837 // FIXME: Why are select state/country separate widget types?
838 $isSelect = (in_array($widget, array(
841 'Select State/Province',
842 'Multi-Select State/Province',
844 'Multi-Select Country',
850 $options = $field->getOptions($search ?
'search' : 'create');
852 // Consolidate widget types to simplify the below switch statement
853 if ($search ||
(strpos($widget, 'Select') !== FALSE)) {
857 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
858 $selectAttributes = array('class' => 'crm-select2');
860 // Search field is always multi-select
861 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
862 $selectAttributes['class'] .= ' huge';
863 $selectAttributes['multiple'] = 'multiple';
864 $selectAttributes['placeholder'] = $placeholder;
867 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
868 $isSupportedWidget = in_array($widget, ['Select', 'Radio']);
869 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
870 if ($field->option_group_id
&& !$search && $isSelect && $canEditOptions) {
871 $customFieldAttributes +
= array(
872 'data-api-entity' => $field->getEntity(),
873 'data-api-field' => 'custom_' . $field->id
,
874 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
876 $selectAttributes +
= $customFieldAttributes;
880 if (!isset($label)) {
881 $label = $field->label
;
884 // at some point in time we might want to split the below into small functions
889 if ($field->is_search_range
&& $search) {
890 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
891 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
894 if ($field->text_length
) {
895 $field->attributes
.= ' maxlength=' . $field->text_length
;
896 if ($field->text_length
< 20) {
897 $field->attributes
.= ' size=' . $field->text_length
;
900 $element = $qf->add('text', $elementName, $label,
902 $useRequired && !$search
908 $attributes = $dataCrmCustomAttr;
909 if ($field->note_rows
) {
910 $attributes .= 'rows=' . $field->note_rows
;
913 $attributes .= 'rows=4';
915 if ($field->note_columns
) {
916 $attributes .= ' cols=' . $field->note_columns
;
919 $attributes .= ' cols=60';
921 if ($field->text_length
) {
922 $attributes .= ' maxlength=' . $field->text_length
;
924 $element = $qf->add('textarea',
928 $useRequired && !$search
933 $attr = array('data-crm-custom' => $dataCrmCustomVal);
934 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
935 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
936 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
939 'date' => $field->date_format
,
940 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
941 //CRM-18487 - max date should be the last date of the year.
942 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
943 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
945 if ($field->is_search_range
&& $search) {
946 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
947 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
950 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
956 parse_str($field->attributes
, $radioAttributes);
957 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
959 foreach ($options as $v => $l) {
960 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
962 $element = $qf->addGroup($choice, $elementName, $label);
963 $optionEditKey = 'data-option-edit-path';
964 if (isset($selectAttributes[$optionEditKey])) {
965 $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
968 if ($useRequired && !$search) {
969 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
972 $element->setAttribute('allowClear', TRUE);
976 // For all select elements
978 if (empty($selectAttributes['multiple'])) {
979 $options = array('' => $placeholder) +
$options;
981 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
983 // Add and/or option for fields that store multiple values
984 if ($search && self
::isSerialized($field)) {
987 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
988 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
990 $qf->addGroup($operators, $elementName . '_operator');
991 $qf->setDefaults(array($elementName . '_operator' => 'or'));
997 foreach ($options as $v => $l) {
998 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
1001 $group = $element = $qf->addGroup($check, $elementName, $label);
1002 $optionEditKey = 'data-option-edit-path';
1003 if (isset($customFieldAttributes[$optionEditKey])) {
1004 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
1007 if ($useRequired && !$search) {
1008 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
1013 // we should not build upload file in search mode
1017 $element = $qf->add(
1018 strtolower($field->html_type
),
1022 $useRequired && !$search
1024 $qf->addUploadElement($elementName);
1027 case 'RichTextEditor':
1028 $attributes = array(
1029 'rows' => $field->note_rows
,
1030 'cols' => $field->note_columns
,
1031 'data-crm-custom' => $dataCrmCustomVal,
1033 if ($field->text_length
) {
1034 $attributes['maxlength'] = $field->text_length
;
1036 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
1039 case 'Autocomplete-Select':
1040 static $customUrls = array();
1041 // Fixme: why is this a string in the first place??
1042 $attributes = array();
1043 if ($field->attributes
) {
1044 foreach (explode(' ', $field->attributes
) as $at) {
1045 if (strpos($at, '=')) {
1046 list($k, $v) = explode('=', $at);
1047 $attributes[$k] = trim($v, ' "');
1051 if ($field->data_type
== 'ContactReference') {
1052 // break if contact does not have permission to access ContactReference
1053 if (!CRM_Core_Permission
::check('access contact reference fields')) {
1056 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1057 $attributes['data-api-entity'] = 'Contact';
1058 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
1060 $urlParams = "context=customfield&id={$field->id}";
1062 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1069 // FIXME: This won't work with customFieldOptions hook
1070 $attributes +
= array(
1071 'entity' => 'option_value',
1072 'placeholder' => $placeholder,
1073 'multiple' => $search,
1075 'params' => array('option_group_id' => $field->option_group_id
),
1078 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1081 $qf->assign('customUrls', $customUrls);
1085 switch ($field->data_type
) {
1087 // integers will have numeric rule applied to them.
1088 if ($field->is_search_range
&& $search) {
1089 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1090 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1092 elseif ($widget == 'Text') {
1093 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1098 if ($field->is_search_range
&& $search) {
1099 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1100 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1102 elseif ($widget == 'Text') {
1103 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1108 if ($field->is_search_range
&& $search) {
1109 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1110 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1112 elseif ($widget == 'Text') {
1113 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1118 $element->setAttribute('class', "url");
1119 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1122 if ($field->is_view
&& !$search) {
1123 $qf->freeze($elementName);
1129 * Delete the Custom Field.
1131 * @param object $field
1134 public static function deleteField($field) {
1135 CRM_Utils_System
::flushCache();
1137 // first delete the custom option group and values associated with this field
1138 if ($field->option_group_id
) {
1139 //check if option group is related to any other field, if
1140 //not delete the option group and related option values
1141 self
::checkOptionGroup($field->option_group_id
);
1144 // next drop the column from the custom value table
1145 self
::createField($field, 'delete');
1148 CRM_Core_BAO_UFField
::delUFField($field->id
);
1149 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1151 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
1155 * @param string|int|array|null $value
1156 * @param CRM_Core_BAO_CustomField|int|array|string $field
1157 * @param int $entityId
1160 * @throws \Exception
1162 public static function displayValue($value, $field, $entityId = NULL) {
1163 $field = is_array($field) ?
$field['id'] : $field;
1164 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1167 throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1170 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1171 $field = self
::getFieldObject($fieldId);
1174 $fieldInfo = array('options' => $field->getOptions()) +
(array) $field;
1176 return self
::formatDisplayValue($value, $fieldInfo, $entityId);
1180 * Lower-level logic for rendering a custom field value
1182 * @param string|array $value
1183 * @param array $field
1184 * @param int|null $entityId
1188 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1190 if (self
::isSerialized($field) && !is_array($value)) {
1191 $value = CRM_Utils_Array
::explodePadded($value);
1194 if ($field['html_type'] == 'CheckBox') {
1195 CRM_Utils_Array
::formatArrayKeys($value);
1198 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1200 switch ($field['html_type']) {
1203 case 'Autocomplete-Select':
1205 case 'Select Country':
1206 case 'Select State/Province':
1208 case 'Multi-Select':
1209 case 'Multi-Select State/Province':
1210 case 'Multi-Select Country':
1211 if ($field['data_type'] == 'ContactReference' && $value) {
1212 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1214 elseif (is_array($value)) {
1216 foreach ($value as $key => $val) {
1217 $v[] = CRM_Utils_Array
::value($val, $field['options']);
1219 $display = implode(', ', $v);
1222 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1227 $customFormat = NULL;
1229 // FIXME: Are there any legitimate reasons why $value would be an array?
1230 // Or should we throw an exception here if it is?
1231 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1233 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1234 $format = CRM_Utils_Array
::value('date_format', $field);
1237 if (array_key_exists($format, $actualPHPFormats)) {
1238 $customTimeFormat = (array) $actualPHPFormats[$format];
1239 switch (CRM_Utils_Array
::value('time_format', $field)) {
1241 $customTimeFormat[] = 'g:iA';
1245 $customTimeFormat[] = 'G:i';
1249 //If time is not selected remove time from value.
1250 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1252 $customFormat = implode(" ", $customTimeFormat);
1255 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1259 // In the context of displaying a profile, show file/image
1262 if (CRM_Utils_Rule
::positiveInteger($value)) {
1266 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1268 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1270 $display = $url['file_url'];
1274 // In other contexts show a paperclip icon
1275 if (CRM_Utils_Rule
::integer($value)) {
1276 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1277 $display = $icons[$value];
1280 //CRM-18396, if filename is passed instead
1288 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1292 $display = nl2br($display);
1296 if ($field['data_type'] == 'Money' && isset($value)) {
1297 //$value can also be an array(while using IN operator from search builder or api).
1298 foreach ((array) $value as $val) {
1299 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1301 $display = implode(', ', $disp);
1309 * Set default values for custom data used in profile.
1311 * @param int $customFieldId
1313 * @param string $elementName
1314 * Custom field name.
1315 * @param array $defaults
1316 * Associated array of fields.
1317 * @param int $contactId
1321 * @param mixed $value
1322 * If passed - dont fetch value from db,.
1323 * just format the given value
1325 public static function setProfileDefaults(
1333 //get the type of custom field
1334 $customField = new CRM_Core_BAO_CustomField();
1335 $customField->id
= $customFieldId;
1336 $customField->find(TRUE);
1339 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1340 $value = $customField->default_value
;
1344 if (!isset($value)) {
1345 $info = self
::getTableColumnGroup($customFieldId);
1346 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1347 $result = CRM_Core_DAO
::executeQuery($query);
1348 if ($result->fetch()) {
1349 $value = $result->value
;
1353 if ($customField->data_type
== 'Country') {
1355 $config = CRM_Core_Config
::singleton();
1356 if ($config->defaultContactCountry
) {
1357 $value = $config->defaultContactCountry();
1363 //set defaults if mode is registration
1364 if (!trim($value) &&
1366 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1368 $value = $customField->default_value
;
1371 if ($customField->data_type
== 'Money' && isset($value)) {
1372 $value = number_format($value, 2);
1374 switch ($customField->html_type
) {
1376 case 'Multi-Select':
1377 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1378 $defaults[$elementName] = array();
1379 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1380 substr($value, 1, -1)
1382 foreach ($customOption as $val) {
1383 if (in_array($val['value'], $checkedValue)) {
1384 if ($customField->html_type
== 'CheckBox') {
1385 $defaults[$elementName][$val['value']] = 1;
1387 elseif ($customField->html_type
== 'Multi-Select') {
1388 $defaults[$elementName][$val['value']] = $val['value'];
1394 case 'Autocomplete-Select':
1395 if ($customField->data_type
== 'ContactReference') {
1396 if (is_numeric($value)) {
1397 $defaults[$elementName . '_id'] = $value;
1398 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1402 $defaults[$elementName] = $value;
1407 $defaults[$elementName] = $value;
1414 * @param int $contactID
1416 * @param int $fileID
1417 * @param bool $absolute
1419 * @param string $multiRecordWhereClause
1423 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1426 $params = array('id' => $cfID);
1427 $defaults = array();
1428 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1429 $columnName = $defaults['column_name'];
1431 //table name of custom data
1432 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1433 $defaults['custom_group_id'],
1437 //query to fetch id from civicrm_file
1438 if ($multiRecordWhereClause) {
1439 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1442 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1444 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1449 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1454 $result['file_id'] = $fileID;
1456 if ($fileType == 'image/jpeg' ||
1457 $fileType == 'image/pjpeg' ||
1458 $fileType == 'image/gif' ||
1459 $fileType == 'image/x-png' ||
1460 $fileType == 'image/png'
1462 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1467 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1468 $url = CRM_Utils_System
::url('civicrm/file',
1469 "reset=1&id=$fileID&eid=$contactID",
1470 $absolute, NULL, TRUE, TRUE
1472 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1474 // for non image files
1476 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1480 $url = CRM_Utils_System
::url('civicrm/file',
1481 "reset=1&id=$fileID&eid=$contactID",
1482 $absolute, NULL, TRUE, TRUE
1484 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1492 * Format custom fields before inserting.
1494 * @param int $customFieldId
1496 * @param array $customFormatted
1498 * @param mixed $value
1499 * Value of custom field.
1500 * @param string $customFieldExtend
1501 * Custom field extends.
1502 * @param int $customValueId
1503 * Custom option value id.
1504 * @param int $entityId
1505 * Entity id (contribution, membership...).
1506 * @param bool $inline
1507 * Consider inline custom groups only.
1508 * @param bool $checkPermission
1509 * If false, do not include permissioning clause.
1510 * @param bool $includeViewOnly
1511 * If true, fields marked 'View Only' are included. Required for APIv3.
1513 * @return array|NULL
1514 * formatted custom field array
1516 public static function formatCustomField(
1517 $customFieldId, &$customFormatted, $value,
1518 $customFieldExtend, $customValueId = NULL,
1521 $checkPermission = TRUE,
1522 $includeViewOnly = FALSE
1524 //get the custom fields for the entity
1525 //subtype and basic type
1526 $customDataSubType = NULL;
1527 if ($customFieldExtend) {
1528 // This is the case when getFieldsForImport() requires fields
1529 // of subtype and its parent.CRM-5143
1530 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1531 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1532 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1533 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1534 if (is_array($customFieldExtend)) {
1535 $customFieldExtend = array_unique(array_values($customFieldExtend));
1540 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1550 if (!array_key_exists($customFieldId, $customFields)) {
1554 // return if field is a 'code' field
1555 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1559 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1561 if (!$customValueId &&
1562 // we always create new entites for is_multiple unless specified
1563 !$customFields[$customFieldId]['is_multiple'] &&
1569 WHERE entity_id={$entityId}";
1571 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1574 //fix checkbox, now check box always submits values
1575 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1577 // Note that only during merge this is not an array, and you can directly use value
1578 if (is_array($value)) {
1579 $selectedValues = array();
1580 foreach ($value as $selId => $val) {
1582 $selectedValues[] = $selId;
1585 if (!empty($selectedValues)) {
1586 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1588 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1597 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select') {
1599 $value = CRM_Utils_Array
::implodePadded($value);
1606 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1607 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1609 $customFields[$customFieldId]['data_type'] == 'String' &&
1610 !empty($customFields[$customFieldId]['text_length']) &&
1613 // lets make sure that value is less than the length, else we'll
1614 // be losing some data, CRM-7481
1615 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1616 // need to do a few things here
1618 // 1. lets find a new length
1619 $newLength = $customFields[$customFieldId]['text_length'];
1620 $minLength = strlen($value);
1621 while ($newLength < $minLength) {
1622 $newLength = $newLength * 2;
1625 // set the custom field meta data to have a length larger than value
1626 // alter the custom value table column to match this length
1627 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1632 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1633 if (!CRM_Utils_System
::isNull($value)) {
1634 $format = $customFields[$customFieldId]['date_format'];
1635 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1640 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1641 $customFields[$customFieldId]['data_type'] == 'Money'
1647 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1648 $value = CRM_Utils_Rule
::cleanMoney($value);
1652 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1653 $customFields[$customFieldId]['data_type'] == 'Country'
1663 if ($customFields[$customFieldId]['data_type'] == 'File') {
1664 if (empty($value)) {
1668 $config = CRM_Core_Config
::singleton();
1670 // If we are already passing the file id as a value then retrieve and set the file data
1671 if (CRM_Utils_Rule
::integer($value)) {
1672 $fileDAO = new CRM_Core_DAO_File();
1673 $fileDAO->id
= $value;
1674 $fileDAO->find(TRUE);
1677 $fName = $fileDAO->uri
;
1678 $mimeType = $fileDAO->mime_type
;
1682 $fName = $value['name'];
1683 $mimeType = $value['type'];
1686 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1688 // rename this file to go into the secure directory only if
1689 // user has uploaded new file not existing verfied on the basis of $fileID
1690 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1691 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1694 if ($customValueId && empty($fileID)) {
1699 $params = array(1 => array($customValueId, 'Integer'));
1700 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1703 $fileDAO = new CRM_Core_DAO_File();
1706 $fileDAO->id
= $fileId;
1709 $fileDAO->uri
= $filename;
1710 $fileDAO->mime_type
= $mimeType;
1711 $fileDAO->upload_date
= date('YmdHis');
1713 $fileId = $fileDAO->id
;
1717 if (!is_array($customFormatted)) {
1718 $customFormatted = array();
1721 if (!array_key_exists($customFieldId, $customFormatted)) {
1722 $customFormatted[$customFieldId] = array();
1726 if ($customValueId) {
1727 $index = $customValueId;
1730 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1731 $customFormatted[$customFieldId][$index] = array();
1733 $customFormatted[$customFieldId][$index] = array(
1734 'id' => $customValueId > 0 ?
$customValueId : NULL,
1736 'type' => $customFields[$customFieldId]['data_type'],
1737 'custom_field_id' => $customFieldId,
1738 'custom_group_id' => $groupID,
1739 'table_name' => $tableName,
1740 'column_name' => $columnName,
1741 'file_id' => $fileId,
1742 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1745 //we need to sort so that custom fields are created in the order of entry
1746 krsort($customFormatted[$customFieldId]);
1747 return $customFormatted;
1751 * Get default custom table schema.
1753 * @param array $params
1757 public static function defaultCustomTableSchema($params) {
1758 // add the id and extends_id
1760 'name' => $params['name'],
1761 'is_multiple' => $params['is_multiple'],
1762 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1766 'type' => 'int unsigned',
1769 'attributes' => 'AUTO_INCREMENT',
1770 'comment' => 'Default MySQL primary key',
1773 'name' => 'entity_id',
1774 'type' => 'int unsigned',
1776 'comment' => 'Table that this extends',
1777 'fk_table_name' => $params['extends_name'],
1778 'fk_field_name' => 'id',
1779 'fk_attributes' => 'ON DELETE CASCADE',
1784 if (!$params['is_multiple']) {
1785 $table['indexes'] = array(
1788 'field_name_1' => 'entity_id',
1796 * Create custom field.
1798 * @param CRM_Core_DAO_CustomField $field
1799 * @param string $operation
1800 * @param bool $indexExist
1801 * @param bool $triggerRebuild
1803 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1804 $tableName = CRM_Core_DAO
::getFieldValue(
1805 'CRM_Core_DAO_CustomGroup',
1806 $field->custom_group_id
,
1811 'table_name' => $tableName,
1812 'operation' => $operation,
1813 'name' => $field->column_name
,
1814 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1818 'required' => $field->is_required
,
1819 'searchable' => $field->is_searchable
,
1822 if ($operation == 'delete') {
1823 $fkName = "{$tableName}_{$field->column_name}";
1824 if (strlen($fkName) >= 48) {
1825 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1827 $params['fkName'] = $fkName;
1829 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1830 $params['fk_table_name'] = 'civicrm_country';
1831 $params['fk_field_name'] = 'id';
1832 $params['fk_attributes'] = 'ON DELETE SET NULL';
1834 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1835 $params['type'] = 'varchar(255)';
1837 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1838 $params['fk_table_name'] = 'civicrm_state_province';
1839 $params['fk_field_name'] = 'id';
1840 $params['fk_attributes'] = 'ON DELETE SET NULL';
1842 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1843 $params['type'] = 'varchar(255)';
1845 elseif ($field->data_type
== 'File') {
1846 $params['fk_table_name'] = 'civicrm_file';
1847 $params['fk_field_name'] = 'id';
1848 $params['fk_attributes'] = 'ON DELETE SET NULL';
1850 elseif ($field->data_type
== 'ContactReference') {
1851 $params['fk_table_name'] = 'civicrm_contact';
1852 $params['fk_field_name'] = 'id';
1853 $params['fk_attributes'] = 'ON DELETE SET NULL';
1855 if (isset($field->default_value
)) {
1856 $params['default'] = "'{$field->default_value}'";
1859 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1863 * Determine whether it would be safe to move a field.
1865 * @param int $fieldID
1866 * FK to civicrm_custom_field.
1867 * @param int $newGroupID
1868 * FK to civicrm_custom_group.
1871 * array(string) or TRUE
1873 public static function _moveFieldValidate($fieldID, $newGroupID) {
1876 $field = new CRM_Core_DAO_CustomField();
1877 $field->id
= $fieldID;
1878 if (!$field->find(TRUE)) {
1879 $errors['fieldID'] = 'Invalid ID for custom field';
1883 $oldGroup = new CRM_Core_DAO_CustomGroup();
1884 $oldGroup->id
= $field->custom_group_id
;
1885 if (!$oldGroup->find(TRUE)) {
1886 $errors['fieldID'] = 'Invalid ID for old custom group';
1890 $newGroup = new CRM_Core_DAO_CustomGroup();
1891 $newGroup->id
= $newGroupID;
1892 if (!$newGroup->find(TRUE)) {
1893 $errors['newGroupID'] = 'Invalid ID for new custom group';
1899 FROM civicrm_custom_field a
1900 INNER JOIN civicrm_custom_field b
1902 AND a.label = b.label
1903 AND b.custom_group_id = %2
1906 1 => array($field->id
, 'Integer'),
1907 2 => array($newGroup->id
, 'Integer'),
1909 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1911 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1914 $tableName = $oldGroup->table_name
;
1915 $columnName = $field->column_name
;
1920 WHERE $columnName is not null
1922 $count = CRM_Core_DAO
::singleValueQuery($query,
1923 CRM_Core_DAO
::$_nullArray
1928 FROM civicrm_custom_group
1929 WHERE id IN ( %1, %2 )
1932 1 => array($oldGroup->id
, 'Integer'),
1933 2 => array($newGroup->id
, 'Integer'),
1936 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1938 while ($dao->fetch()) {
1939 $extends[] = $dao->extends;
1941 if ($extends[0] != $extends[1]) {
1942 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1946 return empty($errors) ?
TRUE : $errors;
1950 * Move a custom data field from one group (table) to another.
1952 * @param int $fieldID
1953 * FK to civicrm_custom_field.
1954 * @param int $newGroupID
1955 * FK to civicrm_custom_group.
1957 public static function moveField($fieldID, $newGroupID) {
1958 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1959 if (TRUE !== $validation) {
1960 CRM_Core_Error
::fatal(implode(' ', $validation));
1962 $field = new CRM_Core_DAO_CustomField();
1963 $field->id
= $fieldID;
1966 $newGroup = new CRM_Core_DAO_CustomGroup();
1967 $newGroup->id
= $newGroupID;
1968 $newGroup->find(TRUE);
1970 $oldGroup = new CRM_Core_DAO_CustomGroup();
1971 $oldGroup->id
= $field->custom_group_id
;
1972 $oldGroup->find(TRUE);
1975 $add->custom_group_id
= $newGroup->id
;
1976 self
::createField($add, 'add');
1978 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1979 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1980 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1982 CRM_Core_DAO
::executeQuery($sql);
1985 $del->custom_group_id
= $oldGroup->id
;
1986 self
::createField($del, 'delete');
1990 CRM_Utils_System
::flushCache();
1994 * Get the database table name and column name for a custom field.
1996 * @param int $fieldID
1997 * The fieldID of the custom field.
1998 * @param bool $force
1999 * Force the sql to be run again (primarily used for tests).
2002 * fatal is fieldID does not exists, else array of tableName, columnName
2004 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2005 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2006 $cache = CRM_Utils_Cache
::singleton();
2007 $fieldValues = $cache->get($cacheKey);
2008 if (empty($fieldValues) ||
$force) {
2010 SELECT cg.table_name, cf.column_name, cg.id
2011 FROM civicrm_custom_group cg,
2012 civicrm_custom_field cf
2013 WHERE cf.custom_group_id = cg.id
2015 $params = array(1 => array($fieldID, 'Integer'));
2016 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2018 if (!$dao->fetch()) {
2019 CRM_Core_Error
::fatal();
2022 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2023 $cache->set($cacheKey, $fieldValues);
2025 return $fieldValues;
2029 * Get custom option groups.
2031 * @param array $includeFieldIds
2032 * Ids of custom fields for which option groups must be included.
2034 * Currently this is required in the cases where option groups are to be included
2035 * for inactive fields : CRM-5369
2039 public static function customOptionGroup($includeFieldIds = NULL) {
2040 static $customOptionGroup = NULL;
2042 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2043 if ($cacheKey == 'force') {
2044 $customOptionGroup[$cacheKey] = NULL;
2047 if (empty($customOptionGroup[$cacheKey])) {
2048 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2050 //support for single as well as array format.
2051 if (!empty($includeFieldIds)) {
2052 if (is_array($includeFieldIds)) {
2053 $includeFieldIds = implode(',', $includeFieldIds);
2055 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2059 SELECT g.id, g.title
2060 FROM civicrm_option_group g
2061 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2062 WHERE {$whereClause}";
2064 $dao = CRM_Core_DAO
::executeQuery($query);
2065 while ($dao->fetch()) {
2066 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2070 return $customOptionGroup[$cacheKey];
2074 * Fix orphan groups.
2076 * @param int $customFieldId
2078 * @param int $optionGroupId
2081 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2082 // check if option group belongs to any custom Field else delete
2083 // get the current option group
2084 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2088 // get the updated option group
2089 // if both are same return
2090 if ($currentOptionGroupId == $optionGroupId) {
2094 // check if option group is related to any other field
2095 self
::checkOptionGroup($currentOptionGroupId);
2099 * Check if option group is related to more than one custom field.
2101 * @param int $optionGroupId
2104 public static function checkOptionGroup($optionGroupId) {
2107 FROM civicrm_custom_field
2108 WHERE option_group_id = {$optionGroupId}";
2110 $count = CRM_Core_DAO
::singleValueQuery($query);
2113 //delete the option group
2114 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2119 * Get option group default.
2121 * @param int $optionGroupId
2122 * @param string $htmlType
2124 * @return null|string
2126 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2128 SELECT default_value, html_type
2129 FROM civicrm_custom_field
2130 WHERE option_group_id = {$optionGroupId}
2131 AND default_value IS NOT NULL
2132 ORDER BY html_type";
2134 $dao = CRM_Core_DAO
::executeQuery($query);
2135 $defaultValue = NULL;
2136 $defaultHTMLType = NULL;
2137 while ($dao->fetch()) {
2138 if ($dao->html_type
== $htmlType) {
2139 return $dao->default_value
;
2141 if ($defaultValue == NULL) {
2142 $defaultValue = $dao->default_value
;
2143 $defaultHTMLType = $dao->html_type
;
2147 // some conversions are needed if either the old or new has a html type which has potential
2148 // multiple default values.
2149 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2150 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2152 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2154 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2155 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2157 $defaultValue = substr($defaultValue, 1, -1);
2158 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2159 substr($defaultValue, 1, -1)
2161 $defaultValue = $values[0];
2164 return $defaultValue;
2168 * Post process function.
2170 * @param array $params
2171 * @param int $entityID
2172 * @param string $customFieldExtends
2173 * @param bool $inline
2174 * @param bool $checkPermissions
2178 public static function postProcess(
2181 $customFieldExtends,
2183 $checkPermissions = TRUE
2185 $customData = array();
2187 foreach ($params as $key => $value) {
2188 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2190 // for autocomplete transfer hidden value instead of label
2191 if ($params[$key] && isset($params[$key . '_id'])) {
2192 $value = $params[$key . '_id'];
2195 // we need to append time with date
2196 if ($params[$key] && isset($params[$key . '_time'])) {
2197 $value .= ' ' . $params[$key . '_time'];
2200 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2203 $customFieldExtends,
2204 $customFieldInfo[1],
2215 * Get custom field ID from field/group name/title.
2217 * @param string $fieldName Field name or label
2218 * @param string|null $groupTitle (Optional) Group name or label
2219 * @param bool $fullString Whether to return "custom_123" or "123"
2221 * @return string|int|null
2222 * @throws \CiviCRM_API3_Exception
2224 public static function getCustomFieldID($fieldName, $groupTitle = NULL, $fullString = FALSE) {
2225 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName])) {
2226 $customFieldParams = [
2227 'name' => $fieldName,
2228 'label' => $fieldName,
2229 'options' => ['or' => [["name", "label"]]],
2233 $customFieldParams['custom_group_id.name'] = $groupTitle;
2234 $customFieldParams['custom_group_id.title'] = $groupTitle;
2235 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2238 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2240 if (empty($field['id'])) {
2241 Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['id'] = NULL;
2242 Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['string'] = NULL;
2245 Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['id'] = $field['id'];
2246 Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['string'] = 'custom_' . $field['id'];
2251 return Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['string'];
2253 return Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['id'];
2257 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2263 public static function getNameFromID($ids) {
2264 if (is_array($ids)) {
2265 $ids = implode(',', $ids);
2268 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2269 FROM civicrm_custom_field f
2270 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2271 WHERE f.id IN ($ids)";
2273 $dao = CRM_Core_DAO
::executeQuery($sql);
2275 while ($dao->fetch()) {
2276 $result[$dao->id
] = array(
2277 'field_name' => $dao->field_name
,
2278 'field_label' => $dao->field_label
,
2279 'group_name' => $dao->group_name
,
2280 'group_title' => $dao->group_title
,
2287 * Validate custom data.
2289 * @param array $params
2290 * Custom data submitted.
2291 * ie array( 'custom_1' => 'validate me' );
2294 * validation errors.
2296 public static function validateCustomData($params) {
2298 if (!is_array($params) ||
empty($params)) {
2302 //pick up profile fields.
2303 $profileFields = array();
2304 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2306 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2308 CRM_Core_Action
::VIEW
2312 //lets start w/ params.
2313 foreach ($params as $key => $value) {
2314 $customFieldID = self
::getKeyID($key);
2315 if (!$customFieldID) {
2319 //load the structural info for given field.
2320 $field = new CRM_Core_DAO_CustomField();
2321 $field->id
= $customFieldID;
2322 if (!$field->find(TRUE)) {
2325 $dataType = $field->data_type
;
2327 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2328 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2329 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2331 $fieldTitle = $field->label
;
2334 //no need to validate.
2335 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2339 //lets validate first for required field.
2340 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2341 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2345 //now time to take care of custom field form rules.
2346 $ruleName = $errorMsg = NULL;
2347 switch ($dataType) {
2349 $ruleName = 'integer';
2350 $errorMsg = ts('%1 must be an integer (whole number).',
2351 array(1 => $fieldTitle)
2356 $ruleName = 'money';
2357 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2358 array(1 => $fieldTitle)
2363 $ruleName = 'numeric';
2364 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2365 array(1 => $fieldTitle)
2370 $ruleName = 'wikiURL';
2371 $errorMsg = ts('%1 must be valid Website.',
2372 array(1 => $fieldTitle)
2377 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2379 $funName = "CRM_Utils_Rule::{$ruleName}";
2380 if (is_callable($funName)) {
2381 $valid = call_user_func($funName, $value);
2384 $errors[$key] = $errorMsg;
2393 * Is this field a multi record field.
2395 * @param int $customId
2399 public static function isMultiRecordField($customId) {
2400 $isMultipleWithGid = FALSE;
2401 if (!is_numeric($customId)) {
2402 $customId = self
::getKeyID($customId);
2404 if (is_numeric($customId)) {
2405 $sql = "SELECT cg.id cgId
2406 FROM civicrm_custom_group cg
2407 INNER JOIN civicrm_custom_field cf
2408 ON cg.id = cf.custom_group_id
2409 WHERE cf.id = %1 AND cg.is_multiple = 1";
2410 $params[1] = array($customId, 'Integer');
2411 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2412 if ($dao->fetch()) {
2414 $isMultipleWithGid = $dao->cgId
;
2419 return $isMultipleWithGid;
2423 * Does this field store a serialized string?
2425 * @param array $field
2429 public static function isSerialized($field) {
2430 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2431 $field = (array) $field;
2432 // 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.
2433 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2437 * Get api entity for this field
2441 public function getEntity() {
2442 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2443 return in_array($entity, array('Individual', 'Household', 'Organization')) ?
'Contact' : $entity;
2447 * Set pseudoconstant properties for field metadata.
2449 * @param array $field
2450 * @param string|null $optionGroupName
2452 private static function getOptionsForField(&$field, $optionGroupName) {
2453 if ($optionGroupName) {
2454 $field['pseudoconstant'] = array(
2455 'optionGroupName' => $optionGroupName,
2456 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2459 elseif ($field['data_type'] == 'Boolean') {
2460 $field['pseudoconstant'] = array(
2461 'callback' => 'CRM_Core_SelectValues::boolean',
2464 elseif ($field['data_type'] == 'Country') {
2465 $field['pseudoconstant'] = array(
2466 'table' => 'civicrm_country',
2467 'keyColumn' => 'id',
2468 'labelColumn' => 'name',
2469 'nameColumn' => 'iso_code',
2472 elseif ($field['data_type'] == 'StateProvince') {
2473 $field['pseudoconstant'] = array(
2474 'table' => 'civicrm_state_province',
2475 'keyColumn' => 'id',
2476 'labelColumn' => 'name',