3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 $cgTable.extends, $cfTable.is_search_range,
546 $cgTable.extends_entity_column_value,
547 $cgTable.extends_entity_column_id,
549 $cfTable.option_group_id,
550 $cfTable.date_format,
551 $cfTable.time_format,
552 $cgTable.is_multiple,
553 og.name as option_group_name
556 ON $cfTable.custom_group_id = $cgTable.id
557 LEFT JOIN civicrm_option_group og
558 ON $cfTable.option_group_id = og.id
562 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
566 $query .= " AND $cgTable.style = 'Inline' ";
569 //get the custom fields for specific type in
570 //combination with fields those support any type.
571 if (!empty($customDataSubType)) {
572 $subtypeClause = array();
573 foreach ($customDataSubType as $subtype) {
574 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
575 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
578 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
580 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
583 if ($customDataSubName) {
584 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
587 // also get the permission stuff here
588 if ($checkPermission) {
589 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
594 $permissionClause = '(1)';
597 $query .= " $extends AND $permissionClause
598 ORDER BY $cgTable.weight, $cgTable.title,
599 $cfTable.weight, $cfTable.label";
601 $dao = CRM_Core_DAO
::executeQuery($query);
604 while (($dao->fetch()) != NULL) {
605 $fields[$dao->id
]['label'] = $dao->label
;
606 $fields[$dao->id
]['groupTitle'] = $dao->title
;
607 $fields[$dao->id
]['data_type'] = $dao->data_type
;
608 $fields[$dao->id
]['html_type'] = $dao->html_type
;
609 $fields[$dao->id
]['default_value'] = $dao->default_value
;
610 $fields[$dao->id
]['text_length'] = $dao->text_length
;
611 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
612 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
613 $fields[$dao->id
]['extends'] = $dao->extends;
614 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
615 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
616 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
617 $fields[$dao->id
]['is_view'] = $dao->is_view
;
618 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
619 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
620 $fields[$dao->id
]['date_format'] = $dao->date_format
;
621 $fields[$dao->id
]['time_format'] = $dao->time_format
;
622 $fields[$dao->id
]['is_required'] = $dao->is_required
;
623 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
626 CRM_Core_BAO_Cache
::setItem($fields,
628 "custom importableFields $cacheKey"
631 self
::$_importFields[$cacheKey] = $fields;
634 return self
::$_importFields[$cacheKey];
638 * Return the field ids and names (with groups) for import purpose.
640 * @param int|string $contactType Contact type
641 * @param bool $showAll
642 * If true returns all fields (includes disabled fields).
643 * @param bool $onlyParent
644 * Return fields ONLY related to basic types.
645 * @param bool $search
646 * When called from search and multiple records need to be returned.
647 * @param bool $checkPermission
648 * If false, do not include permissioning clause.
650 * @param bool $withMultiple
654 public static function getFieldsForImport(
655 $contactType = 'Individual',
659 $checkPermission = TRUE,
660 $withMultiple = FALSE
662 // Note: there are situations when we want getFieldsForImport() return fields related
663 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
664 $fields = &self
::getFields($contactType,
674 $importableFields = array();
675 foreach ($fields as $id => $values) {
676 // for now we should not allow multiple fields in profile / export etc, hence unsetting
678 (!empty($values['is_multiple']) && !$withMultiple)
683 /* generate the key for the fields array */
687 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
688 $importableFields[$key] = array(
690 'title' => CRM_Utils_Array
::value('label', $values),
691 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
693 'custom_field_id' => $id,
694 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
695 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
696 'data_type' => CRM_Utils_Array
::value('data_type', $values),
697 'html_type' => CRM_Utils_Array
::value('html_type', $values),
698 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
701 // CRM-6681, pass date and time format when html_type = Select Date
702 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
703 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
704 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
708 return $importableFields;
712 * Get the field id from an import key.
722 public static function getKeyID($key, $all = FALSE) {
724 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
731 CRM_Utils_Array
::value(2, $match),
735 return $all ?
array(NULL, NULL) : NULL;
739 * Use the cache to get all values of a specific custom field.
741 * @param int $fieldID
742 * The custom field ID.
744 * @return CRM_Core_BAO_CustomField
747 public static function getFieldObject($fieldID) {
748 $field = new CRM_Core_BAO_CustomField();
750 // check if we can get the field values from the system cache
751 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
752 $cache = CRM_Utils_Cache
::singleton();
753 $fieldValues = $cache->get($cacheKey);
754 if (empty($fieldValues)) {
755 $field->id
= $fieldID;
756 if (!$field->find(TRUE)) {
757 CRM_Core_Error
::fatal();
760 $fieldValues = array();
761 CRM_Core_DAO
::storeValues($field, $fieldValues);
763 $cache->set($cacheKey, $fieldValues);
766 $field->copyValues($fieldValues);
773 * Add a custom field to an existing form.
775 * @param CRM_Core_Form $qf
776 * Form object (reference).
777 * @param string $elementName
778 * Name of the custom field.
779 * @param int $fieldId
780 * @param bool $useRequired
781 * True if required else false.
782 * @param bool $search
783 * True if used for search else false.
784 * @param string $label
785 * Label for custom field.
786 * @return \HTML_QuickForm_Element|null
787 * @throws \CiviCRM_API3_Exception
789 public static function addQuickFormElement(
790 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
792 $field = self
::getFieldObject($fieldId);
793 $widget = $field->html_type
;
796 // Custom field HTML should indicate group+field name
797 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
798 $dataCrmCustomVal = $groupName . ':' . $field->name
;
799 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
800 $field->attributes
.= $dataCrmCustomAttr;
802 // Fixed for Issue CRM-2183
803 if ($widget == 'TextArea' && $search) {
807 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
809 // FIXME: Why are select state/country separate widget types?
810 $isSelect = (in_array($widget, array(
813 'Select State/Province',
814 'Multi-Select State/Province',
816 'Multi-Select Country',
823 $options = $field->getOptions($search ?
'search' : 'create');
825 // Consolidate widget types to simplify the below switch statement
826 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
829 $selectAttributes = array(
830 'data-crm-custom' => $dataCrmCustomVal,
831 'class' => 'crm-select2',
833 // Search field is always multi-select
834 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
835 $selectAttributes['class'] .= ' huge';
836 $selectAttributes['multiple'] = 'multiple';
837 $selectAttributes['placeholder'] = $placeholder;
839 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
840 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
841 $selectAttributes +
= array(
842 'data-api-entity' => $field->getEntity(),
843 'data-api-field' => 'custom_' . $field->id
,
844 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
849 if (!isset($label)) {
850 $label = $field->label
;
853 // at some point in time we might want to split the below into small functions
858 if ($field->is_search_range
&& $search) {
859 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
860 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
863 $element = $qf->add('text', $elementName, $label,
865 $useRequired && !$search
871 $attributes = $dataCrmCustomAttr;
872 if ($field->note_rows
) {
873 $attributes .= 'rows=' . $field->note_rows
;
876 $attributes .= 'rows=4';
878 if ($field->note_columns
) {
879 $attributes .= ' cols=' . $field->note_columns
;
882 $attributes .= ' cols=60';
884 if ($field->text_length
) {
885 $attributes .= ' maxlength=' . $field->text_length
;
887 $element = $qf->add('textarea',
891 $useRequired && !$search
896 $attr = array('data-crm-custom' => $dataCrmCustomVal);
898 'date' => $field->date_format
,
899 'minDate' => isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) . '-01-01' : NULL,
900 'maxDate' => isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) . '-01-01' : NULL,
901 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
903 if ($field->is_search_range
&& $search) {
904 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
905 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
908 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
914 foreach ($options as $v => $l) {
915 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
917 $element = $qf->addGroup($choice, $elementName, $label);
918 if ($useRequired && !$search) {
919 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
922 $element->setAttribute('allowClear', TRUE);
926 // For all select elements
928 if (empty($selectAttributes['multiple'])) {
929 $options = array('' => $placeholder) +
$options;
931 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
933 // Add and/or option for fields that store multiple values
934 if ($search && self
::isSerialized($field)) {
937 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
938 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
940 $qf->addGroup($operators, $elementName . '_operator');
941 $qf->setDefaults(array($elementName . '_operator' => 'or'));
945 case 'AdvMulti-Select':
946 $element = $qf->addElement(
953 'class' => 'advmultiselect',
954 'data-crm-custom' => $dataCrmCustomVal,
958 $element->setButtonAttributes('add', array('value' => ts('Add >>')));
959 $element->setButtonAttributes('remove', array('value' => ts('<< Remove')));
961 if ($useRequired && !$search) {
962 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
968 foreach ($options as $v => $l) {
969 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
971 $element = $qf->addGroup($check, $elementName, $label);
972 if ($useRequired && !$search) {
973 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
978 // we should not build upload file in search mode
983 strtolower($field->html_type
),
987 $useRequired && !$search
989 $qf->addUploadElement($elementName);
992 case 'RichTextEditor':
994 'rows' => $field->note_rows
,
995 'cols' => $field->note_columns
,
996 'data-crm-custom' => $dataCrmCustomVal,
998 if ($field->text_length
) {
999 $attributes['maxlength'] = $field->text_length
;
1001 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $search);
1004 case 'Autocomplete-Select':
1005 static $customUrls = array();
1006 // Fixme: why is this a string in the first place??
1007 $attributes = array();
1008 if ($field->attributes
) {
1009 foreach (explode(' ', $field->attributes
) as $at) {
1010 if (strpos($at, '=')) {
1011 list($k, $v) = explode('=', $at);
1012 $attributes[$k] = trim($v, ' "');
1016 if ($field->data_type
== 'ContactReference') {
1017 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1018 $attributes['data-api-entity'] = 'Contact';
1019 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
1021 $urlParams = "context=customfield&id={$field->id}";
1023 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1030 // FIXME: This won't work with customFieldOptions hook
1031 $attributes +
= array(
1032 'entity' => 'option_value',
1033 'placeholder' => $placeholder,
1034 'multiple' => $search,
1036 'params' => array('option_group_id' => $field->option_group_id
),
1039 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1042 $qf->assign('customUrls', $customUrls);
1046 switch ($field->data_type
) {
1048 // integers will have numeric rule applied to them.
1049 if ($field->is_search_range
&& $search) {
1050 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1051 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1053 elseif ($widget == 'Text') {
1054 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1059 if ($field->is_search_range
&& $search) {
1060 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1061 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1063 elseif ($widget == 'Text') {
1064 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1069 if ($field->is_search_range
&& $search) {
1070 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1071 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1073 elseif ($widget == 'Text') {
1074 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1079 $element->setAttribute('class', "url");
1080 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1083 if ($field->is_view
&& !$search) {
1084 $qf->freeze($elementName);
1090 * Delete the Custom Field.
1092 * @param object $field
1095 public static function deleteField($field) {
1096 CRM_Utils_System
::flushCache();
1098 // first delete the custom option group and values associated with this field
1099 if ($field->option_group_id
) {
1100 //check if option group is related to any other field, if
1101 //not delete the option group and related option values
1102 self
::checkOptionGroup($field->option_group_id
);
1105 // next drop the column from the custom value table
1106 self
::createField($field, 'delete');
1109 CRM_Core_BAO_UFField
::delUFField($field->id
);
1110 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1114 * @param string|int|array|null $value
1115 * @param CRM_Core_BAO_CustomField|int|array|string $field
1119 * @throws \Exception
1121 public static function displayValue($value, $field, $contactId = NULL) {
1122 $field = is_array($field) ?
$field['id'] : $field;
1123 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1126 throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1129 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1130 $field = self
::getFieldObject($fieldId);
1133 $fieldInfo = array('options' => $field->getOptions()) +
(array) $field;
1135 return self
::formatDisplayValue($value, $fieldInfo, $contactId);
1139 * Lower-level logic for rendering a custom field value
1141 * @param string|array $value
1142 * @param array $field
1143 * @param int|null $contactID
1147 private static function formatDisplayValue($value, $field, $contactID = NULL) {
1149 if (self
::isSerialized($field) && !is_array($value)) {
1150 $value = CRM_Utils_Array
::explodePadded($value);
1153 if ($field['html_type'] == 'CheckBox') {
1154 CRM_Utils_Array
::formatArrayKeys($value);
1157 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1159 switch ($field['html_type']) {
1162 case 'Autocomplete-Select':
1164 case 'Select Country':
1165 case 'Select State/Province':
1167 case 'AdvMulti-Select':
1168 case 'Multi-Select':
1169 case 'Multi-Select State/Province':
1170 case 'Multi-Select Country':
1171 if ($field['data_type'] == 'ContactReference' && $value) {
1172 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1174 elseif (is_array($value)) {
1176 foreach ($value as $key => $val) {
1177 $v[] = CRM_Utils_Array
::value($val, $field['options']);
1179 $display = implode(', ', $v);
1182 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1187 $customFormat = NULL;
1189 // FIXME: Are there any legitimate reasons why $value would be an array?
1190 // Or should we throw an exception here if it is?
1191 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1193 $actualPHPFormats = CRM_Core_SelectValues
::datePluginToPHPFormats();
1194 $format = CRM_Utils_Array
::value('date_format', $field);
1197 if (array_key_exists($format, $actualPHPFormats)) {
1198 $customTimeFormat = (array) $actualPHPFormats[$format];
1199 switch (CRM_Utils_Array
::value('time_format', $field)) {
1201 $customTimeFormat[] = 'g:iA';
1205 $customTimeFormat[] = 'G:i';
1209 // if time is not selected remove time from value
1210 $value = substr($value, 0, 10);
1212 $customFormat = implode(" ", $customTimeFormat);
1215 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1219 // In the context of displaying a profile, show file/image
1220 if ($contactID && $value) {
1221 $url = self
::getFileURL($contactID, $field['id'], $value);
1223 $display = $url['file_url'];
1226 // In other contexts show a paperclip icon
1228 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1229 $display = $icons[$value];
1234 $display = nl2br($display);
1241 * Set default values for custom data used in profile.
1243 * @param int $customFieldId
1245 * @param string $elementName
1246 * Custom field name.
1247 * @param array $defaults
1248 * Associated array of fields.
1249 * @param int $contactId
1253 * @param mixed $value
1254 * If passed - dont fetch value from db,.
1255 * just format the given value
1257 public static function setProfileDefaults(
1265 //get the type of custom field
1266 $customField = new CRM_Core_BAO_CustomField();
1267 $customField->id
= $customFieldId;
1268 $customField->find(TRUE);
1271 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1272 $value = $customField->default_value
;
1276 if (!isset($value)) {
1277 $info = self
::getTableColumnGroup($customFieldId);
1278 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1279 $result = CRM_Core_DAO
::executeQuery($query);
1280 if ($result->fetch()) {
1281 $value = $result->value
;
1285 if ($customField->data_type
== 'Country') {
1287 $config = CRM_Core_Config
::singleton();
1288 if ($config->defaultContactCountry
) {
1289 $value = $config->defaultContactCountry();
1295 //set defaults if mode is registration
1296 if (!trim($value) &&
1298 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1300 $value = $customField->default_value
;
1303 if ($customField->data_type
== 'Money' && isset($value)) {
1304 $value = number_format($value, 2);
1306 switch ($customField->html_type
) {
1308 case 'AdvMulti-Select':
1309 case 'Multi-Select':
1310 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1311 $defaults[$elementName] = array();
1312 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1313 substr($value, 1, -1)
1315 foreach ($customOption as $val) {
1316 if (in_array($val['value'], $checkedValue)) {
1317 if ($customField->html_type
== 'CheckBox') {
1318 $defaults[$elementName][$val['value']] = 1;
1320 elseif ($customField->html_type
== 'Multi-Select' ||
1321 $customField->html_type
== 'AdvMulti-Select'
1323 $defaults[$elementName][$val['value']] = $val['value'];
1329 case 'Autocomplete-Select':
1330 if ($customField->data_type
== 'ContactReference') {
1331 if (is_numeric($value)) {
1332 $defaults[$elementName . '_id'] = $value;
1333 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1337 $defaults[$elementName] = $value;
1342 $defaults[$elementName] = $value;
1349 * @param int $contactID
1351 * @param int $fileID
1352 * @param bool $absolute
1354 * @param string $multiRecordWhereClause
1358 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1361 $params = array('id' => $cfID);
1362 $defaults = array();
1363 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1364 $columnName = $defaults['column_name'];
1366 //table name of custom data
1367 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1368 $defaults['custom_group_id'],
1372 //query to fetch id from civicrm_file
1373 if ($multiRecordWhereClause) {
1374 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1377 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1379 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1384 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1389 $result['file_id'] = $fileID;
1391 if ($fileType == 'image/jpeg' ||
1392 $fileType == 'image/pjpeg' ||
1393 $fileType == 'image/gif' ||
1394 $fileType == 'image/x-png' ||
1395 $fileType == 'image/png'
1397 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1402 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1403 list($imageWidth, $imageHeight) = getimagesize($path);
1404 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1405 $url = CRM_Utils_System
::url('civicrm/file',
1406 "reset=1&id=$fileID&eid=$contactID",
1407 $absolute, NULL, TRUE, TRUE
1409 $result['file_url'] = "
1410 <a href=\"$url\" class='crm-image-popup'>
1411 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1413 // for non image files
1416 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1420 $url = CRM_Utils_System
::url('civicrm/file',
1421 "reset=1&id=$fileID&eid=$contactID",
1422 $absolute, NULL, TRUE, TRUE
1424 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1432 * Format custom fields before inserting.
1434 * @param int $customFieldId
1436 * @param array $customFormatted
1438 * @param mixed $value
1439 * Value of custom field.
1440 * @param string $customFieldExtend
1441 * Custom field extends.
1442 * @param int $customValueId
1443 * Custom option value id.
1444 * @param int $entityId
1445 * Entity id (contribution, membership...).
1446 * @param bool $inline
1447 * Consider inline custom groups only.
1448 * @param bool $checkPermission
1449 * If false, do not include permissioning clause.
1450 * @param bool $includeViewOnly
1451 * If true, fields marked 'View Only' are included. Required for APIv3.
1453 * @return array|NULL
1454 * formatted custom field array
1456 public static function formatCustomField(
1457 $customFieldId, &$customFormatted, $value,
1458 $customFieldExtend, $customValueId = NULL,
1461 $checkPermission = TRUE,
1462 $includeViewOnly = FALSE
1464 //get the custom fields for the entity
1465 //subtype and basic type
1466 $customDataSubType = NULL;
1467 if ($customFieldExtend) {
1468 // This is the case when getFieldsForImport() requires fields
1469 // of subtype and its parent.CRM-5143
1470 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1471 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1472 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1473 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1474 if (is_array($customFieldExtend)) {
1475 $customFieldExtend = array_unique(array_values($customFieldExtend));
1480 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1490 if (!array_key_exists($customFieldId, $customFields)) {
1494 // return if field is a 'code' field
1495 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1499 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1501 if (!$customValueId &&
1502 // we always create new entites for is_multiple unless specified
1503 !$customFields[$customFieldId]['is_multiple'] &&
1509 WHERE entity_id={$entityId}";
1511 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1514 //fix checkbox, now check box always submits values
1515 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1517 // Note that only during merge this is not an array, and you can directly use value
1518 if (is_array($value)) {
1519 $selectedValues = array();
1520 foreach ($value as $selId => $val) {
1522 $selectedValues[] = $selId;
1525 if (!empty($selectedValues)) {
1526 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1528 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1537 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1538 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1541 $value = CRM_Utils_Array
::implodePadded($value);
1548 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1549 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1550 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1552 $customFields[$customFieldId]['data_type'] == 'String' &&
1553 !empty($customFields[$customFieldId]['text_length']) &&
1556 // lets make sure that value is less than the length, else we'll
1557 // be losing some data, CRM-7481
1558 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1559 // need to do a few things here
1561 // 1. lets find a new length
1562 $newLength = $customFields[$customFieldId]['text_length'];
1563 $minLength = strlen($value);
1564 while ($newLength < $minLength) {
1565 $newLength = $newLength * 2;
1568 // set the custom field meta data to have a length larger than value
1569 // alter the custom value table column to match this length
1570 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1575 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1576 if (!CRM_Utils_System
::isNull($value)) {
1577 $format = $customFields[$customFieldId]['date_format'];
1578 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1583 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1584 $customFields[$customFieldId]['data_type'] == 'Money'
1590 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1591 $value = CRM_Utils_Rule
::cleanMoney($value);
1595 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1596 $customFields[$customFieldId]['data_type'] == 'Country'
1606 if ($customFields[$customFieldId]['data_type'] == 'File') {
1607 if (empty($value)) {
1611 $config = CRM_Core_Config
::singleton();
1613 $fName = $value['name'];
1614 $mimeType = $value['type'];
1616 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1618 // rename this file to go into the secure directory
1619 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1620 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1623 if ($customValueId) {
1628 $params = array(1 => array($customValueId, 'Integer'));
1629 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1632 $fileDAO = new CRM_Core_DAO_File();
1635 $fileDAO->id
= $fileId;
1638 $fileDAO->uri
= $filename;
1639 $fileDAO->mime_type
= $mimeType;
1640 $fileDAO->upload_date
= date('Ymdhis');
1642 $fileId = $fileDAO->id
;
1646 if (!is_array($customFormatted)) {
1647 $customFormatted = array();
1650 if (!array_key_exists($customFieldId, $customFormatted)) {
1651 $customFormatted[$customFieldId] = array();
1655 if ($customValueId) {
1656 $index = $customValueId;
1659 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1660 $customFormatted[$customFieldId][$index] = array();
1662 $customFormatted[$customFieldId][$index] = array(
1663 'id' => $customValueId > 0 ?
$customValueId : NULL,
1665 'type' => $customFields[$customFieldId]['data_type'],
1666 'custom_field_id' => $customFieldId,
1667 'custom_group_id' => $groupID,
1668 'table_name' => $tableName,
1669 'column_name' => $columnName,
1670 'file_id' => $fileId,
1671 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1674 //we need to sort so that custom fields are created in the order of entry
1675 krsort($customFormatted[$customFieldId]);
1676 return $customFormatted;
1680 * Get default custom table schema.
1682 * @param array $params
1686 public static function defaultCustomTableSchema($params) {
1687 // add the id and extends_id
1689 'name' => $params['name'],
1690 'is_multiple' => $params['is_multiple'],
1691 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1695 'type' => 'int unsigned',
1698 'attributes' => 'AUTO_INCREMENT',
1699 'comment' => 'Default MySQL primary key',
1702 'name' => 'entity_id',
1703 'type' => 'int unsigned',
1705 'comment' => 'Table that this extends',
1706 'fk_table_name' => $params['extends_name'],
1707 'fk_field_name' => 'id',
1708 'fk_attributes' => 'ON DELETE CASCADE',
1713 if (!$params['is_multiple']) {
1714 $table['indexes'] = array(
1717 'field_name_1' => 'entity_id',
1725 * Create custom field.
1727 * @param CRM_Core_DAO_CustomField $field
1728 * @param string $operation
1729 * @param bool $indexExist
1730 * @param bool $triggerRebuild
1732 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1733 $tableName = CRM_Core_DAO
::getFieldValue(
1734 'CRM_Core_DAO_CustomGroup',
1735 $field->custom_group_id
,
1740 'table_name' => $tableName,
1741 'operation' => $operation,
1742 'name' => $field->column_name
,
1743 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1747 'required' => $field->is_required
,
1748 'searchable' => $field->is_searchable
,
1751 if ($operation == 'delete') {
1752 $fkName = "{$tableName}_{$field->column_name}";
1753 if (strlen($fkName) >= 48) {
1754 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1756 $params['fkName'] = $fkName;
1758 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1759 $params['fk_table_name'] = 'civicrm_country';
1760 $params['fk_field_name'] = 'id';
1761 $params['fk_attributes'] = 'ON DELETE SET NULL';
1763 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1764 $params['type'] = 'varchar(255)';
1766 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1767 $params['fk_table_name'] = 'civicrm_state_province';
1768 $params['fk_field_name'] = 'id';
1769 $params['fk_attributes'] = 'ON DELETE SET NULL';
1771 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1772 $params['type'] = 'varchar(255)';
1774 elseif ($field->data_type
== 'File') {
1775 $params['fk_table_name'] = 'civicrm_file';
1776 $params['fk_field_name'] = 'id';
1777 $params['fk_attributes'] = 'ON DELETE SET NULL';
1779 elseif ($field->data_type
== 'ContactReference') {
1780 $params['fk_table_name'] = 'civicrm_contact';
1781 $params['fk_field_name'] = 'id';
1782 $params['fk_attributes'] = 'ON DELETE SET NULL';
1784 if (isset($field->default_value
)) {
1785 $params['default'] = "'{$field->default_value}'";
1788 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1792 * Determine whether it would be safe to move a field.
1794 * @param int $fieldID
1795 * FK to civicrm_custom_field.
1796 * @param int $newGroupID
1797 * FK to civicrm_custom_group.
1800 * array(string) or TRUE
1802 public static function _moveFieldValidate($fieldID, $newGroupID) {
1805 $field = new CRM_Core_DAO_CustomField();
1806 $field->id
= $fieldID;
1807 if (!$field->find(TRUE)) {
1808 $errors['fieldID'] = 'Invalid ID for custom field';
1812 $oldGroup = new CRM_Core_DAO_CustomGroup();
1813 $oldGroup->id
= $field->custom_group_id
;
1814 if (!$oldGroup->find(TRUE)) {
1815 $errors['fieldID'] = 'Invalid ID for old custom group';
1819 $newGroup = new CRM_Core_DAO_CustomGroup();
1820 $newGroup->id
= $newGroupID;
1821 if (!$newGroup->find(TRUE)) {
1822 $errors['newGroupID'] = 'Invalid ID for new custom group';
1828 FROM civicrm_custom_field a
1829 INNER JOIN civicrm_custom_field b
1831 AND a.label = b.label
1832 AND b.custom_group_id = %2
1835 1 => array($field->id
, 'Integer'),
1836 2 => array($newGroup->id
, 'Integer'),
1838 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1840 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1843 $tableName = $oldGroup->table_name
;
1844 $columnName = $field->column_name
;
1849 WHERE $columnName is not null
1851 $count = CRM_Core_DAO
::singleValueQuery($query,
1852 CRM_Core_DAO
::$_nullArray
1857 FROM civicrm_custom_group
1858 WHERE id IN ( %1, %2 )
1861 1 => array($oldGroup->id
, 'Integer'),
1862 2 => array($newGroup->id
, 'Integer'),
1865 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1867 while ($dao->fetch()) {
1868 $extends[] = $dao->extends;
1870 if ($extends[0] != $extends[1]) {
1871 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1875 return empty($errors) ?
TRUE : $errors;
1879 * Move a custom data field from one group (table) to another.
1881 * @param int $fieldID
1882 * FK to civicrm_custom_field.
1883 * @param int $newGroupID
1884 * FK to civicrm_custom_group.
1886 public static function moveField($fieldID, $newGroupID) {
1887 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1888 if (TRUE !== $validation) {
1889 CRM_Core_Error
::fatal(implode(' ', $validation));
1891 $field = new CRM_Core_DAO_CustomField();
1892 $field->id
= $fieldID;
1895 $newGroup = new CRM_Core_DAO_CustomGroup();
1896 $newGroup->id
= $newGroupID;
1897 $newGroup->find(TRUE);
1899 $oldGroup = new CRM_Core_DAO_CustomGroup();
1900 $oldGroup->id
= $field->custom_group_id
;
1901 $oldGroup->find(TRUE);
1904 $add->custom_group_id
= $newGroup->id
;
1905 self
::createField($add, 'add');
1907 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1908 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1909 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1911 CRM_Core_DAO
::executeQuery($sql);
1914 $del->custom_group_id
= $oldGroup->id
;
1915 self
::createField($del, 'delete');
1919 CRM_Utils_System
::flushCache();
1923 * Get the database table name and column name for a custom field.
1925 * @param int $fieldID
1926 * The fieldID of the custom field.
1927 * @param bool $force
1928 * Force the sql to be run again (primarily used for tests).
1931 * fatal is fieldID does not exists, else array of tableName, columnName
1933 public static function getTableColumnGroup($fieldID, $force = FALSE) {
1934 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
1935 $cache = CRM_Utils_Cache
::singleton();
1936 $fieldValues = $cache->get($cacheKey);
1937 if (empty($fieldValues) ||
$force) {
1939 SELECT cg.table_name, cf.column_name, cg.id
1940 FROM civicrm_custom_group cg,
1941 civicrm_custom_field cf
1942 WHERE cf.custom_group_id = cg.id
1944 $params = array(1 => array($fieldID, 'Integer'));
1945 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1947 if (!$dao->fetch()) {
1948 CRM_Core_Error
::fatal();
1951 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
1952 $cache->set($cacheKey, $fieldValues);
1954 return $fieldValues;
1958 * Get custom option groups.
1960 * @param array $includeFieldIds
1961 * Ids of custom fields for which option groups must be included.
1963 * Currently this is required in the cases where option groups are to be included
1964 * for inactive fields : CRM-5369
1968 public static function customOptionGroup($includeFieldIds = NULL) {
1969 static $customOptionGroup = NULL;
1971 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
1972 if ($cacheKey == 'force') {
1973 $customOptionGroup[$cacheKey] = NULL;
1976 if (empty($customOptionGroup[$cacheKey])) {
1977 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
1979 //support for single as well as array format.
1980 if (!empty($includeFieldIds)) {
1981 if (is_array($includeFieldIds)) {
1982 $includeFieldIds = implode(',', $includeFieldIds);
1984 $whereClause .= "OR f.id IN ( $includeFieldIds )";
1988 SELECT g.id, g.title
1989 FROM civicrm_option_group g
1990 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
1991 WHERE {$whereClause}";
1993 $dao = CRM_Core_DAO
::executeQuery($query);
1994 while ($dao->fetch()) {
1995 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
1999 return $customOptionGroup[$cacheKey];
2003 * Fix orphan groups.
2005 * @param int $customFieldId
2007 * @param int $optionGroupId
2010 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2011 // check if option group belongs to any custom Field else delete
2012 // get the current option group
2013 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2017 // get the updated option group
2018 // if both are same return
2019 if ($currentOptionGroupId == $optionGroupId) {
2023 // check if option group is related to any other field
2024 self
::checkOptionGroup($currentOptionGroupId);
2028 * Check if option group is related to more than one custom field.
2030 * @param int $optionGroupId
2033 public static function checkOptionGroup($optionGroupId) {
2036 FROM civicrm_custom_field
2037 WHERE option_group_id = {$optionGroupId}";
2039 $count = CRM_Core_DAO
::singleValueQuery($query);
2042 //delete the option group
2043 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2048 * Get option group default.
2050 * @param int $optionGroupId
2051 * @param string $htmlType
2053 * @return null|string
2055 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2057 SELECT default_value, html_type
2058 FROM civicrm_custom_field
2059 WHERE option_group_id = {$optionGroupId}
2060 AND default_value IS NOT NULL
2061 ORDER BY html_type";
2063 $dao = CRM_Core_DAO
::executeQuery($query);
2064 $defaultValue = NULL;
2065 $defaultHTMLType = NULL;
2066 while ($dao->fetch()) {
2067 if ($dao->html_type
== $htmlType) {
2068 return $dao->default_value
;
2070 if ($defaultValue == NULL) {
2071 $defaultValue = $dao->default_value
;
2072 $defaultHTMLType = $dao->html_type
;
2076 // some conversions are needed if either the old or new has a html type which has potential
2077 // multiple default values.
2078 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2079 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2081 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2083 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2084 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2086 $defaultValue = substr($defaultValue, 1, -1);
2087 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2088 substr($defaultValue, 1, -1)
2090 $defaultValue = $values[0];
2093 return $defaultValue;
2097 * Post process function.
2099 * @param array $params
2100 * @param int $entityID
2101 * @param string $customFieldExtends
2102 * @param bool $inline
2103 * @param bool $checkPermissions
2107 public static function postProcess(
2110 $customFieldExtends,
2112 $checkPermissions = TRUE
2114 $customData = array();
2116 foreach ($params as $key => $value) {
2117 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2119 // for autocomplete transfer hidden value instead of label
2120 if ($params[$key] && isset($params[$key . '_id'])) {
2121 $value = $params[$key . '_id'];
2124 // we need to append time with date
2125 if ($params[$key] && isset($params[$key . '_time'])) {
2126 $value .= ' ' . $params[$key . '_time'];
2129 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2132 $customFieldExtends,
2133 $customFieldInfo[1],
2148 * Get custom field ID.
2150 * @param string $fieldLabel
2151 * @param null $groupTitle
2155 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2156 $params = array(1 => array($fieldLabel, 'String'));
2158 $params[2] = array($groupTitle, 'String');
2161 FROM civicrm_custom_field f
2162 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2163 WHERE ( f.label = %1 OR f.name = %1 )
2164 AND ( g.title = %2 OR g.name = %2 )
2170 FROM civicrm_custom_field f
2171 WHERE ( f.label = %1 OR f.name = %1 )
2175 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2176 if ($dao->fetch() &&
2187 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2193 public static function getNameFromID($ids) {
2194 if (is_array($ids)) {
2195 $ids = implode(',', $ids);
2198 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2199 FROM civicrm_custom_field f
2200 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2201 WHERE f.id IN ($ids)";
2203 $dao = CRM_Core_DAO
::executeQuery($sql);
2205 while ($dao->fetch()) {
2206 $result[$dao->id
] = array(
2207 'field_name' => $dao->field_name
,
2208 'field_label' => $dao->field_label
,
2209 'group_name' => $dao->group_name
,
2210 'group_title' => $dao->group_title
,
2217 * Validate custom data.
2219 * @param array $params
2220 * Custom data submitted.
2221 * ie array( 'custom_1' => 'validate me' );
2224 * validation errors.
2226 public static function validateCustomData($params) {
2228 if (!is_array($params) ||
empty($params)) {
2232 //pick up profile fields.
2233 $profileFields = array();
2234 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2236 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2238 CRM_Core_Action
::VIEW
2242 //lets start w/ params.
2243 foreach ($params as $key => $value) {
2244 $customFieldID = self
::getKeyID($key);
2245 if (!$customFieldID) {
2249 //load the structural info for given field.
2250 $field = new CRM_Core_DAO_CustomField();
2251 $field->id
= $customFieldID;
2252 if (!$field->find(TRUE)) {
2255 $dataType = $field->data_type
;
2257 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2258 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2259 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2261 $fieldTitle = $field->label
;
2264 //no need to validate.
2265 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2269 //lets validate first for required field.
2270 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2271 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2275 //now time to take care of custom field form rules.
2276 $ruleName = $errorMsg = NULL;
2277 switch ($dataType) {
2279 $ruleName = 'integer';
2280 $errorMsg = ts('%1 must be an integer (whole number).',
2281 array(1 => $fieldTitle)
2286 $ruleName = 'money';
2287 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2288 array(1 => $fieldTitle)
2293 $ruleName = 'numeric';
2294 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2295 array(1 => $fieldTitle)
2300 $ruleName = 'wikiURL';
2301 $errorMsg = ts('%1 must be valid Website.',
2302 array(1 => $fieldTitle)
2307 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2309 $funName = "CRM_Utils_Rule::{$ruleName}";
2310 if (is_callable($funName)) {
2311 $valid = call_user_func($funName, $value);
2314 $errors[$key] = $errorMsg;
2323 * Is this field a multi record field.
2325 * @param int $customId
2329 public static function isMultiRecordField($customId) {
2330 $isMultipleWithGid = FALSE;
2331 if (!is_numeric($customId)) {
2332 $customId = self
::getKeyID($customId);
2334 if (is_numeric($customId)) {
2335 $sql = "SELECT cg.id cgId
2336 FROM civicrm_custom_group cg
2337 INNER JOIN civicrm_custom_field cf
2338 ON cg.id = cf.custom_group_id
2339 WHERE cf.id = %1 AND cg.is_multiple = 1";
2340 $params[1] = array($customId, 'Integer');
2341 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2342 if ($dao->fetch()) {
2344 $isMultipleWithGid = $dao->cgId
;
2349 return $isMultipleWithGid;
2353 * Does this field store a serialized string?
2355 * @param array $field
2359 public static function isSerialized($field) {
2360 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2361 $field = (array) $field;
2362 // 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.
2363 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2367 * Get api entity for this field
2371 public function getEntity() {
2372 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2373 return in_array($entity, array('Individual', 'Household', 'Organization')) ?
'Contact' : $entity;
2377 * Set pseudoconstant properties for field metadata.
2379 * @param array $field
2380 * @param string|null $optionGroupName
2382 private static function getOptionsForField(&$field, $optionGroupName) {
2383 if ($optionGroupName) {
2384 $field['pseudoconstant'] = array(
2385 'optionGroupName' => $optionGroupName,
2386 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2389 elseif ($field['data_type'] == 'Boolean') {
2390 $field['pseudoconstant'] = array(
2391 'callback' => 'CRM_Core_SelectValues::boolean',
2394 elseif ($field['data_type'] == 'Country') {
2395 $field['pseudoconstant'] = array(
2396 'table' => 'civicrm_country',
2397 'keyColumn' => 'id',
2398 'labelColumn' => 'name',
2399 'nameColumn' => 'iso_code',
2402 elseif ($field['data_type'] == 'StateProvince') {
2403 $field['pseudoconstant'] = array(
2404 'table' => 'civicrm_state_province',
2405 'keyColumn' => 'id',
2406 'labelColumn' => 'name',