3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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 * Get data to html array.
89 * (Does this caching achieve anything?)
93 public static function dataToHtml() {
94 if (!self
::$_dataToHtml) {
95 self
::$_dataToHtml = array(
100 'CheckBox' => 'CheckBox',
101 'Multi-Select' => 'Multi-Select',
102 'AdvMulti-Select' => 'AdvMulti-Select',
103 'Autocomplete-Select' => 'Autocomplete-Select',
105 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
106 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
107 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
108 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
109 array('Date' => 'Select Date'),
110 array('Radio' => 'Radio'),
111 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
112 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
113 array('File' => 'File'),
114 array('Link' => 'Link'),
115 array('ContactReference' => 'Autocomplete-Select'),
118 return self
::$_dataToHtml;
122 * Takes an associative array and creates a custom field object.
124 * This function is invoked from within the web form layer and also from the api layer
126 * @param array $params
127 * (reference) an assoc array of name/value pairs.
129 * @return CRM_Core_DAO_CustomField
131 public static function create(&$params) {
132 $origParams = array_merge(array(), $params);
134 if (!isset($params['id'])) {
135 if (!isset($params['column_name'])) {
136 // if add mode & column_name not present, calculate it.
137 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
139 if (!isset($params['name'])) {
140 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
144 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
149 $columnName = $params['column_name'];
152 //as during create if field is_searchable we had created index.
153 if (!empty($params['id'])) {
154 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
157 switch (CRM_Utils_Array
::value('html_type', $params)) {
159 if (empty($params['date_format'])) {
160 $config = CRM_Core_Config
::singleton();
161 $params['date_format'] = $config->dateInputFormat
;
166 case 'AdvMulti-Select':
168 if (isset($params['default_checkbox_option'])) {
169 $tempArray = array_keys($params['default_checkbox_option']);
170 $defaultArray = array();
171 foreach ($tempArray as $k => $v) {
172 if ($params['option_value'][$v]) {
173 $defaultArray[] = $params['option_value'][$v];
177 if (!empty($defaultArray)) {
178 // also add the separator before and after the value per new convention (CRM-1604)
179 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
183 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
185 $params['default_value'] = $params['option_value'][$params['default_option']];
191 $transaction = new CRM_Core_Transaction();
192 // create any option group & values if required
193 if ($params['html_type'] != 'Text' &&
194 in_array($params['data_type'], array(
202 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
203 $params['custom_group_id'],
207 //CRM-16659: if option_value then create an option group for this custom field.
208 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
209 // first create an option group for this custom group
210 $optionGroup = new CRM_Core_DAO_OptionGroup();
211 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
212 $optionGroup->title
= $params['label'];
213 $optionGroup->is_active
= 1;
214 $optionGroup->save();
215 $params['option_group_id'] = $optionGroup->id
;
216 if (!empty($params['option_value']) && is_array($params['option_value'])) {
217 foreach ($params['option_value'] as $k => $v) {
218 if (strlen(trim($v))) {
219 $optionValue = new CRM_Core_DAO_OptionValue();
220 $optionValue->option_group_id
= $optionGroup->id
;
221 $optionValue->label
= $params['option_label'][$k];
222 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
223 switch ($params['data_type']) {
225 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
229 $optionValue->value
= intval($v);
233 $optionValue->value
= floatval($v);
237 $optionValue->value
= trim($v);
240 $optionValue->weight
= $params['option_weight'][$k];
241 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
242 $optionValue->save();
249 // check for orphan option groups
250 if (!empty($params['option_group_id'])) {
251 if (!empty($params['id'])) {
252 self
::fixOptionGroups($params['id'], $params['option_group_id']);
255 // if we do not have a default value
256 // retrieve it from one of the other custom fields which use this option group
257 if (empty($params['default_value'])) {
258 //don't insert only value separator as default value, CRM-4579
259 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
263 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
267 $params['default_value'] = $defaultValue;
272 // since we need to save option group id :)
273 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
274 $params['attributes'] = 'rows=4, cols=60';
277 $customField = new CRM_Core_DAO_CustomField();
278 $customField->copyValues($params);
279 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
280 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
281 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $params, FALSE);
282 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
283 //CRM-15792 - Custom field gets disabled if is_active not set
284 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, TRUE);
285 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
286 $customField->save();
288 // make sure all values are present in the object for further processing
289 $customField->find(TRUE);
291 $triggerRebuild = CRM_Utils_Array
::value('triggerRebuild', $params, TRUE);
292 //create/drop the index when we toggle the is_searchable flag
293 if (!empty($params['id'])) {
294 self
::createField($customField, 'modify', $indexExist, $triggerRebuild);
297 if (!isset($origParams['column_name'])) {
298 $columnName .= "_{$customField->id}";
299 $params['column_name'] = $columnName;
301 $customField->column_name
= $columnName;
302 $customField->save();
303 // make sure all values are present in the object
304 $customField->find(TRUE);
307 self
::createField($customField, 'add', $indexExist, $triggerRebuild);
310 // complete transaction
311 $transaction->commit();
313 CRM_Utils_System
::flushCache();
319 * Fetch object based on array of properties.
321 * @param array $params
322 * (reference ) an assoc array of name/value pairs.
323 * @param array $defaults
324 * (reference ) an assoc array to hold the flattened values.
326 * @return CRM_Core_DAO_CustomField
328 public static function retrieve(&$params, &$defaults) {
329 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
333 * Update the is_active flag in the db.
336 * Id of the database record.
337 * @param bool $is_active
338 * Value we want to set the is_active field.
341 * DAO object on success, null otherwise
343 public static function setIsActive($id, $is_active) {
345 CRM_Utils_System
::flushCache();
347 //enable-disable CustomField
348 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
349 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
353 * Get the field title.
361 public static function getTitle($id) {
362 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
366 * @param string $context
369 public function getOptions($context = NULL) {
370 CRM_Core_DAO
::buildOptionsContext($context);
375 if (!$this->data_type ||
!$this->custom_group_id
) {
379 if (!empty($this->option_group_id
)) {
380 $options = CRM_Core_OptionGroup
::valuesByID(
381 $this->option_group_id
,
386 !($context == 'validate' ||
$context == 'get')
389 elseif ($this->data_type
=== 'StateProvince') {
390 $options = CRM_Core_Pseudoconstant
::stateProvince();
392 elseif ($this->data_type
=== 'Country') {
393 $options = $context == 'validate' ? CRM_Core_Pseudoconstant
::countryIsoCode() : CRM_Core_Pseudoconstant
::country();
395 elseif ($this->data_type
=== 'Boolean') {
396 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
401 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
402 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, array('context' => $context));
407 * Store and return an array of all active custom fields.
409 * @param string $customDataType
410 * Type of Custom Data; empty is a synonym for "all contact data types".
411 * @param bool $showAll
412 * If true returns all fields (includes disabled fields).
413 * @param bool $inline
414 * If true returns all inline fields (includes disabled fields).
415 * @param int $customDataSubType
416 * Custom Data sub type value.
417 * @param int $customDataSubName
418 * Custom Data sub name value.
419 * @param bool $onlyParent
420 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
421 * @param bool $onlySubType
422 * Return only custom data for subtype.
423 * @param bool $checkPermission
424 * If false, do not include permissioning clause.
427 * an array of active custom fields.
429 public static function &getFields(
430 $customDataType = 'Individual',
433 $customDataSubType = NULL,
434 $customDataSubName = NULL,
436 $onlySubType = FALSE,
437 $checkPermission = TRUE
439 if (empty($customDataType)) {
440 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
442 if ($customDataType && !is_array($customDataType)) {
444 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
445 // This is the case when getFieldsForImport() requires fields
446 // limited strictly to a subtype.
447 $customDataSubType = $customDataType;
448 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
452 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
453 // this makes the method flexible to support retrieving fields
454 // for multiple extends value.
455 $customDataType = array($customDataType);
459 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
461 if (is_array($customDataType)) {
462 $cacheKey = implode('_', $customDataType);
465 $cacheKey = $customDataType;
468 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
469 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
470 $cacheKey .= $showAll ?
'_1' : '_0';
471 $cacheKey .= $inline ?
'_1_' : '_0_';
472 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
473 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
474 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
476 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
478 // also get the permission stuff here
479 if ($checkPermission) {
480 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
485 $permissionClause = '(1)';
488 // lets md5 permission clause and take first 8 characters
489 $cacheKey .= substr(md5($permissionClause), 0, 8);
491 if (strlen($cacheKey) > 40) {
492 $cacheKey = md5($cacheKey);
495 if (!self
::$_importFields ||
496 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
498 if (!self
::$_importFields) {
499 self
::$_importFields = array();
502 // check if we can retrieve from database cache
503 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
505 if ($fields === NULL) {
506 $cfTable = self
::getTableName();
509 if (is_array($customDataType)) {
511 foreach ($customDataType as $dataType) {
512 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
513 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
514 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
517 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
519 $value = $value ?
$value . ", {$val}" : $val;
523 $extends = "AND $cgTable.extends IN ( $value ) ";
527 if (!empty($customDataType) && empty($extends)) {
528 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
529 self
::$_importFields[$cacheKey] = array();
530 return self
::$_importFields[$cacheKey];
534 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
537 $query = "SELECT $cfTable.id, $cfTable.label,
541 $cfTable.default_value,
542 $cfTable.options_per_line, $cfTable.text_length,
543 $cfTable.custom_group_id,
544 $cfTable.is_required,
545 $cfTable.column_name,
546 $cgTable.extends, $cfTable.is_search_range,
547 $cgTable.extends_entity_column_value,
548 $cgTable.extends_entity_column_id,
550 $cfTable.option_group_id,
551 $cfTable.date_format,
552 $cfTable.time_format,
553 $cgTable.is_multiple,
555 og.name as option_group_name
558 ON $cfTable.custom_group_id = $cgTable.id
559 LEFT JOIN civicrm_option_group og
560 ON $cfTable.option_group_id = og.id
564 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
568 $query .= " AND $cgTable.style = 'Inline' ";
571 //get the custom fields for specific type in
572 //combination with fields those support any type.
573 if (!empty($customDataSubType)) {
574 $subtypeClause = array();
575 foreach ($customDataSubType as $subtype) {
576 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
577 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
580 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
582 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
585 if ($customDataSubName) {
586 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
589 // also get the permission stuff here
590 if ($checkPermission) {
591 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
596 $permissionClause = '(1)';
599 $query .= " $extends AND $permissionClause
600 ORDER BY $cgTable.weight, $cgTable.title,
601 $cfTable.weight, $cfTable.label";
603 $dao = CRM_Core_DAO
::executeQuery($query);
606 while (($dao->fetch()) != NULL) {
607 $fields[$dao->id
]['label'] = $dao->label
;
608 $fields[$dao->id
]['groupTitle'] = $dao->title
;
609 $fields[$dao->id
]['data_type'] = $dao->data_type
;
610 $fields[$dao->id
]['html_type'] = $dao->html_type
;
611 $fields[$dao->id
]['default_value'] = $dao->default_value
;
612 $fields[$dao->id
]['text_length'] = $dao->text_length
;
613 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
614 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
615 $fields[$dao->id
]['extends'] = $dao->extends;
616 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
617 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
618 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
619 $fields[$dao->id
]['is_view'] = $dao->is_view
;
620 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
621 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
622 $fields[$dao->id
]['date_format'] = $dao->date_format
;
623 $fields[$dao->id
]['time_format'] = $dao->time_format
;
624 $fields[$dao->id
]['is_required'] = $dao->is_required
;
625 $fields[$dao->id
]['table_name'] = $dao->table_name
;
626 $fields[$dao->id
]['column_name'] = $dao->column_name
;
627 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
630 CRM_Core_BAO_Cache
::setItem($fields,
632 "custom importableFields $cacheKey"
635 self
::$_importFields[$cacheKey] = $fields;
638 return self
::$_importFields[$cacheKey];
642 * Return the field ids and names (with groups) for import purpose.
644 * @param int|string $contactType Contact type
645 * @param bool $showAll
646 * If true returns all fields (includes disabled fields).
647 * @param bool $onlyParent
648 * Return fields ONLY related to basic types.
649 * @param bool $search
650 * When called from search and multiple records need to be returned.
651 * @param bool $checkPermission
652 * If false, do not include permissioning clause.
654 * @param bool $withMultiple
658 public static function getFieldsForImport(
659 $contactType = 'Individual',
663 $checkPermission = TRUE,
664 $withMultiple = FALSE
666 // Note: there are situations when we want getFieldsForImport() return fields related
667 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
668 $fields = &self
::getFields($contactType,
678 $importableFields = array();
679 foreach ($fields as $id => $values) {
680 // for now we should not allow multiple fields in profile / export etc, hence unsetting
682 (!empty($values['is_multiple']) && !$withMultiple)
687 /* generate the key for the fields array */
691 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
692 $importableFields[$key] = array(
694 'title' => CRM_Utils_Array
::value('label', $values),
695 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
697 'custom_field_id' => $id,
698 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
699 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
700 'data_type' => CRM_Utils_Array
::value('data_type', $values),
701 'html_type' => CRM_Utils_Array
::value('html_type', $values),
702 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
705 // CRM-6681, pass date and time format when html_type = Select Date
706 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
707 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
708 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
712 return $importableFields;
716 * Get the field id from an import key.
726 public static function getKeyID($key, $all = FALSE) {
728 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
735 CRM_Utils_Array
::value(2, $match),
739 return $all ?
array(NULL, NULL) : NULL;
743 * Use the cache to get all values of a specific custom field.
745 * @param int $fieldID
746 * The custom field ID.
748 * @return CRM_Core_BAO_CustomField
751 public static function getFieldObject($fieldID) {
752 $field = new CRM_Core_BAO_CustomField();
754 // check if we can get the field values from the system cache
755 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
756 $cache = CRM_Utils_Cache
::singleton();
757 $fieldValues = $cache->get($cacheKey);
758 if (empty($fieldValues)) {
759 $field->id
= $fieldID;
760 if (!$field->find(TRUE)) {
761 CRM_Core_Error
::fatal();
764 $fieldValues = array();
765 CRM_Core_DAO
::storeValues($field, $fieldValues);
767 $cache->set($cacheKey, $fieldValues);
770 $field->copyValues($fieldValues);
777 * Add a custom field to an existing form.
779 * @param CRM_Core_Form $qf
780 * Form object (reference).
781 * @param string $elementName
782 * Name of the custom field.
783 * @param int $fieldId
784 * @param bool $useRequired
785 * True if required else false.
786 * @param bool $search
787 * True if used for search else false.
788 * @param string $label
789 * Label for custom field.
790 * @return \HTML_QuickForm_Element|null
791 * @throws \CiviCRM_API3_Exception
793 public static function addQuickFormElement(
794 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
796 $field = self
::getFieldObject($fieldId);
797 $widget = $field->html_type
;
800 // Custom field HTML should indicate group+field name
801 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
802 $dataCrmCustomVal = $groupName . ':' . $field->name
;
803 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
804 $field->attributes
.= $dataCrmCustomAttr;
806 // Fixed for Issue CRM-2183
807 if ($widget == 'TextArea' && $search) {
811 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
813 // FIXME: Why are select state/country separate widget types?
814 $isSelect = (in_array($widget, array(
817 'Select State/Province',
818 'Multi-Select State/Province',
820 'Multi-Select Country',
827 $options = $field->getOptions($search ?
'search' : 'create');
829 // Consolidate widget types to simplify the below switch statement
830 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
833 $selectAttributes = array(
834 'data-crm-custom' => $dataCrmCustomVal,
835 'class' => 'crm-select2',
837 // Search field is always multi-select
838 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
839 $selectAttributes['class'] .= ' huge';
840 $selectAttributes['multiple'] = 'multiple';
841 $selectAttributes['placeholder'] = $placeholder;
843 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
844 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
845 $selectAttributes +
= array(
846 'data-api-entity' => $field->getEntity(),
847 'data-api-field' => 'custom_' . $field->id
,
848 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
853 if (!isset($label)) {
854 $label = $field->label
;
857 // at some point in time we might want to split the below into small functions
862 if ($field->is_search_range
&& $search) {
863 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
864 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
867 $element = $qf->add('text', $elementName, $label,
869 $useRequired && !$search
875 $attributes = $dataCrmCustomAttr;
876 if ($field->note_rows
) {
877 $attributes .= 'rows=' . $field->note_rows
;
880 $attributes .= 'rows=4';
882 if ($field->note_columns
) {
883 $attributes .= ' cols=' . $field->note_columns
;
886 $attributes .= ' cols=60';
888 if ($field->text_length
) {
889 $attributes .= ' maxlength=' . $field->text_length
;
891 $element = $qf->add('textarea',
895 $useRequired && !$search
900 $attr = array('data-crm-custom' => $dataCrmCustomVal);
902 'date' => $field->date_format
,
903 'minDate' => isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) . '-01-01' : NULL,
904 'maxDate' => isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) . '-01-01' : NULL,
905 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
907 if ($field->is_search_range
&& $search) {
908 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
909 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
912 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
918 foreach ($options as $v => $l) {
919 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
921 $element = $qf->addGroup($choice, $elementName, $label);
922 if ($useRequired && !$search) {
923 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
926 $element->setAttribute('allowClear', TRUE);
930 // For all select elements
932 if (empty($selectAttributes['multiple'])) {
933 $options = array('' => $placeholder) +
$options;
935 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
937 // Add and/or option for fields that store multiple values
938 if ($search && self
::isSerialized($field)) {
941 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
942 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
944 $qf->addGroup($operators, $elementName . '_operator');
945 $qf->setDefaults(array($elementName . '_operator' => 'or'));
949 case 'AdvMulti-Select':
950 $element = $qf->addElement(
957 'class' => 'advmultiselect',
958 'data-crm-custom' => $dataCrmCustomVal,
962 $element->setButtonAttributes('add', array('value' => ts('Add >>')));
963 $element->setButtonAttributes('remove', array('value' => ts('<< Remove')));
965 if ($useRequired && !$search) {
966 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
972 foreach ($options as $v => $l) {
973 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
975 $element = $qf->addGroup($check, $elementName, $label);
976 if ($useRequired && !$search) {
977 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
982 // we should not build upload file in search mode
987 strtolower($field->html_type
),
991 $useRequired && !$search
993 $qf->addUploadElement($elementName);
996 case 'RichTextEditor':
998 'rows' => $field->note_rows
,
999 'cols' => $field->note_columns
,
1000 'data-crm-custom' => $dataCrmCustomVal,
1002 if ($field->text_length
) {
1003 $attributes['maxlength'] = $field->text_length
;
1005 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $search);
1008 case 'Autocomplete-Select':
1009 static $customUrls = array();
1010 // Fixme: why is this a string in the first place??
1011 $attributes = array();
1012 if ($field->attributes
) {
1013 foreach (explode(' ', $field->attributes
) as $at) {
1014 if (strpos($at, '=')) {
1015 list($k, $v) = explode('=', $at);
1016 $attributes[$k] = trim($v, ' "');
1020 if ($field->data_type
== 'ContactReference') {
1021 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1022 $attributes['data-api-entity'] = 'Contact';
1023 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
1025 $urlParams = "context=customfield&id={$field->id}";
1027 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1034 // FIXME: This won't work with customFieldOptions hook
1035 $attributes +
= array(
1036 'entity' => 'option_value',
1037 'placeholder' => $placeholder,
1038 'multiple' => $search,
1040 'params' => array('option_group_id' => $field->option_group_id
),
1043 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1046 $qf->assign('customUrls', $customUrls);
1050 switch ($field->data_type
) {
1052 // integers will have numeric rule applied to them.
1053 if ($field->is_search_range
&& $search) {
1054 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1055 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1057 elseif ($widget == 'Text') {
1058 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1063 if ($field->is_search_range
&& $search) {
1064 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1065 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1067 elseif ($widget == 'Text') {
1068 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1073 if ($field->is_search_range
&& $search) {
1074 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1075 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1077 elseif ($widget == 'Text') {
1078 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1083 $element->setAttribute('class', "url");
1084 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1087 if ($field->is_view
&& !$search) {
1088 $qf->freeze($elementName);
1094 * Delete the Custom Field.
1096 * @param object $field
1099 public static function deleteField($field) {
1100 CRM_Utils_System
::flushCache();
1102 // first delete the custom option group and values associated with this field
1103 if ($field->option_group_id
) {
1104 //check if option group is related to any other field, if
1105 //not delete the option group and related option values
1106 self
::checkOptionGroup($field->option_group_id
);
1109 // next drop the column from the custom value table
1110 self
::createField($field, 'delete');
1113 CRM_Core_BAO_UFField
::delUFField($field->id
);
1114 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1118 * @param string|int|array|null $value
1119 * @param CRM_Core_BAO_CustomField|int|array|string $field
1123 * @throws \Exception
1125 public static function displayValue($value, $field, $contactId = NULL) {
1126 $field = is_array($field) ?
$field['id'] : $field;
1127 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1130 throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1133 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1134 $field = self
::getFieldObject($fieldId);
1137 $fieldInfo = array('options' => $field->getOptions()) +
(array) $field;
1139 return self
::formatDisplayValue($value, $fieldInfo, $contactId);
1143 * Lower-level logic for rendering a custom field value
1145 * @param string|array $value
1146 * @param array $field
1147 * @param int|null $entityId
1151 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1153 if (self
::isSerialized($field) && !is_array($value)) {
1154 $value = CRM_Utils_Array
::explodePadded($value);
1157 if ($field['html_type'] == 'CheckBox') {
1158 CRM_Utils_Array
::formatArrayKeys($value);
1161 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1163 switch ($field['html_type']) {
1166 case 'Autocomplete-Select':
1168 case 'Select Country':
1169 case 'Select State/Province':
1171 case 'AdvMulti-Select':
1172 case 'Multi-Select':
1173 case 'Multi-Select State/Province':
1174 case 'Multi-Select Country':
1175 if ($field['data_type'] == 'ContactReference' && $value) {
1176 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1178 elseif (is_array($value)) {
1180 foreach ($value as $key => $val) {
1181 $v[] = CRM_Utils_Array
::value($val, $field['options']);
1183 $display = implode(', ', $v);
1186 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1191 $customFormat = NULL;
1193 // FIXME: Are there any legitimate reasons why $value would be an array?
1194 // Or should we throw an exception here if it is?
1195 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1197 $actualPHPFormats = CRM_Core_SelectValues
::datePluginToPHPFormats();
1198 $format = CRM_Utils_Array
::value('date_format', $field);
1201 if (array_key_exists($format, $actualPHPFormats)) {
1202 $customTimeFormat = (array) $actualPHPFormats[$format];
1203 switch (CRM_Utils_Array
::value('time_format', $field)) {
1205 $customTimeFormat[] = 'g:iA';
1209 $customTimeFormat[] = 'G:i';
1213 // if time is not selected remove time from value
1214 $value = substr($value, 0, 10);
1216 $customFormat = implode(" ", $customTimeFormat);
1219 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1223 // In the context of displaying a profile, show file/image
1226 $url = self
::getFileURL($entityId, $field['id']);
1228 $display = $url['file_url'];
1232 // In other contexts show a paperclip icon
1233 if (CRM_Utils_Rule
::integer($value)) {
1234 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1235 $display = $icons[$value];
1238 //CRM-18396, if filename is passed instead
1246 $display = nl2br($display);
1253 * Set default values for custom data used in profile.
1255 * @param int $customFieldId
1257 * @param string $elementName
1258 * Custom field name.
1259 * @param array $defaults
1260 * Associated array of fields.
1261 * @param int $contactId
1265 * @param mixed $value
1266 * If passed - dont fetch value from db,.
1267 * just format the given value
1269 public static function setProfileDefaults(
1277 //get the type of custom field
1278 $customField = new CRM_Core_BAO_CustomField();
1279 $customField->id
= $customFieldId;
1280 $customField->find(TRUE);
1283 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1284 $value = $customField->default_value
;
1288 if (!isset($value)) {
1289 $info = self
::getTableColumnGroup($customFieldId);
1290 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1291 $result = CRM_Core_DAO
::executeQuery($query);
1292 if ($result->fetch()) {
1293 $value = $result->value
;
1297 if ($customField->data_type
== 'Country') {
1299 $config = CRM_Core_Config
::singleton();
1300 if ($config->defaultContactCountry
) {
1301 $value = $config->defaultContactCountry();
1307 //set defaults if mode is registration
1308 if (!trim($value) &&
1310 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1312 $value = $customField->default_value
;
1315 if ($customField->data_type
== 'Money' && isset($value)) {
1316 $value = number_format($value, 2);
1318 switch ($customField->html_type
) {
1320 case 'AdvMulti-Select':
1321 case 'Multi-Select':
1322 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1323 $defaults[$elementName] = array();
1324 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1325 substr($value, 1, -1)
1327 foreach ($customOption as $val) {
1328 if (in_array($val['value'], $checkedValue)) {
1329 if ($customField->html_type
== 'CheckBox') {
1330 $defaults[$elementName][$val['value']] = 1;
1332 elseif ($customField->html_type
== 'Multi-Select' ||
1333 $customField->html_type
== 'AdvMulti-Select'
1335 $defaults[$elementName][$val['value']] = $val['value'];
1341 case 'Autocomplete-Select':
1342 if ($customField->data_type
== 'ContactReference') {
1343 if (is_numeric($value)) {
1344 $defaults[$elementName . '_id'] = $value;
1345 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1349 $defaults[$elementName] = $value;
1354 $defaults[$elementName] = $value;
1361 * @param int $contactID
1363 * @param int $fileID
1364 * @param bool $absolute
1366 * @param string $multiRecordWhereClause
1370 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1373 $params = array('id' => $cfID);
1374 $defaults = array();
1375 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1376 $columnName = $defaults['column_name'];
1378 //table name of custom data
1379 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1380 $defaults['custom_group_id'],
1384 //query to fetch id from civicrm_file
1385 if ($multiRecordWhereClause) {
1386 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1389 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1391 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1396 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1401 $result['file_id'] = $fileID;
1403 if ($fileType == 'image/jpeg' ||
1404 $fileType == 'image/pjpeg' ||
1405 $fileType == 'image/gif' ||
1406 $fileType == 'image/x-png' ||
1407 $fileType == 'image/png'
1409 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1414 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1415 list($imageWidth, $imageHeight) = getimagesize($path);
1416 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1417 $url = CRM_Utils_System
::url('civicrm/file',
1418 "reset=1&id=$fileID&eid=$contactID",
1419 $absolute, NULL, TRUE, TRUE
1421 $result['file_url'] = "
1422 <a href=\"$url\" class='crm-image-popup'>
1423 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1425 // for non image files
1428 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1432 $url = CRM_Utils_System
::url('civicrm/file',
1433 "reset=1&id=$fileID&eid=$contactID",
1434 $absolute, NULL, TRUE, TRUE
1436 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1444 * Format custom fields before inserting.
1446 * @param int $customFieldId
1448 * @param array $customFormatted
1450 * @param mixed $value
1451 * Value of custom field.
1452 * @param string $customFieldExtend
1453 * Custom field extends.
1454 * @param int $customValueId
1455 * Custom option value id.
1456 * @param int $entityId
1457 * Entity id (contribution, membership...).
1458 * @param bool $inline
1459 * Consider inline custom groups only.
1460 * @param bool $checkPermission
1461 * If false, do not include permissioning clause.
1462 * @param bool $includeViewOnly
1463 * If true, fields marked 'View Only' are included. Required for APIv3.
1465 * @return array|NULL
1466 * formatted custom field array
1468 public static function formatCustomField(
1469 $customFieldId, &$customFormatted, $value,
1470 $customFieldExtend, $customValueId = NULL,
1473 $checkPermission = TRUE,
1474 $includeViewOnly = FALSE
1476 //get the custom fields for the entity
1477 //subtype and basic type
1478 $customDataSubType = NULL;
1479 if ($customFieldExtend) {
1480 // This is the case when getFieldsForImport() requires fields
1481 // of subtype and its parent.CRM-5143
1482 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1483 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1484 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1485 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1486 if (is_array($customFieldExtend)) {
1487 $customFieldExtend = array_unique(array_values($customFieldExtend));
1492 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1502 if (!array_key_exists($customFieldId, $customFields)) {
1506 // return if field is a 'code' field
1507 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1511 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1513 if (!$customValueId &&
1514 // we always create new entites for is_multiple unless specified
1515 !$customFields[$customFieldId]['is_multiple'] &&
1521 WHERE entity_id={$entityId}";
1523 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1526 //fix checkbox, now check box always submits values
1527 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1529 // Note that only during merge this is not an array, and you can directly use value
1530 if (is_array($value)) {
1531 $selectedValues = array();
1532 foreach ($value as $selId => $val) {
1534 $selectedValues[] = $selId;
1537 if (!empty($selectedValues)) {
1538 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1540 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1549 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1550 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1553 $value = CRM_Utils_Array
::implodePadded($value);
1560 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1561 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1562 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1564 $customFields[$customFieldId]['data_type'] == 'String' &&
1565 !empty($customFields[$customFieldId]['text_length']) &&
1568 // lets make sure that value is less than the length, else we'll
1569 // be losing some data, CRM-7481
1570 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1571 // need to do a few things here
1573 // 1. lets find a new length
1574 $newLength = $customFields[$customFieldId]['text_length'];
1575 $minLength = strlen($value);
1576 while ($newLength < $minLength) {
1577 $newLength = $newLength * 2;
1580 // set the custom field meta data to have a length larger than value
1581 // alter the custom value table column to match this length
1582 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1587 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1588 if (!CRM_Utils_System
::isNull($value)) {
1589 $format = $customFields[$customFieldId]['date_format'];
1590 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1595 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1596 $customFields[$customFieldId]['data_type'] == 'Money'
1602 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1603 $value = CRM_Utils_Rule
::cleanMoney($value);
1607 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1608 $customFields[$customFieldId]['data_type'] == 'Country'
1618 if ($customFields[$customFieldId]['data_type'] == 'File') {
1619 if (empty($value)) {
1623 $config = CRM_Core_Config
::singleton();
1625 $fName = $value['name'];
1626 $mimeType = $value['type'];
1628 // If we are already passing the file id as a value then retrieve and set the file data
1629 if (CRM_Utils_Rule
::integer($value)) {
1630 $fileDAO = new CRM_Core_DAO_File();
1631 $fileDAO->id
= $value;
1632 $fileDAO->find(TRUE);
1635 $fName = $fileDAO->uri
;
1636 $mimeType = $fileDAO->mime_type
;
1640 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1642 // rename this file to go into the secure directory only if
1643 // user has uploaded new file not existing verfied on the basis of $fileID
1644 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1645 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1648 if ($customValueId && empty($fileID)) {
1653 $params = array(1 => array($customValueId, 'Integer'));
1654 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1657 $fileDAO = new CRM_Core_DAO_File();
1660 $fileDAO->id
= $fileId;
1663 $fileDAO->uri
= $filename;
1664 $fileDAO->mime_type
= $mimeType;
1665 $fileDAO->upload_date
= date('Ymdhis');
1667 $fileId = $fileDAO->id
;
1671 if (!is_array($customFormatted)) {
1672 $customFormatted = array();
1675 if (!array_key_exists($customFieldId, $customFormatted)) {
1676 $customFormatted[$customFieldId] = array();
1680 if ($customValueId) {
1681 $index = $customValueId;
1684 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1685 $customFormatted[$customFieldId][$index] = array();
1687 $customFormatted[$customFieldId][$index] = array(
1688 'id' => $customValueId > 0 ?
$customValueId : NULL,
1690 'type' => $customFields[$customFieldId]['data_type'],
1691 'custom_field_id' => $customFieldId,
1692 'custom_group_id' => $groupID,
1693 'table_name' => $tableName,
1694 'column_name' => $columnName,
1695 'file_id' => $fileId,
1696 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1699 //we need to sort so that custom fields are created in the order of entry
1700 krsort($customFormatted[$customFieldId]);
1701 return $customFormatted;
1705 * Get default custom table schema.
1707 * @param array $params
1711 public static function defaultCustomTableSchema($params) {
1712 // add the id and extends_id
1714 'name' => $params['name'],
1715 'is_multiple' => $params['is_multiple'],
1716 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1720 'type' => 'int unsigned',
1723 'attributes' => 'AUTO_INCREMENT',
1724 'comment' => 'Default MySQL primary key',
1727 'name' => 'entity_id',
1728 'type' => 'int unsigned',
1730 'comment' => 'Table that this extends',
1731 'fk_table_name' => $params['extends_name'],
1732 'fk_field_name' => 'id',
1733 'fk_attributes' => 'ON DELETE CASCADE',
1738 if (!$params['is_multiple']) {
1739 $table['indexes'] = array(
1742 'field_name_1' => 'entity_id',
1750 * Create custom field.
1752 * @param CRM_Core_DAO_CustomField $field
1753 * @param string $operation
1754 * @param bool $indexExist
1755 * @param bool $triggerRebuild
1757 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1758 $tableName = CRM_Core_DAO
::getFieldValue(
1759 'CRM_Core_DAO_CustomGroup',
1760 $field->custom_group_id
,
1765 'table_name' => $tableName,
1766 'operation' => $operation,
1767 'name' => $field->column_name
,
1768 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1772 'required' => $field->is_required
,
1773 'searchable' => $field->is_searchable
,
1776 if ($operation == 'delete') {
1777 $fkName = "{$tableName}_{$field->column_name}";
1778 if (strlen($fkName) >= 48) {
1779 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1781 $params['fkName'] = $fkName;
1783 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1784 $params['fk_table_name'] = 'civicrm_country';
1785 $params['fk_field_name'] = 'id';
1786 $params['fk_attributes'] = 'ON DELETE SET NULL';
1788 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1789 $params['type'] = 'varchar(255)';
1791 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1792 $params['fk_table_name'] = 'civicrm_state_province';
1793 $params['fk_field_name'] = 'id';
1794 $params['fk_attributes'] = 'ON DELETE SET NULL';
1796 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1797 $params['type'] = 'varchar(255)';
1799 elseif ($field->data_type
== 'File') {
1800 $params['fk_table_name'] = 'civicrm_file';
1801 $params['fk_field_name'] = 'id';
1802 $params['fk_attributes'] = 'ON DELETE SET NULL';
1804 elseif ($field->data_type
== 'ContactReference') {
1805 $params['fk_table_name'] = 'civicrm_contact';
1806 $params['fk_field_name'] = 'id';
1807 $params['fk_attributes'] = 'ON DELETE SET NULL';
1809 if (isset($field->default_value
)) {
1810 $params['default'] = "'{$field->default_value}'";
1813 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1817 * Determine whether it would be safe to move a field.
1819 * @param int $fieldID
1820 * FK to civicrm_custom_field.
1821 * @param int $newGroupID
1822 * FK to civicrm_custom_group.
1825 * array(string) or TRUE
1827 public static function _moveFieldValidate($fieldID, $newGroupID) {
1830 $field = new CRM_Core_DAO_CustomField();
1831 $field->id
= $fieldID;
1832 if (!$field->find(TRUE)) {
1833 $errors['fieldID'] = 'Invalid ID for custom field';
1837 $oldGroup = new CRM_Core_DAO_CustomGroup();
1838 $oldGroup->id
= $field->custom_group_id
;
1839 if (!$oldGroup->find(TRUE)) {
1840 $errors['fieldID'] = 'Invalid ID for old custom group';
1844 $newGroup = new CRM_Core_DAO_CustomGroup();
1845 $newGroup->id
= $newGroupID;
1846 if (!$newGroup->find(TRUE)) {
1847 $errors['newGroupID'] = 'Invalid ID for new custom group';
1853 FROM civicrm_custom_field a
1854 INNER JOIN civicrm_custom_field b
1856 AND a.label = b.label
1857 AND b.custom_group_id = %2
1860 1 => array($field->id
, 'Integer'),
1861 2 => array($newGroup->id
, 'Integer'),
1863 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1865 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1868 $tableName = $oldGroup->table_name
;
1869 $columnName = $field->column_name
;
1874 WHERE $columnName is not null
1876 $count = CRM_Core_DAO
::singleValueQuery($query,
1877 CRM_Core_DAO
::$_nullArray
1882 FROM civicrm_custom_group
1883 WHERE id IN ( %1, %2 )
1886 1 => array($oldGroup->id
, 'Integer'),
1887 2 => array($newGroup->id
, 'Integer'),
1890 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1892 while ($dao->fetch()) {
1893 $extends[] = $dao->extends;
1895 if ($extends[0] != $extends[1]) {
1896 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1900 return empty($errors) ?
TRUE : $errors;
1904 * Move a custom data field from one group (table) to another.
1906 * @param int $fieldID
1907 * FK to civicrm_custom_field.
1908 * @param int $newGroupID
1909 * FK to civicrm_custom_group.
1911 public static function moveField($fieldID, $newGroupID) {
1912 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1913 if (TRUE !== $validation) {
1914 CRM_Core_Error
::fatal(implode(' ', $validation));
1916 $field = new CRM_Core_DAO_CustomField();
1917 $field->id
= $fieldID;
1920 $newGroup = new CRM_Core_DAO_CustomGroup();
1921 $newGroup->id
= $newGroupID;
1922 $newGroup->find(TRUE);
1924 $oldGroup = new CRM_Core_DAO_CustomGroup();
1925 $oldGroup->id
= $field->custom_group_id
;
1926 $oldGroup->find(TRUE);
1929 $add->custom_group_id
= $newGroup->id
;
1930 self
::createField($add, 'add');
1932 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1933 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1934 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1936 CRM_Core_DAO
::executeQuery($sql);
1939 $del->custom_group_id
= $oldGroup->id
;
1940 self
::createField($del, 'delete');
1944 CRM_Utils_System
::flushCache();
1948 * Get the database table name and column name for a custom field.
1950 * @param int $fieldID
1951 * The fieldID of the custom field.
1952 * @param bool $force
1953 * Force the sql to be run again (primarily used for tests).
1956 * fatal is fieldID does not exists, else array of tableName, columnName
1958 public static function getTableColumnGroup($fieldID, $force = FALSE) {
1959 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
1960 $cache = CRM_Utils_Cache
::singleton();
1961 $fieldValues = $cache->get($cacheKey);
1962 if (empty($fieldValues) ||
$force) {
1964 SELECT cg.table_name, cf.column_name, cg.id
1965 FROM civicrm_custom_group cg,
1966 civicrm_custom_field cf
1967 WHERE cf.custom_group_id = cg.id
1969 $params = array(1 => array($fieldID, 'Integer'));
1970 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1972 if (!$dao->fetch()) {
1973 CRM_Core_Error
::fatal();
1976 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
1977 $cache->set($cacheKey, $fieldValues);
1979 return $fieldValues;
1983 * Get custom option groups.
1985 * @param array $includeFieldIds
1986 * Ids of custom fields for which option groups must be included.
1988 * Currently this is required in the cases where option groups are to be included
1989 * for inactive fields : CRM-5369
1993 public static function customOptionGroup($includeFieldIds = NULL) {
1994 static $customOptionGroup = NULL;
1996 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
1997 if ($cacheKey == 'force') {
1998 $customOptionGroup[$cacheKey] = NULL;
2001 if (empty($customOptionGroup[$cacheKey])) {
2002 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2004 //support for single as well as array format.
2005 if (!empty($includeFieldIds)) {
2006 if (is_array($includeFieldIds)) {
2007 $includeFieldIds = implode(',', $includeFieldIds);
2009 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2013 SELECT g.id, g.title
2014 FROM civicrm_option_group g
2015 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2016 WHERE {$whereClause}";
2018 $dao = CRM_Core_DAO
::executeQuery($query);
2019 while ($dao->fetch()) {
2020 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2024 return $customOptionGroup[$cacheKey];
2028 * Fix orphan groups.
2030 * @param int $customFieldId
2032 * @param int $optionGroupId
2035 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2036 // check if option group belongs to any custom Field else delete
2037 // get the current option group
2038 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2042 // get the updated option group
2043 // if both are same return
2044 if ($currentOptionGroupId == $optionGroupId) {
2048 // check if option group is related to any other field
2049 self
::checkOptionGroup($currentOptionGroupId);
2053 * Check if option group is related to more than one custom field.
2055 * @param int $optionGroupId
2058 public static function checkOptionGroup($optionGroupId) {
2061 FROM civicrm_custom_field
2062 WHERE option_group_id = {$optionGroupId}";
2064 $count = CRM_Core_DAO
::singleValueQuery($query);
2067 //delete the option group
2068 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2073 * Get option group default.
2075 * @param int $optionGroupId
2076 * @param string $htmlType
2078 * @return null|string
2080 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2082 SELECT default_value, html_type
2083 FROM civicrm_custom_field
2084 WHERE option_group_id = {$optionGroupId}
2085 AND default_value IS NOT NULL
2086 ORDER BY html_type";
2088 $dao = CRM_Core_DAO
::executeQuery($query);
2089 $defaultValue = NULL;
2090 $defaultHTMLType = NULL;
2091 while ($dao->fetch()) {
2092 if ($dao->html_type
== $htmlType) {
2093 return $dao->default_value
;
2095 if ($defaultValue == NULL) {
2096 $defaultValue = $dao->default_value
;
2097 $defaultHTMLType = $dao->html_type
;
2101 // some conversions are needed if either the old or new has a html type which has potential
2102 // multiple default values.
2103 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2104 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2106 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2108 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2109 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2111 $defaultValue = substr($defaultValue, 1, -1);
2112 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2113 substr($defaultValue, 1, -1)
2115 $defaultValue = $values[0];
2118 return $defaultValue;
2122 * Post process function.
2124 * @param array $params
2125 * @param int $entityID
2126 * @param string $customFieldExtends
2127 * @param bool $inline
2128 * @param bool $checkPermissions
2132 public static function postProcess(
2135 $customFieldExtends,
2137 $checkPermissions = TRUE
2139 $customData = array();
2141 foreach ($params as $key => $value) {
2142 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2144 // for autocomplete transfer hidden value instead of label
2145 if ($params[$key] && isset($params[$key . '_id'])) {
2146 $value = $params[$key . '_id'];
2149 // we need to append time with date
2150 if ($params[$key] && isset($params[$key . '_time'])) {
2151 $value .= ' ' . $params[$key . '_time'];
2154 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2157 $customFieldExtends,
2158 $customFieldInfo[1],
2173 * Get custom field ID.
2175 * @param string $fieldLabel
2176 * @param null $groupTitle
2180 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2181 $params = array(1 => array($fieldLabel, 'String'));
2183 $params[2] = array($groupTitle, 'String');
2186 FROM civicrm_custom_field f
2187 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2188 WHERE ( f.label = %1 OR f.name = %1 )
2189 AND ( g.title = %2 OR g.name = %2 )
2195 FROM civicrm_custom_field f
2196 WHERE ( f.label = %1 OR f.name = %1 )
2200 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2201 if ($dao->fetch() &&
2212 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2218 public static function getNameFromID($ids) {
2219 if (is_array($ids)) {
2220 $ids = implode(',', $ids);
2223 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2224 FROM civicrm_custom_field f
2225 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2226 WHERE f.id IN ($ids)";
2228 $dao = CRM_Core_DAO
::executeQuery($sql);
2230 while ($dao->fetch()) {
2231 $result[$dao->id
] = array(
2232 'field_name' => $dao->field_name
,
2233 'field_label' => $dao->field_label
,
2234 'group_name' => $dao->group_name
,
2235 'group_title' => $dao->group_title
,
2242 * Validate custom data.
2244 * @param array $params
2245 * Custom data submitted.
2246 * ie array( 'custom_1' => 'validate me' );
2249 * validation errors.
2251 public static function validateCustomData($params) {
2253 if (!is_array($params) ||
empty($params)) {
2257 //pick up profile fields.
2258 $profileFields = array();
2259 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2261 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2263 CRM_Core_Action
::VIEW
2267 //lets start w/ params.
2268 foreach ($params as $key => $value) {
2269 $customFieldID = self
::getKeyID($key);
2270 if (!$customFieldID) {
2274 //load the structural info for given field.
2275 $field = new CRM_Core_DAO_CustomField();
2276 $field->id
= $customFieldID;
2277 if (!$field->find(TRUE)) {
2280 $dataType = $field->data_type
;
2282 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2283 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2284 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2286 $fieldTitle = $field->label
;
2289 //no need to validate.
2290 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2294 //lets validate first for required field.
2295 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2296 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2300 //now time to take care of custom field form rules.
2301 $ruleName = $errorMsg = NULL;
2302 switch ($dataType) {
2304 $ruleName = 'integer';
2305 $errorMsg = ts('%1 must be an integer (whole number).',
2306 array(1 => $fieldTitle)
2311 $ruleName = 'money';
2312 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2313 array(1 => $fieldTitle)
2318 $ruleName = 'numeric';
2319 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2320 array(1 => $fieldTitle)
2325 $ruleName = 'wikiURL';
2326 $errorMsg = ts('%1 must be valid Website.',
2327 array(1 => $fieldTitle)
2332 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2334 $funName = "CRM_Utils_Rule::{$ruleName}";
2335 if (is_callable($funName)) {
2336 $valid = call_user_func($funName, $value);
2339 $errors[$key] = $errorMsg;
2348 * Is this field a multi record field.
2350 * @param int $customId
2354 public static function isMultiRecordField($customId) {
2355 $isMultipleWithGid = FALSE;
2356 if (!is_numeric($customId)) {
2357 $customId = self
::getKeyID($customId);
2359 if (is_numeric($customId)) {
2360 $sql = "SELECT cg.id cgId
2361 FROM civicrm_custom_group cg
2362 INNER JOIN civicrm_custom_field cf
2363 ON cg.id = cf.custom_group_id
2364 WHERE cf.id = %1 AND cg.is_multiple = 1";
2365 $params[1] = array($customId, 'Integer');
2366 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2367 if ($dao->fetch()) {
2369 $isMultipleWithGid = $dao->cgId
;
2374 return $isMultipleWithGid;
2378 * Does this field store a serialized string?
2380 * @param array $field
2384 public static function isSerialized($field) {
2385 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2386 $field = (array) $field;
2387 // 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.
2388 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2392 * Get api entity for this field
2396 public function getEntity() {
2397 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2398 return in_array($entity, array('Individual', 'Household', 'Organization')) ?
'Contact' : $entity;
2402 * Set pseudoconstant properties for field metadata.
2404 * @param array $field
2405 * @param string|null $optionGroupName
2407 private static function getOptionsForField(&$field, $optionGroupName) {
2408 if ($optionGroupName) {
2409 $field['pseudoconstant'] = array(
2410 'optionGroupName' => $optionGroupName,
2411 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2414 elseif ($field['data_type'] == 'Boolean') {
2415 $field['pseudoconstant'] = array(
2416 'callback' => 'CRM_Core_SelectValues::boolean',
2419 elseif ($field['data_type'] == 'Country') {
2420 $field['pseudoconstant'] = array(
2421 'table' => 'civicrm_country',
2422 'keyColumn' => 'id',
2423 'labelColumn' => 'name',
2424 'nameColumn' => 'iso_code',
2427 elseif ($field['data_type'] == 'StateProvince') {
2428 $field['pseudoconstant'] = array(
2429 'table' => 'civicrm_state_province',
2430 'keyColumn' => 'id',
2431 'labelColumn' => 'name',