3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
35 * Business objects for managing custom data fields.
37 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
40 * Array for valid combinations of data_type & descriptions.
44 public static $_dataType = NULL;
47 * Array for valid combinations of data_type & html_type.
51 public static $_dataToHtml = NULL;
54 * Array to hold (formatted) fields for import
58 public static $_importFields = NULL;
61 * Build and retrieve the list of data types and descriptions.
64 * Data type => Description
66 public static function &dataType() {
67 if (!(self
::$_dataType)) {
68 self
::$_dataType = array(
69 'String' => ts('Alphanumeric'),
70 'Int' => ts('Integer'),
71 'Float' => ts('Number'),
72 'Money' => ts('Money'),
75 'Boolean' => ts('Yes or No'),
76 'StateProvince' => ts('State/Province'),
77 'Country' => ts('Country'),
80 'ContactReference' => ts('Contact Reference'),
83 return self
::$_dataType;
87 * Build the map of custom field's data types and there respective Util type
90 * Data data-type => CRM_Utils_Type
92 public static function dataToType() {
94 'String' => CRM_Utils_Type
::T_STRING
,
95 'Int' => CRM_Utils_Type
::T_INT
,
96 'Money' => CRM_Utils_Type
::T_MONEY
,
97 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
98 'Float' => CRM_Utils_Type
::T_FLOAT
,
99 'Date' => CRM_Utils_Type
::T_DATE
,
100 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
101 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
102 'StateProvince' => CRM_Utils_Type
::T_INT
,
103 'File' => CRM_Utils_Type
::T_STRING
,
104 'Link' => CRM_Utils_Type
::T_STRING
,
105 'ContactReference' => CRM_Utils_Type
::T_INT
,
106 'Country' => CRM_Utils_Type
::T_INT
,
111 * Get data to html array.
113 * (Does this caching achieve anything?)
117 public static function dataToHtml() {
118 if (!self
::$_dataToHtml) {
119 self
::$_dataToHtml = array(
122 'Select' => 'Select',
124 'CheckBox' => 'CheckBox',
125 'Multi-Select' => 'Multi-Select',
126 'Autocomplete-Select' => 'Autocomplete-Select',
128 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
129 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
130 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
131 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
132 array('Date' => 'Select Date'),
133 array('Radio' => 'Radio'),
134 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
135 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
136 array('File' => 'File'),
137 array('Link' => 'Link'),
138 array('ContactReference' => 'Autocomplete-Select'),
141 return self
::$_dataToHtml;
145 * Takes an associative array and creates a custom field object.
147 * This function is invoked from within the web form layer and also from the api layer
149 * @param array $params
150 * (reference) an assoc array of name/value pairs.
152 * @return CRM_Core_DAO_CustomField
154 public static function create(&$params) {
155 $origParams = array_merge(array(), $params);
157 $op = empty($params['id']) ?
'create' : 'edit';
159 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
161 if ($op == 'create') {
162 if (!isset($params['column_name'])) {
163 // if add mode & column_name not present, calculate it.
164 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
166 if (!isset($params['name'])) {
167 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
171 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
176 $columnName = $params['column_name'];
179 //as during create if field is_searchable we had created index.
180 if (!empty($params['id'])) {
181 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
184 switch (CRM_Utils_Array
::value('html_type', $params)) {
186 if (empty($params['date_format'])) {
187 $config = CRM_Core_Config
::singleton();
188 $params['date_format'] = $config->dateInputFormat
;
194 if (isset($params['default_checkbox_option'])) {
195 $tempArray = array_keys($params['default_checkbox_option']);
196 $defaultArray = array();
197 foreach ($tempArray as $k => $v) {
198 if ($params['option_value'][$v]) {
199 $defaultArray[] = $params['option_value'][$v];
203 if (!empty($defaultArray)) {
204 // also add the separator before and after the value per new convention (CRM-1604)
205 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
209 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
211 $params['default_value'] = $params['option_value'][$params['default_option']];
217 $transaction = new CRM_Core_Transaction();
219 $htmlType = CRM_Utils_Array
::value('html_type', $params);
220 $dataType = CRM_Utils_Array
::value('data_type', $params);
221 $allowedOptionTypes = array('String', 'Int', 'Float', 'Money');
223 // create any option group & values if required
224 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)
226 //CRM-16659: if option_value then create an option group for this custom field.
227 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
228 // first create an option group for this custom group
229 $optionGroup = new CRM_Core_DAO_OptionGroup();
230 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
231 $optionGroup->title
= $params['label'];
232 $optionGroup->is_active
= 1;
233 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
234 $optionGroup->is_reserved
= 0;
235 $optionGroup->data_type
= $dataType;
236 $optionGroup->save();
237 $params['option_group_id'] = $optionGroup->id
;
238 if (!empty($params['option_value']) && is_array($params['option_value'])) {
239 foreach ($params['option_value'] as $k => $v) {
240 if (strlen(trim($v))) {
241 $optionValue = new CRM_Core_DAO_OptionValue();
242 $optionValue->option_group_id
= $optionGroup->id
;
243 $optionValue->label
= $params['option_label'][$k];
244 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
247 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
251 $optionValue->value
= intval($v);
255 $optionValue->value
= floatval($v);
259 $optionValue->value
= trim($v);
262 $optionValue->weight
= $params['option_weight'][$k];
263 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
264 $optionValue->save();
271 // check for orphan option groups
272 if (!empty($params['option_group_id'])) {
273 if (!empty($params['id'])) {
274 self
::fixOptionGroups($params['id'], $params['option_group_id']);
277 // if we do not have a default value
278 // retrieve it from one of the other custom fields which use this option group
279 if (empty($params['default_value'])) {
280 //don't insert only value separator as default value, CRM-4579
281 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
285 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
289 $params['default_value'] = $defaultValue;
294 // since we need to save option group id :)
295 if (!isset($params['attributes']) && strtolower($htmlType) == 'textarea') {
296 $params['attributes'] = 'rows=4, cols=60';
299 $customField = new CRM_Core_DAO_CustomField();
300 $customField->copyValues($params);
301 if ($op == 'create') {
302 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
303 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
304 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $params, FALSE);
305 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
306 //CRM-15792 - Custom field gets disabled if is_active not set
307 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, TRUE);
308 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
310 $customField->save();
312 // make sure all values are present in the object for further processing
313 $customField->find(TRUE);
315 $triggerRebuild = CRM_Utils_Array
::value('triggerRebuild', $params, TRUE);
316 //create/drop the index when we toggle the is_searchable flag
318 self
::createField($customField, 'modify', $indexExist, $triggerRebuild);
321 if (!isset($origParams['column_name'])) {
322 $columnName .= "_{$customField->id}";
323 $params['column_name'] = $columnName;
325 $customField->column_name
= $columnName;
326 $customField->save();
327 // make sure all values are present in the object
328 $customField->find(TRUE);
331 self
::createField($customField, 'add', $indexExist, $triggerRebuild);
334 // complete transaction
335 $transaction->commit();
337 CRM_Utils_Hook
::post($op, 'CustomField', $customField->id
, $customField);
339 CRM_Utils_System
::flushCache();
345 * Fetch object based on array of properties.
347 * @param array $params
348 * (reference ) an assoc array of name/value pairs.
349 * @param array $defaults
350 * (reference ) an assoc array to hold the flattened values.
352 * @return CRM_Core_DAO_CustomField
354 public static function retrieve(&$params, &$defaults) {
355 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
359 * Update the is_active flag in the db.
362 * Id of the database record.
363 * @param bool $is_active
364 * Value we want to set the is_active field.
367 * DAO object on success, null otherwise
369 public static function setIsActive($id, $is_active) {
371 CRM_Utils_System
::flushCache();
373 //enable-disable CustomField
374 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
375 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
379 * Get the field title.
387 public static function getTitle($id) {
388 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
392 * @param string $context
395 public function getOptions($context = NULL) {
396 CRM_Core_DAO
::buildOptionsContext($context);
401 if (!$this->data_type ||
!$this->custom_group_id
) {
405 if (!empty($this->option_group_id
)) {
406 $options = CRM_Core_OptionGroup
::valuesByID(
407 $this->option_group_id
,
412 !($context == 'validate' ||
$context == 'get')
415 elseif ($this->data_type
=== 'StateProvince') {
416 $options = CRM_Core_Pseudoconstant
::stateProvince();
418 elseif ($this->data_type
=== 'Country') {
419 $options = $context == 'validate' ? CRM_Core_Pseudoconstant
::countryIsoCode() : CRM_Core_Pseudoconstant
::country();
421 elseif ($this->data_type
=== 'Boolean') {
422 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
427 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
428 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, array('context' => $context));
433 * Store and return an array of all active custom fields.
435 * @param string $customDataType
436 * Type of Custom Data; empty is a synonym for "all contact data types".
437 * @param bool $showAll
438 * If true returns all fields (includes disabled fields).
439 * @param bool $inline
440 * If true returns all inline fields (includes disabled fields).
441 * @param int $customDataSubType
442 * Custom Data sub type value.
443 * @param int $customDataSubName
444 * Custom Data sub name value.
445 * @param bool $onlyParent
446 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
447 * @param bool $onlySubType
448 * Return only custom data for subtype.
449 * @param bool $checkPermission
450 * If false, do not include permissioning clause.
453 * an array of active custom fields.
455 public static function &getFields(
456 $customDataType = 'Individual',
459 $customDataSubType = NULL,
460 $customDataSubName = NULL,
462 $onlySubType = FALSE,
463 $checkPermission = TRUE
465 if (empty($customDataType)) {
466 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
468 if ($customDataType && !is_array($customDataType)) {
470 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
471 // This is the case when getFieldsForImport() requires fields
472 // limited strictly to a subtype.
473 $customDataSubType = $customDataType;
474 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
478 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
479 // this makes the method flexible to support retrieving fields
480 // for multiple extends value.
481 $customDataType = array($customDataType);
485 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
487 if (is_array($customDataType)) {
488 $cacheKey = implode('_', $customDataType);
491 $cacheKey = $customDataType;
494 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
495 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
496 $cacheKey .= $showAll ?
'_1' : '_0';
497 $cacheKey .= $inline ?
'_1_' : '_0_';
498 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
499 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
500 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
502 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
504 // also get the permission stuff here
505 if ($checkPermission) {
506 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
511 $permissionClause = '(1)';
514 // lets md5 permission clause and take first 8 characters
515 $cacheKey .= substr(md5($permissionClause), 0, 8);
517 if (strlen($cacheKey) > 40) {
518 $cacheKey = md5($cacheKey);
521 if (!self
::$_importFields ||
522 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
524 if (!self
::$_importFields) {
525 self
::$_importFields = array();
528 // check if we can retrieve from database cache
529 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
531 if ($fields === NULL) {
532 $cfTable = self
::getTableName();
535 if (is_array($customDataType)) {
537 foreach ($customDataType as $dataType) {
538 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
539 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
540 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
543 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
545 $value = $value ?
$value . ", {$val}" : $val;
549 $extends = "AND $cgTable.extends IN ( $value ) ";
553 if (!empty($customDataType) && empty($extends)) {
554 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
555 self
::$_importFields[$cacheKey] = array();
556 return self
::$_importFields[$cacheKey];
560 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
563 $query = "SELECT $cfTable.id, $cfTable.label,
567 $cfTable.default_value,
568 $cfTable.options_per_line, $cfTable.text_length,
569 $cfTable.custom_group_id,
570 $cfTable.is_required,
571 $cfTable.column_name,
572 $cgTable.extends, $cfTable.is_search_range,
573 $cgTable.extends_entity_column_value,
574 $cgTable.extends_entity_column_id,
576 $cfTable.option_group_id,
577 $cfTable.date_format,
578 $cfTable.time_format,
579 $cgTable.is_multiple,
581 og.name as option_group_name
584 ON $cfTable.custom_group_id = $cgTable.id
585 LEFT JOIN civicrm_option_group og
586 ON $cfTable.option_group_id = og.id
590 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
594 $query .= " AND $cgTable.style = 'Inline' ";
597 //get the custom fields for specific type in
598 //combination with fields those support any type.
599 if (!empty($customDataSubType)) {
600 $subtypeClause = array();
601 foreach ($customDataSubType as $subtype) {
602 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
603 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
606 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
608 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
611 if ($customDataSubName) {
612 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
615 // also get the permission stuff here
616 if ($checkPermission) {
617 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
622 $permissionClause = '(1)';
625 $query .= " $extends AND $permissionClause
626 ORDER BY $cgTable.weight, $cgTable.title,
627 $cfTable.weight, $cfTable.label";
629 $dao = CRM_Core_DAO
::executeQuery($query);
632 while (($dao->fetch()) != NULL) {
633 $fields[$dao->id
]['label'] = $dao->label
;
634 $fields[$dao->id
]['groupTitle'] = $dao->title
;
635 $fields[$dao->id
]['data_type'] = $dao->data_type
;
636 $fields[$dao->id
]['html_type'] = $dao->html_type
;
637 $fields[$dao->id
]['default_value'] = $dao->default_value
;
638 $fields[$dao->id
]['text_length'] = $dao->text_length
;
639 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
640 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
641 $fields[$dao->id
]['extends'] = $dao->extends;
642 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
643 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
644 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
645 $fields[$dao->id
]['is_view'] = $dao->is_view
;
646 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
647 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
648 $fields[$dao->id
]['date_format'] = $dao->date_format
;
649 $fields[$dao->id
]['time_format'] = $dao->time_format
;
650 $fields[$dao->id
]['is_required'] = $dao->is_required
;
651 $fields[$dao->id
]['table_name'] = $dao->table_name
;
652 $fields[$dao->id
]['column_name'] = $dao->column_name
;
653 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
656 CRM_Core_BAO_Cache
::setItem($fields,
658 "custom importableFields $cacheKey"
661 self
::$_importFields[$cacheKey] = $fields;
664 return self
::$_importFields[$cacheKey];
668 * Return the field ids and names (with groups) for import purpose.
670 * @param int|string $contactType Contact type
671 * @param bool $showAll
672 * If true returns all fields (includes disabled fields).
673 * @param bool $onlyParent
674 * Return fields ONLY related to basic types.
675 * @param bool $search
676 * When called from search and multiple records need to be returned.
677 * @param bool $checkPermission
678 * If false, do not include permissioning clause.
680 * @param bool $withMultiple
684 public static function getFieldsForImport(
685 $contactType = 'Individual',
689 $checkPermission = TRUE,
690 $withMultiple = FALSE
692 // Note: there are situations when we want getFieldsForImport() return fields related
693 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
694 $fields = &self
::getFields($contactType,
704 $importableFields = array();
705 foreach ($fields as $id => $values) {
706 // for now we should not allow multiple fields in profile / export etc, hence unsetting
708 (!empty($values['is_multiple']) && !$withMultiple)
713 /* generate the key for the fields array */
717 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
718 $importableFields[$key] = array(
720 'type' => CRM_Utils_Array
::value(CRM_Utils_Array
::value('data_type', $values), self
::dataToType()),
721 'title' => CRM_Utils_Array
::value('label', $values),
722 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
724 'custom_field_id' => $id,
725 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
726 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
727 'data_type' => CRM_Utils_Array
::value('data_type', $values),
728 'html_type' => CRM_Utils_Array
::value('html_type', $values),
729 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
732 // CRM-6681, pass date and time format when html_type = Select Date
733 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
734 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
735 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
739 return $importableFields;
743 * Get the field id from an import key.
753 public static function getKeyID($key, $all = FALSE) {
755 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
762 CRM_Utils_Array
::value(2, $match),
766 return $all ?
array(NULL, NULL) : NULL;
770 * Use the cache to get all values of a specific custom field.
772 * @param int $fieldID
773 * The custom field ID.
775 * @return CRM_Core_BAO_CustomField
778 public static function getFieldObject($fieldID) {
779 $field = new CRM_Core_BAO_CustomField();
781 // check if we can get the field values from the system cache
782 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
783 $cache = CRM_Utils_Cache
::singleton();
784 $fieldValues = $cache->get($cacheKey);
785 if (empty($fieldValues)) {
786 $field->id
= $fieldID;
787 if (!$field->find(TRUE)) {
788 CRM_Core_Error
::fatal();
791 $fieldValues = array();
792 CRM_Core_DAO
::storeValues($field, $fieldValues);
794 $cache->set($cacheKey, $fieldValues);
797 $field->copyValues($fieldValues);
804 * Add a custom field to an existing form.
806 * @param CRM_Core_Form $qf
807 * Form object (reference).
808 * @param string $elementName
809 * Name of the custom field.
810 * @param int $fieldId
811 * @param bool $useRequired
812 * True if required else false.
813 * @param bool $search
814 * True if used for search else false.
815 * @param string $label
816 * Label for custom field.
817 * @return \HTML_QuickForm_Element|null
818 * @throws \CiviCRM_API3_Exception
820 public static function addQuickFormElement(
821 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
823 $field = self
::getFieldObject($fieldId);
824 $widget = $field->html_type
;
826 $customFieldAttributes = array();
828 // Custom field HTML should indicate group+field name
829 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
830 $dataCrmCustomVal = $groupName . ':' . $field->name
;
831 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
832 $field->attributes
.= $dataCrmCustomAttr;
834 // Fixed for Issue CRM-2183
835 if ($widget == 'TextArea' && $search) {
839 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
841 // FIXME: Why are select state/country separate widget types?
842 $isSelect = (in_array($widget, array(
845 'Select State/Province',
846 'Multi-Select State/Province',
848 'Multi-Select Country',
854 $options = $field->getOptions($search ?
'search' : 'create');
856 // Consolidate widget types to simplify the below switch statement
857 if ($search ||
(strpos($widget, 'Select') !== FALSE)) {
861 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
862 $selectAttributes = array('class' => 'crm-select2');
864 // Search field is always multi-select
865 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
866 $selectAttributes['class'] .= ' huge';
867 $selectAttributes['multiple'] = 'multiple';
868 $selectAttributes['placeholder'] = $placeholder;
871 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
872 $isSupportedWidget = in_array($widget, ['Select', 'Radio']);
873 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
874 if ($field->option_group_id
&& !$search && $isSelect && $canEditOptions) {
875 $customFieldAttributes +
= array(
876 'data-api-entity' => $field->getEntity(),
877 'data-api-field' => 'custom_' . $field->id
,
878 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
880 $selectAttributes +
= $customFieldAttributes;
884 if (!isset($label)) {
885 $label = $field->label
;
888 // at some point in time we might want to split the below into small functions
893 if ($field->is_search_range
&& $search) {
894 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
895 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
898 if ($field->text_length
) {
899 $field->attributes
.= ' maxlength=' . $field->text_length
;
900 if ($field->text_length
< 20) {
901 $field->attributes
.= ' size=' . $field->text_length
;
904 $element = $qf->add('text', $elementName, $label,
906 $useRequired && !$search
912 $attributes = $dataCrmCustomAttr;
913 if ($field->note_rows
) {
914 $attributes .= 'rows=' . $field->note_rows
;
917 $attributes .= 'rows=4';
919 if ($field->note_columns
) {
920 $attributes .= ' cols=' . $field->note_columns
;
923 $attributes .= ' cols=60';
925 if ($field->text_length
) {
926 $attributes .= ' maxlength=' . $field->text_length
;
928 $element = $qf->add('textarea',
932 $useRequired && !$search
937 $attr = array('data-crm-custom' => $dataCrmCustomVal);
938 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
939 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
940 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
943 'date' => $field->date_format
,
944 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
945 //CRM-18487 - max date should be the last date of the year.
946 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
947 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
949 if ($field->is_search_range
&& $search) {
950 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
951 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
954 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
960 parse_str($field->attributes
, $radioAttributes);
961 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
963 foreach ($options as $v => $l) {
964 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
966 $element = $qf->addGroup($choice, $elementName, $label);
967 $optionEditKey = 'data-option-edit-path';
968 if (isset($selectAttributes[$optionEditKey])) {
969 $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
972 if ($useRequired && !$search) {
973 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
976 $element->setAttribute('allowClear', TRUE);
980 // For all select elements
982 if (empty($selectAttributes['multiple'])) {
983 $options = array('' => $placeholder) +
$options;
985 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
987 // Add and/or option for fields that store multiple values
988 if ($search && self
::isSerialized($field)) {
991 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
992 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
994 $qf->addGroup($operators, $elementName . '_operator');
995 $qf->setDefaults(array($elementName . '_operator' => 'or'));
1001 foreach ($options as $v => $l) {
1002 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
1005 $group = $element = $qf->addGroup($check, $elementName, $label);
1006 $optionEditKey = 'data-option-edit-path';
1007 if (isset($customFieldAttributes[$optionEditKey])) {
1008 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
1011 if ($useRequired && !$search) {
1012 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
1017 // we should not build upload file in search mode
1021 $element = $qf->add(
1022 strtolower($field->html_type
),
1026 $useRequired && !$search
1028 $qf->addUploadElement($elementName);
1031 case 'RichTextEditor':
1032 $attributes = array(
1033 'rows' => $field->note_rows
,
1034 'cols' => $field->note_columns
,
1035 'data-crm-custom' => $dataCrmCustomVal,
1037 if ($field->text_length
) {
1038 $attributes['maxlength'] = $field->text_length
;
1040 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
1043 case 'Autocomplete-Select':
1044 static $customUrls = array();
1045 // Fixme: why is this a string in the first place??
1046 $attributes = array();
1047 if ($field->attributes
) {
1048 foreach (explode(' ', $field->attributes
) as $at) {
1049 if (strpos($at, '=')) {
1050 list($k, $v) = explode('=', $at);
1051 $attributes[$k] = trim($v, ' "');
1055 if ($field->data_type
== 'ContactReference') {
1056 // break if contact does not have permission to access ContactReference
1057 if (!CRM_Core_Permission
::check('access contact reference fields')) {
1060 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1061 $attributes['data-api-entity'] = 'Contact';
1062 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
1064 $urlParams = "context=customfield&id={$field->id}";
1066 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1073 // FIXME: This won't work with customFieldOptions hook
1074 $attributes +
= array(
1075 'entity' => 'option_value',
1076 'placeholder' => $placeholder,
1077 'multiple' => $search,
1079 'params' => array('option_group_id' => $field->option_group_id
),
1082 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1085 $qf->assign('customUrls', $customUrls);
1089 switch ($field->data_type
) {
1091 // integers will have numeric rule applied to them.
1092 if ($field->is_search_range
&& $search) {
1093 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1094 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1096 elseif ($widget == 'Text') {
1097 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1102 if ($field->is_search_range
&& $search) {
1103 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1104 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1106 elseif ($widget == 'Text') {
1107 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1112 if ($field->is_search_range
&& $search) {
1113 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1114 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1116 elseif ($widget == 'Text') {
1117 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1122 $element->setAttribute('class', "url");
1123 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1126 if ($field->is_view
&& !$search) {
1127 $qf->freeze($elementName);
1133 * Delete the Custom Field.
1135 * @param object $field
1138 public static function deleteField($field) {
1139 CRM_Utils_System
::flushCache();
1141 // first delete the custom option group and values associated with this field
1142 if ($field->option_group_id
) {
1143 //check if option group is related to any other field, if
1144 //not delete the option group and related option values
1145 self
::checkOptionGroup($field->option_group_id
);
1148 // next drop the column from the custom value table
1149 self
::createField($field, 'delete');
1152 CRM_Core_BAO_UFField
::delUFField($field->id
);
1153 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1155 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
1159 * @param string|int|array|null $value
1160 * @param CRM_Core_BAO_CustomField|int|array|string $field
1161 * @param int $entityId
1164 * @throws \Exception
1166 public static function displayValue($value, $field, $entityId = NULL) {
1167 $field = is_array($field) ?
$field['id'] : $field;
1168 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1171 throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1174 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1175 $field = self
::getFieldObject($fieldId);
1178 $fieldInfo = array('options' => $field->getOptions()) +
(array) $field;
1180 return self
::formatDisplayValue($value, $fieldInfo, $entityId);
1184 * Lower-level logic for rendering a custom field value
1186 * @param string|array $value
1187 * @param array $field
1188 * @param int|null $entityId
1192 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1194 if (self
::isSerialized($field) && !is_array($value)) {
1195 $value = CRM_Utils_Array
::explodePadded($value);
1198 if ($field['html_type'] == 'CheckBox') {
1199 CRM_Utils_Array
::formatArrayKeys($value);
1202 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1204 switch ($field['html_type']) {
1207 case 'Autocomplete-Select':
1209 case 'Select Country':
1210 case 'Select State/Province':
1212 case 'Multi-Select':
1213 case 'Multi-Select State/Province':
1214 case 'Multi-Select Country':
1215 if ($field['data_type'] == 'ContactReference' && $value) {
1216 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1218 elseif (is_array($value)) {
1220 foreach ($value as $key => $val) {
1221 $v[] = CRM_Utils_Array
::value($val, $field['options']);
1223 $display = implode(', ', $v);
1226 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1231 $customFormat = NULL;
1233 // FIXME: Are there any legitimate reasons why $value would be an array?
1234 // Or should we throw an exception here if it is?
1235 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1237 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1238 $format = CRM_Utils_Array
::value('date_format', $field);
1241 if (array_key_exists($format, $actualPHPFormats)) {
1242 $customTimeFormat = (array) $actualPHPFormats[$format];
1243 switch (CRM_Utils_Array
::value('time_format', $field)) {
1245 $customTimeFormat[] = 'g:iA';
1249 $customTimeFormat[] = 'G:i';
1253 //If time is not selected remove time from value.
1254 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1256 $customFormat = implode(" ", $customTimeFormat);
1259 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1263 // In the context of displaying a profile, show file/image
1266 if (CRM_Utils_Rule
::positiveInteger($value)) {
1270 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1272 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1274 $display = $url['file_url'];
1278 // In other contexts show a paperclip icon
1279 if (CRM_Utils_Rule
::integer($value)) {
1280 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1281 $display = $icons[$value];
1284 //CRM-18396, if filename is passed instead
1292 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1296 $display = nl2br($display);
1300 if ($field['data_type'] == 'Money' && isset($value)) {
1301 //$value can also be an array(while using IN operator from search builder or api).
1302 foreach ((array) $value as $val) {
1303 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1305 $display = implode(', ', $disp);
1313 * Set default values for custom data used in profile.
1315 * @param int $customFieldId
1317 * @param string $elementName
1318 * Custom field name.
1319 * @param array $defaults
1320 * Associated array of fields.
1321 * @param int $contactId
1325 * @param mixed $value
1326 * If passed - dont fetch value from db,.
1327 * just format the given value
1329 public static function setProfileDefaults(
1337 //get the type of custom field
1338 $customField = new CRM_Core_BAO_CustomField();
1339 $customField->id
= $customFieldId;
1340 $customField->find(TRUE);
1343 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1344 $value = $customField->default_value
;
1348 if (!isset($value)) {
1349 $info = self
::getTableColumnGroup($customFieldId);
1350 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1351 $result = CRM_Core_DAO
::executeQuery($query);
1352 if ($result->fetch()) {
1353 $value = $result->value
;
1357 if ($customField->data_type
== 'Country') {
1359 $config = CRM_Core_Config
::singleton();
1360 if ($config->defaultContactCountry
) {
1361 $value = $config->defaultContactCountry();
1367 //set defaults if mode is registration
1368 if (!trim($value) &&
1370 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1372 $value = $customField->default_value
;
1375 if ($customField->data_type
== 'Money' && isset($value)) {
1376 $value = number_format($value, 2);
1378 switch ($customField->html_type
) {
1380 case 'Multi-Select':
1381 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1382 $defaults[$elementName] = array();
1383 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1384 substr($value, 1, -1)
1386 foreach ($customOption as $val) {
1387 if (in_array($val['value'], $checkedValue)) {
1388 if ($customField->html_type
== 'CheckBox') {
1389 $defaults[$elementName][$val['value']] = 1;
1391 elseif ($customField->html_type
== 'Multi-Select') {
1392 $defaults[$elementName][$val['value']] = $val['value'];
1398 case 'Autocomplete-Select':
1399 if ($customField->data_type
== 'ContactReference') {
1400 if (is_numeric($value)) {
1401 $defaults[$elementName . '_id'] = $value;
1402 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1406 $defaults[$elementName] = $value;
1411 $defaults[$elementName] = $value;
1418 * @param int $contactID
1420 * @param int $fileID
1421 * @param bool $absolute
1423 * @param string $multiRecordWhereClause
1427 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1430 $params = array('id' => $cfID);
1431 $defaults = array();
1432 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1433 $columnName = $defaults['column_name'];
1435 //table name of custom data
1436 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1437 $defaults['custom_group_id'],
1441 //query to fetch id from civicrm_file
1442 if ($multiRecordWhereClause) {
1443 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1446 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1448 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1453 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1458 $result['file_id'] = $fileID;
1460 if ($fileType == 'image/jpeg' ||
1461 $fileType == 'image/pjpeg' ||
1462 $fileType == 'image/gif' ||
1463 $fileType == 'image/x-png' ||
1464 $fileType == 'image/png'
1466 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1471 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1472 $url = CRM_Utils_System
::url('civicrm/file',
1473 "reset=1&id=$fileID&eid=$contactID",
1474 $absolute, NULL, TRUE, TRUE
1476 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1478 // for non image files
1480 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1484 $url = CRM_Utils_System
::url('civicrm/file',
1485 "reset=1&id=$fileID&eid=$contactID",
1486 $absolute, NULL, TRUE, TRUE
1488 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1496 * Format custom fields before inserting.
1498 * @param int $customFieldId
1500 * @param array $customFormatted
1502 * @param mixed $value
1503 * Value of custom field.
1504 * @param string $customFieldExtend
1505 * Custom field extends.
1506 * @param int $customValueId
1507 * Custom option value id.
1508 * @param int $entityId
1509 * Entity id (contribution, membership...).
1510 * @param bool $inline
1511 * Consider inline custom groups only.
1512 * @param bool $checkPermission
1513 * If false, do not include permissioning clause.
1514 * @param bool $includeViewOnly
1515 * If true, fields marked 'View Only' are included. Required for APIv3.
1517 * @return array|NULL
1518 * formatted custom field array
1520 public static function formatCustomField(
1521 $customFieldId, &$customFormatted, $value,
1522 $customFieldExtend, $customValueId = NULL,
1525 $checkPermission = TRUE,
1526 $includeViewOnly = FALSE
1528 //get the custom fields for the entity
1529 //subtype and basic type
1530 $customDataSubType = NULL;
1531 if ($customFieldExtend) {
1532 // This is the case when getFieldsForImport() requires fields
1533 // of subtype and its parent.CRM-5143
1534 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1535 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1536 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1537 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1538 if (is_array($customFieldExtend)) {
1539 $customFieldExtend = array_unique(array_values($customFieldExtend));
1544 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1554 if (!array_key_exists($customFieldId, $customFields)) {
1558 // return if field is a 'code' field
1559 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1563 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1565 if (!$customValueId &&
1566 // we always create new entites for is_multiple unless specified
1567 !$customFields[$customFieldId]['is_multiple'] &&
1573 WHERE entity_id={$entityId}";
1575 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1578 //fix checkbox, now check box always submits values
1579 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1581 // Note that only during merge this is not an array, and you can directly use value
1582 if (is_array($value)) {
1583 $selectedValues = array();
1584 foreach ($value as $selId => $val) {
1586 $selectedValues[] = $selId;
1589 if (!empty($selectedValues)) {
1590 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1592 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1601 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select') {
1603 $value = CRM_Utils_Array
::implodePadded($value);
1610 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1611 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1613 $customFields[$customFieldId]['data_type'] == 'String' &&
1614 !empty($customFields[$customFieldId]['text_length']) &&
1617 // lets make sure that value is less than the length, else we'll
1618 // be losing some data, CRM-7481
1619 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1620 // need to do a few things here
1622 // 1. lets find a new length
1623 $newLength = $customFields[$customFieldId]['text_length'];
1624 $minLength = strlen($value);
1625 while ($newLength < $minLength) {
1626 $newLength = $newLength * 2;
1629 // set the custom field meta data to have a length larger than value
1630 // alter the custom value table column to match this length
1631 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1636 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1637 if (!CRM_Utils_System
::isNull($value)) {
1638 $format = $customFields[$customFieldId]['date_format'];
1639 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1644 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1645 $customFields[$customFieldId]['data_type'] == 'Money'
1651 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1652 $value = CRM_Utils_Rule
::cleanMoney($value);
1656 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1657 $customFields[$customFieldId]['data_type'] == 'Country'
1667 if ($customFields[$customFieldId]['data_type'] == 'File') {
1668 if (empty($value)) {
1672 $config = CRM_Core_Config
::singleton();
1674 // If we are already passing the file id as a value then retrieve and set the file data
1675 if (CRM_Utils_Rule
::integer($value)) {
1676 $fileDAO = new CRM_Core_DAO_File();
1677 $fileDAO->id
= $value;
1678 $fileDAO->find(TRUE);
1681 $fName = $fileDAO->uri
;
1682 $mimeType = $fileDAO->mime_type
;
1686 $fName = $value['name'];
1687 $mimeType = $value['type'];
1690 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1692 // rename this file to go into the secure directory only if
1693 // user has uploaded new file not existing verfied on the basis of $fileID
1694 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1695 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1698 if ($customValueId && empty($fileID)) {
1703 $params = array(1 => array($customValueId, 'Integer'));
1704 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1707 $fileDAO = new CRM_Core_DAO_File();
1710 $fileDAO->id
= $fileId;
1713 $fileDAO->uri
= $filename;
1714 $fileDAO->mime_type
= $mimeType;
1715 $fileDAO->upload_date
= date('YmdHis');
1717 $fileId = $fileDAO->id
;
1721 if (!is_array($customFormatted)) {
1722 $customFormatted = array();
1725 if (!array_key_exists($customFieldId, $customFormatted)) {
1726 $customFormatted[$customFieldId] = array();
1730 if ($customValueId) {
1731 $index = $customValueId;
1734 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1735 $customFormatted[$customFieldId][$index] = array();
1737 $customFormatted[$customFieldId][$index] = array(
1738 'id' => $customValueId > 0 ?
$customValueId : NULL,
1740 'type' => $customFields[$customFieldId]['data_type'],
1741 'custom_field_id' => $customFieldId,
1742 'custom_group_id' => $groupID,
1743 'table_name' => $tableName,
1744 'column_name' => $columnName,
1745 'file_id' => $fileId,
1746 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1749 //we need to sort so that custom fields are created in the order of entry
1750 krsort($customFormatted[$customFieldId]);
1751 return $customFormatted;
1755 * Get default custom table schema.
1757 * @param array $params
1761 public static function defaultCustomTableSchema($params) {
1762 // add the id and extends_id
1764 'name' => $params['name'],
1765 'is_multiple' => $params['is_multiple'],
1766 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1770 'type' => 'int unsigned',
1773 'attributes' => 'AUTO_INCREMENT',
1774 'comment' => 'Default MySQL primary key',
1777 'name' => 'entity_id',
1778 'type' => 'int unsigned',
1780 'comment' => 'Table that this extends',
1781 'fk_table_name' => $params['extends_name'],
1782 'fk_field_name' => 'id',
1783 'fk_attributes' => 'ON DELETE CASCADE',
1788 if (!$params['is_multiple']) {
1789 $table['indexes'] = array(
1792 'field_name_1' => 'entity_id',
1800 * Create custom field.
1802 * @param CRM_Core_DAO_CustomField $field
1803 * @param string $operation
1804 * @param bool $indexExist
1805 * @param bool $triggerRebuild
1807 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1808 $tableName = CRM_Core_DAO
::getFieldValue(
1809 'CRM_Core_DAO_CustomGroup',
1810 $field->custom_group_id
,
1815 'table_name' => $tableName,
1816 'operation' => $operation,
1817 'name' => $field->column_name
,
1818 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1822 'required' => $field->is_required
,
1823 'searchable' => $field->is_searchable
,
1826 if ($operation == 'delete') {
1827 $fkName = "{$tableName}_{$field->column_name}";
1828 if (strlen($fkName) >= 48) {
1829 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1831 $params['fkName'] = $fkName;
1833 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1834 $params['fk_table_name'] = 'civicrm_country';
1835 $params['fk_field_name'] = 'id';
1836 $params['fk_attributes'] = 'ON DELETE SET NULL';
1838 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1839 $params['type'] = 'varchar(255)';
1841 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1842 $params['fk_table_name'] = 'civicrm_state_province';
1843 $params['fk_field_name'] = 'id';
1844 $params['fk_attributes'] = 'ON DELETE SET NULL';
1846 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1847 $params['type'] = 'varchar(255)';
1849 elseif ($field->data_type
== 'File') {
1850 $params['fk_table_name'] = 'civicrm_file';
1851 $params['fk_field_name'] = 'id';
1852 $params['fk_attributes'] = 'ON DELETE SET NULL';
1854 elseif ($field->data_type
== 'ContactReference') {
1855 $params['fk_table_name'] = 'civicrm_contact';
1856 $params['fk_field_name'] = 'id';
1857 $params['fk_attributes'] = 'ON DELETE SET NULL';
1859 if (isset($field->default_value
)) {
1860 $params['default'] = "'{$field->default_value}'";
1863 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1867 * Determine whether it would be safe to move a field.
1869 * @param int $fieldID
1870 * FK to civicrm_custom_field.
1871 * @param int $newGroupID
1872 * FK to civicrm_custom_group.
1875 * array(string) or TRUE
1877 public static function _moveFieldValidate($fieldID, $newGroupID) {
1880 $field = new CRM_Core_DAO_CustomField();
1881 $field->id
= $fieldID;
1882 if (!$field->find(TRUE)) {
1883 $errors['fieldID'] = 'Invalid ID for custom field';
1887 $oldGroup = new CRM_Core_DAO_CustomGroup();
1888 $oldGroup->id
= $field->custom_group_id
;
1889 if (!$oldGroup->find(TRUE)) {
1890 $errors['fieldID'] = 'Invalid ID for old custom group';
1894 $newGroup = new CRM_Core_DAO_CustomGroup();
1895 $newGroup->id
= $newGroupID;
1896 if (!$newGroup->find(TRUE)) {
1897 $errors['newGroupID'] = 'Invalid ID for new custom group';
1903 FROM civicrm_custom_field a
1904 INNER JOIN civicrm_custom_field b
1906 AND a.label = b.label
1907 AND b.custom_group_id = %2
1910 1 => array($field->id
, 'Integer'),
1911 2 => array($newGroup->id
, 'Integer'),
1913 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1915 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1918 $tableName = $oldGroup->table_name
;
1919 $columnName = $field->column_name
;
1924 WHERE $columnName is not null
1926 $count = CRM_Core_DAO
::singleValueQuery($query,
1927 CRM_Core_DAO
::$_nullArray
1932 FROM civicrm_custom_group
1933 WHERE id IN ( %1, %2 )
1936 1 => array($oldGroup->id
, 'Integer'),
1937 2 => array($newGroup->id
, 'Integer'),
1940 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1942 while ($dao->fetch()) {
1943 $extends[] = $dao->extends;
1945 if ($extends[0] != $extends[1]) {
1946 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1950 return empty($errors) ?
TRUE : $errors;
1954 * Move a custom data field from one group (table) to another.
1956 * @param int $fieldID
1957 * FK to civicrm_custom_field.
1958 * @param int $newGroupID
1959 * FK to civicrm_custom_group.
1961 public static function moveField($fieldID, $newGroupID) {
1962 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1963 if (TRUE !== $validation) {
1964 CRM_Core_Error
::fatal(implode(' ', $validation));
1966 $field = new CRM_Core_DAO_CustomField();
1967 $field->id
= $fieldID;
1970 $newGroup = new CRM_Core_DAO_CustomGroup();
1971 $newGroup->id
= $newGroupID;
1972 $newGroup->find(TRUE);
1974 $oldGroup = new CRM_Core_DAO_CustomGroup();
1975 $oldGroup->id
= $field->custom_group_id
;
1976 $oldGroup->find(TRUE);
1979 $add->custom_group_id
= $newGroup->id
;
1980 self
::createField($add, 'add');
1982 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1983 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1984 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1986 CRM_Core_DAO
::executeQuery($sql);
1989 $del->custom_group_id
= $oldGroup->id
;
1990 self
::createField($del, 'delete');
1994 CRM_Utils_System
::flushCache();
1998 * Get the database table name and column name for a custom field.
2000 * @param int $fieldID
2001 * The fieldID of the custom field.
2002 * @param bool $force
2003 * Force the sql to be run again (primarily used for tests).
2006 * fatal is fieldID does not exists, else array of tableName, columnName
2008 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2009 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2010 $cache = CRM_Utils_Cache
::singleton();
2011 $fieldValues = $cache->get($cacheKey);
2012 if (empty($fieldValues) ||
$force) {
2014 SELECT cg.table_name, cf.column_name, cg.id
2015 FROM civicrm_custom_group cg,
2016 civicrm_custom_field cf
2017 WHERE cf.custom_group_id = cg.id
2019 $params = array(1 => array($fieldID, 'Integer'));
2020 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2022 if (!$dao->fetch()) {
2023 CRM_Core_Error
::fatal();
2026 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2027 $cache->set($cacheKey, $fieldValues);
2029 return $fieldValues;
2033 * Get custom option groups.
2035 * @deprecated Use the API OptionGroup.get
2037 * @param array $includeFieldIds
2038 * Ids of custom fields for which option groups must be included.
2040 * Currently this is required in the cases where option groups are to be included
2041 * for inactive fields : CRM-5369
2045 public static function customOptionGroup($includeFieldIds = NULL) {
2046 static $customOptionGroup = NULL;
2048 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2049 if ($cacheKey == 'force') {
2050 $customOptionGroup[$cacheKey] = NULL;
2053 if (empty($customOptionGroup[$cacheKey])) {
2054 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2056 //support for single as well as array format.
2057 if (!empty($includeFieldIds)) {
2058 if (is_array($includeFieldIds)) {
2059 $includeFieldIds = implode(',', $includeFieldIds);
2061 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2065 SELECT g.id, g.title
2066 FROM civicrm_option_group g
2067 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2068 WHERE {$whereClause}";
2070 $dao = CRM_Core_DAO
::executeQuery($query);
2071 while ($dao->fetch()) {
2072 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2076 return $customOptionGroup[$cacheKey];
2080 * Fix orphan groups.
2082 * @param int $customFieldId
2084 * @param int $optionGroupId
2087 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2088 // check if option group belongs to any custom Field else delete
2089 // get the current option group
2090 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2094 // get the updated option group
2095 // if both are same return
2096 if ($currentOptionGroupId == $optionGroupId) {
2100 // check if option group is related to any other field
2101 self
::checkOptionGroup($currentOptionGroupId);
2105 * Check if option group is related to more than one custom field.
2107 * @param int $optionGroupId
2110 public static function checkOptionGroup($optionGroupId) {
2113 FROM civicrm_custom_field
2114 WHERE option_group_id = {$optionGroupId}";
2116 $count = CRM_Core_DAO
::singleValueQuery($query);
2119 //delete the option group
2120 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2125 * Get option group default.
2127 * @param int $optionGroupId
2128 * @param string $htmlType
2130 * @return null|string
2132 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2134 SELECT default_value, html_type
2135 FROM civicrm_custom_field
2136 WHERE option_group_id = {$optionGroupId}
2137 AND default_value IS NOT NULL
2138 ORDER BY html_type";
2140 $dao = CRM_Core_DAO
::executeQuery($query);
2141 $defaultValue = NULL;
2142 $defaultHTMLType = NULL;
2143 while ($dao->fetch()) {
2144 if ($dao->html_type
== $htmlType) {
2145 return $dao->default_value
;
2147 if ($defaultValue == NULL) {
2148 $defaultValue = $dao->default_value
;
2149 $defaultHTMLType = $dao->html_type
;
2153 // some conversions are needed if either the old or new has a html type which has potential
2154 // multiple default values.
2155 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2156 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2158 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2160 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2161 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2163 $defaultValue = substr($defaultValue, 1, -1);
2164 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2165 substr($defaultValue, 1, -1)
2167 $defaultValue = $values[0];
2170 return $defaultValue;
2174 * Post process function.
2176 * @param array $params
2177 * @param int $entityID
2178 * @param string $customFieldExtends
2179 * @param bool $inline
2180 * @param bool $checkPermissions
2184 public static function postProcess(
2187 $customFieldExtends,
2189 $checkPermissions = TRUE
2191 $customData = array();
2193 foreach ($params as $key => $value) {
2194 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2196 // for autocomplete transfer hidden value instead of label
2197 if ($params[$key] && isset($params[$key . '_id'])) {
2198 $value = $params[$key . '_id'];
2201 // we need to append time with date
2202 if ($params[$key] && isset($params[$key . '_time'])) {
2203 $value .= ' ' . $params[$key . '_time'];
2206 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2209 $customFieldExtends,
2210 $customFieldInfo[1],
2221 * Get custom field ID from field/group name/title.
2223 * @param string $fieldName Field name or label
2224 * @param string|null $groupTitle (Optional) Group name or label
2225 * @param bool $fullString Whether to return "custom_123" or "123"
2227 * @return string|int|null
2228 * @throws \CiviCRM_API3_Exception
2230 public static function getCustomFieldID($fieldName, $groupTitle = NULL, $fullString = FALSE) {
2231 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName])) {
2232 $customFieldParams = [
2233 'name' => $fieldName,
2234 'label' => $fieldName,
2235 'options' => ['or' => [["name", "label"]]],
2239 $customFieldParams['custom_group_id.name'] = $groupTitle;
2240 $customFieldParams['custom_group_id.title'] = $groupTitle;
2241 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2244 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2246 if (empty($field['id'])) {
2247 Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['id'] = NULL;
2248 Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['string'] = NULL;
2251 Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['id'] = $field['id'];
2252 Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['string'] = 'custom_' . $field['id'];
2257 return Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['string'];
2259 return Civi
::$statics['CRM_Core_BAO_CustomField'][$fieldName]['id'];
2263 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2269 public static function getNameFromID($ids) {
2270 if (is_array($ids)) {
2271 $ids = implode(',', $ids);
2274 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2275 FROM civicrm_custom_field f
2276 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2277 WHERE f.id IN ($ids)";
2279 $dao = CRM_Core_DAO
::executeQuery($sql);
2281 while ($dao->fetch()) {
2282 $result[$dao->id
] = array(
2283 'field_name' => $dao->field_name
,
2284 'field_label' => $dao->field_label
,
2285 'group_name' => $dao->group_name
,
2286 'group_title' => $dao->group_title
,
2293 * Validate custom data.
2295 * @param array $params
2296 * Custom data submitted.
2297 * ie array( 'custom_1' => 'validate me' );
2300 * validation errors.
2302 public static function validateCustomData($params) {
2304 if (!is_array($params) ||
empty($params)) {
2308 //pick up profile fields.
2309 $profileFields = array();
2310 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2312 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2314 CRM_Core_Action
::VIEW
2318 //lets start w/ params.
2319 foreach ($params as $key => $value) {
2320 $customFieldID = self
::getKeyID($key);
2321 if (!$customFieldID) {
2325 //load the structural info for given field.
2326 $field = new CRM_Core_DAO_CustomField();
2327 $field->id
= $customFieldID;
2328 if (!$field->find(TRUE)) {
2331 $dataType = $field->data_type
;
2333 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2334 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2335 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2337 $fieldTitle = $field->label
;
2340 //no need to validate.
2341 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2345 //lets validate first for required field.
2346 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2347 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2351 //now time to take care of custom field form rules.
2352 $ruleName = $errorMsg = NULL;
2353 switch ($dataType) {
2355 $ruleName = 'integer';
2356 $errorMsg = ts('%1 must be an integer (whole number).',
2357 array(1 => $fieldTitle)
2362 $ruleName = 'money';
2363 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2364 array(1 => $fieldTitle)
2369 $ruleName = 'numeric';
2370 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2371 array(1 => $fieldTitle)
2376 $ruleName = 'wikiURL';
2377 $errorMsg = ts('%1 must be valid Website.',
2378 array(1 => $fieldTitle)
2383 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2385 $funName = "CRM_Utils_Rule::{$ruleName}";
2386 if (is_callable($funName)) {
2387 $valid = call_user_func($funName, $value);
2390 $errors[$key] = $errorMsg;
2399 * Is this field a multi record field.
2401 * @param int $customId
2405 public static function isMultiRecordField($customId) {
2406 $isMultipleWithGid = FALSE;
2407 if (!is_numeric($customId)) {
2408 $customId = self
::getKeyID($customId);
2410 if (is_numeric($customId)) {
2411 $sql = "SELECT cg.id cgId
2412 FROM civicrm_custom_group cg
2413 INNER JOIN civicrm_custom_field cf
2414 ON cg.id = cf.custom_group_id
2415 WHERE cf.id = %1 AND cg.is_multiple = 1";
2416 $params[1] = array($customId, 'Integer');
2417 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2418 if ($dao->fetch()) {
2420 $isMultipleWithGid = $dao->cgId
;
2425 return $isMultipleWithGid;
2429 * Does this field store a serialized string?
2431 * @param array $field
2435 public static function isSerialized($field) {
2436 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2437 $field = (array) $field;
2438 // 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.
2439 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2443 * Get api entity for this field
2447 public function getEntity() {
2448 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2449 return in_array($entity, array('Individual', 'Household', 'Organization')) ?
'Contact' : $entity;
2453 * Set pseudoconstant properties for field metadata.
2455 * @param array $field
2456 * @param string|null $optionGroupName
2458 private static function getOptionsForField(&$field, $optionGroupName) {
2459 if ($optionGroupName) {
2460 $field['pseudoconstant'] = array(
2461 'optionGroupName' => $optionGroupName,
2462 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2465 elseif ($field['data_type'] == 'Boolean') {
2466 $field['pseudoconstant'] = array(
2467 'callback' => 'CRM_Core_SelectValues::boolean',
2470 elseif ($field['data_type'] == 'Country') {
2471 $field['pseudoconstant'] = array(
2472 'table' => 'civicrm_country',
2473 'keyColumn' => 'id',
2474 'labelColumn' => 'name',
2475 'nameColumn' => 'iso_code',
2478 elseif ($field['data_type'] == 'StateProvince') {
2479 $field['pseudoconstant'] = array(
2480 'table' => 'civicrm_state_province',
2481 'keyColumn' => 'id',
2482 'labelColumn' => 'name',