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;
63 public static $displayInfoCache = array();
66 * Build and retrieve the list of data types and descriptions.
69 * Data type => Description
71 public static function &dataType() {
72 if (!(self
::$_dataType)) {
73 self
::$_dataType = array(
74 'String' => ts('Alphanumeric'),
75 'Int' => ts('Integer'),
76 'Float' => ts('Number'),
77 'Money' => ts('Money'),
80 'Boolean' => ts('Yes or No'),
81 'StateProvince' => ts('State/Province'),
82 'Country' => ts('Country'),
85 'ContactReference' => ts('Contact Reference'),
88 return self
::$_dataType;
92 * Get data to html array.
94 * (Does this caching achieve anything?)
98 public static function dataToHtml() {
99 if (!self
::$_dataToHtml) {
100 self
::$_dataToHtml = array(
103 'Select' => 'Select',
105 'CheckBox' => 'CheckBox',
106 'Multi-Select' => 'Multi-Select',
107 'AdvMulti-Select' => 'AdvMulti-Select',
108 'Autocomplete-Select' => 'Autocomplete-Select',
110 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
111 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
112 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
113 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
114 array('Date' => 'Select Date'),
115 array('Radio' => 'Radio'),
116 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
117 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
118 array('File' => 'File'),
119 array('Link' => 'Link'),
120 array('ContactReference' => 'Autocomplete-Select'),
123 return self
::$_dataToHtml;
127 * Takes an associative array and creates a custom field object.
129 * This function is invoked from within the web form layer and also from the api layer
131 * @param array $params
132 * (reference) an assoc array of name/value pairs.
134 * @return CRM_Core_DAO_CustomField
136 public static function create(&$params) {
137 $origParams = array_merge(array(), $params);
139 if (!isset($params['id'])) {
140 if (!isset($params['column_name'])) {
141 // if add mode & column_name not present, calculate it.
142 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
144 if (!isset($params['name'])) {
145 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
149 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
154 $columnName = $params['column_name'];
157 //as during create if field is_searchable we had created index.
158 if (!empty($params['id'])) {
159 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
162 switch (CRM_Utils_Array
::value('html_type', $params)) {
164 if (empty($params['date_format'])) {
165 $config = CRM_Core_Config
::singleton();
166 $params['date_format'] = $config->dateInputFormat
;
171 case 'AdvMulti-Select':
173 if (isset($params['default_checkbox_option'])) {
174 $tempArray = array_keys($params['default_checkbox_option']);
175 $defaultArray = array();
176 foreach ($tempArray as $k => $v) {
177 if ($params['option_value'][$v]) {
178 $defaultArray[] = $params['option_value'][$v];
182 if (!empty($defaultArray)) {
183 // also add the separator before and after the value per new convention (CRM-1604)
184 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
188 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
190 $params['default_value'] = $params['option_value'][$params['default_option']];
196 $transaction = new CRM_Core_Transaction();
197 // create any option group & values if required
198 if ($params['html_type'] != 'Text' &&
199 in_array($params['data_type'], array(
207 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
208 $params['custom_group_id'],
212 //CRM-16659: if option_value then create an option group for this custom field.
213 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
214 // first create an option group for this custom group
215 $optionGroup = new CRM_Core_DAO_OptionGroup();
216 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
217 $optionGroup->title
= $params['label'];
218 $optionGroup->is_active
= 1;
219 $optionGroup->save();
220 $params['option_group_id'] = $optionGroup->id
;
221 if (!empty($params['option_value']) && is_array($params['option_value'])) {
222 foreach ($params['option_value'] as $k => $v) {
223 if (strlen(trim($v))) {
224 $optionValue = new CRM_Core_DAO_OptionValue();
225 $optionValue->option_group_id
= $optionGroup->id
;
226 $optionValue->label
= $params['option_label'][$k];
227 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
228 switch ($params['data_type']) {
230 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
234 $optionValue->value
= intval($v);
238 $optionValue->value
= floatval($v);
242 $optionValue->value
= trim($v);
245 $optionValue->weight
= $params['option_weight'][$k];
246 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
247 $optionValue->save();
254 // check for orphan option groups
255 if (!empty($params['option_group_id'])) {
256 if (!empty($params['id'])) {
257 self
::fixOptionGroups($params['id'], $params['option_group_id']);
260 // if we do not have a default value
261 // retrieve it from one of the other custom fields which use this option group
262 if (empty($params['default_value'])) {
263 //don't insert only value separator as default value, CRM-4579
264 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
268 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
272 $params['default_value'] = $defaultValue;
277 // since we need to save option group id :)
278 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
279 $params['attributes'] = 'rows=4, cols=60';
282 $customField = new CRM_Core_DAO_CustomField();
283 $customField->copyValues($params);
284 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
285 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
286 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $params, FALSE);
287 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
288 //CRM-15792 - Custom field gets disabled if is_active not set
289 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, TRUE);
290 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
291 $customField->save();
293 // make sure all values are present in the object for further processing
294 $customField->find(TRUE);
296 $triggerRebuild = CRM_Utils_Array
::value('triggerRebuild', $params, TRUE);
297 //create/drop the index when we toggle the is_searchable flag
298 if (!empty($params['id'])) {
299 self
::createField($customField, 'modify', $indexExist, $triggerRebuild);
302 if (!isset($origParams['column_name'])) {
303 $columnName .= "_{$customField->id}";
304 $params['column_name'] = $columnName;
306 $customField->column_name
= $columnName;
307 $customField->save();
308 // make sure all values are present in the object
309 $customField->find(TRUE);
312 self
::createField($customField, 'add', $indexExist, $triggerRebuild);
315 // complete transaction
316 $transaction->commit();
318 CRM_Utils_System
::flushCache();
324 * Fetch object based on array of properties.
326 * @param array $params
327 * (reference ) an assoc array of name/value pairs.
328 * @param array $defaults
329 * (reference ) an assoc array to hold the flattened values.
331 * @return CRM_Core_DAO_CustomField
333 public static function retrieve(&$params, &$defaults) {
334 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
338 * Update the is_active flag in the db.
341 * Id of the database record.
342 * @param bool $is_active
343 * Value we want to set the is_active field.
346 * DAO object on success, null otherwise
348 public static function setIsActive($id, $is_active) {
350 CRM_Utils_System
::flushCache();
352 //enable-disable CustomField
353 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
354 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
358 * Get the field title.
366 public static function getTitle($id) {
367 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
371 * @param string $context
374 public function getOptions($context = NULL) {
375 CRM_Core_DAO
::buildOptionsContext($context);
380 if (!$this->data_type ||
!$this->custom_group_id
) {
384 if (!empty($this->option_group_id
)) {
385 $options = CRM_Core_OptionGroup
::valuesByID(
386 $this->option_group_id
,
391 !($context == 'validate' ||
$context == 'get')
394 elseif ($this->data_type
=== 'StateProvince') {
395 $options = CRM_Core_Pseudoconstant
::stateProvince();
397 elseif ($this->data_type
=== 'Country') {
398 $options = $context == 'validate' ? CRM_Core_Pseudoconstant
::countryIsoCode() : CRM_Core_Pseudoconstant
::country();
400 elseif ($this->data_type
=== 'Boolean') {
401 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
406 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
407 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
408 $entity = in_array($entity, array('Individual', 'Household', 'Organization')) ?
'Contact' : $entity;
409 CRM_Utils_Hook
::fieldOptions($entity, "custom_{$this->id}", $options, array('context' => $context));
414 * Store and return an array of all active custom fields.
416 * @param string $customDataType
417 * Type of Custom Data; empty is a synonym for "all contact data types".
418 * @param bool $showAll
419 * If true returns all fields (includes disabled fields).
420 * @param bool $inline
421 * If true returns all inline fields (includes disabled fields).
422 * @param int $customDataSubType
423 * Custom Data sub type value.
424 * @param int $customDataSubName
425 * Custom Data sub name value.
426 * @param bool $onlyParent
427 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
428 * @param bool $onlySubType
429 * Return only custom data for subtype.
430 * @param bool $checkPermission
431 * If false, do not include permissioning clause.
434 * an array of active custom fields.
436 public static function &getFields(
437 $customDataType = 'Individual',
440 $customDataSubType = NULL,
441 $customDataSubName = NULL,
443 $onlySubType = FALSE,
444 $checkPermission = TRUE
446 if (empty($customDataType)) {
447 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
449 if ($customDataType && !is_array($customDataType)) {
451 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
452 // This is the case when getFieldsForImport() requires fields
453 // limited strictly to a subtype.
454 $customDataSubType = $customDataType;
455 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
459 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
460 // this makes the method flexible to support retrieving fields
461 // for multiple extends value.
462 $customDataType = array($customDataType);
466 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
468 if (is_array($customDataType)) {
469 $cacheKey = implode('_', $customDataType);
472 $cacheKey = $customDataType;
475 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
476 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
477 $cacheKey .= $showAll ?
'_1' : '_0';
478 $cacheKey .= $inline ?
'_1_' : '_0_';
479 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
480 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
481 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
483 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
485 // also get the permission stuff here
486 if ($checkPermission) {
487 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
492 $permissionClause = '(1)';
495 // lets md5 permission clause and take first 8 characters
496 $cacheKey .= substr(md5($permissionClause), 0, 8);
498 if (strlen($cacheKey) > 40) {
499 $cacheKey = md5($cacheKey);
502 if (!self
::$_importFields ||
503 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
505 if (!self
::$_importFields) {
506 self
::$_importFields = array();
509 // check if we can retrieve from database cache
510 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
512 if ($fields === NULL) {
513 $cfTable = self
::getTableName();
516 if (is_array($customDataType)) {
518 foreach ($customDataType as $dataType) {
519 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
520 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
521 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
524 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
526 $value = $value ?
$value . ", {$val}" : $val;
530 $extends = "AND $cgTable.extends IN ( $value ) ";
534 if (!empty($customDataType) && empty($extends)) {
535 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
536 self
::$_importFields[$cacheKey] = array();
537 return self
::$_importFields[$cacheKey];
541 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
544 $query = "SELECT $cfTable.id, $cfTable.label,
548 $cfTable.default_value,
549 $cfTable.options_per_line, $cfTable.text_length,
550 $cfTable.custom_group_id,
551 $cfTable.is_required,
552 $cgTable.extends, $cfTable.is_search_range,
553 $cgTable.extends_entity_column_value,
554 $cgTable.extends_entity_column_id,
556 $cfTable.option_group_id,
557 $cfTable.date_format,
558 $cfTable.time_format,
559 $cgTable.is_multiple,
560 og.name as option_group_name
563 ON $cfTable.custom_group_id = $cgTable.id
564 LEFT JOIN civicrm_option_group og
565 ON $cfTable.option_group_id = og.id
569 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
573 $query .= " AND $cgTable.style = 'Inline' ";
576 //get the custom fields for specific type in
577 //combination with fields those support any type.
578 if (!empty($customDataSubType)) {
579 $subtypeClause = array();
580 foreach ($customDataSubType as $subtype) {
581 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
582 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
585 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
587 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
590 if ($customDataSubName) {
591 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
594 // also get the permission stuff here
595 if ($checkPermission) {
596 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
601 $permissionClause = '(1)';
604 $query .= " $extends AND $permissionClause
605 ORDER BY $cgTable.weight, $cgTable.title,
606 $cfTable.weight, $cfTable.label";
608 $dao = CRM_Core_DAO
::executeQuery($query);
611 while (($dao->fetch()) != NULL) {
612 $fields[$dao->id
]['label'] = $dao->label
;
613 $fields[$dao->id
]['groupTitle'] = $dao->title
;
614 $fields[$dao->id
]['data_type'] = $dao->data_type
;
615 $fields[$dao->id
]['html_type'] = $dao->html_type
;
616 $fields[$dao->id
]['default_value'] = $dao->default_value
;
617 $fields[$dao->id
]['text_length'] = $dao->text_length
;
618 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
619 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
620 $fields[$dao->id
]['extends'] = $dao->extends;
621 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
622 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
623 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
624 $fields[$dao->id
]['is_view'] = $dao->is_view
;
625 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
626 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
627 $fields[$dao->id
]['date_format'] = $dao->date_format
;
628 $fields[$dao->id
]['time_format'] = $dao->time_format
;
629 $fields[$dao->id
]['is_required'] = $dao->is_required
;
630 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
633 CRM_Core_BAO_Cache
::setItem($fields,
635 "custom importableFields $cacheKey"
638 self
::$_importFields[$cacheKey] = $fields;
641 return self
::$_importFields[$cacheKey];
645 * Return the field ids and names (with groups) for import purpose.
647 * @param int|string $contactType Contact type
648 * @param bool $showAll
649 * If true returns all fields (includes disabled fields).
650 * @param bool $onlyParent
651 * Return fields ONLY related to basic types.
652 * @param bool $search
653 * When called from search and multiple records need to be returned.
654 * @param bool $checkPermission
655 * If false, do not include permissioning clause.
657 * @param bool $withMultiple
661 public static function getFieldsForImport(
662 $contactType = 'Individual',
666 $checkPermission = TRUE,
667 $withMultiple = FALSE
669 // Note: there are situations when we want getFieldsForImport() return fields related
670 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
671 $fields = &self
::getFields($contactType,
681 $importableFields = array();
682 foreach ($fields as $id => $values) {
683 // for now we should not allow multiple fields in profile / export etc, hence unsetting
685 (!empty($values['is_multiple']) && !$withMultiple)
690 /* generate the key for the fields array */
694 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
695 $importableFields[$key] = array(
697 'title' => CRM_Utils_Array
::value('label', $values),
698 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
700 'custom_field_id' => $id,
701 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
702 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
703 'data_type' => CRM_Utils_Array
::value('data_type', $values),
704 'html_type' => CRM_Utils_Array
::value('html_type', $values),
705 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
708 // CRM-6681, pass date and time format when html_type = Select Date
709 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
710 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
711 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
715 return $importableFields;
719 * Get the field id from an import key.
729 public static function getKeyID($key, $all = FALSE) {
731 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
738 CRM_Utils_Array
::value(2, $match),
742 return $all ?
array(NULL, NULL) : NULL;
746 * Use the cache to get all values of a specific custom field.
748 * @param int $fieldID
749 * The custom field ID.
751 * @return CRM_Core_DAO_CustomField
754 public static function getFieldObject($fieldID) {
755 $field = new CRM_Core_DAO_CustomField();
757 // check if we can get the field values from the system cache
758 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
759 $cache = CRM_Utils_Cache
::singleton();
760 $fieldValues = $cache->get($cacheKey);
761 if (empty($fieldValues)) {
762 $field->id
= $fieldID;
763 if (!$field->find(TRUE)) {
764 CRM_Core_Error
::fatal();
767 $fieldValues = array();
768 CRM_Core_DAO
::storeValues($field, $fieldValues);
770 $cache->set($cacheKey, $fieldValues);
773 $field->copyValues($fieldValues);
780 * This function for building custom fields.
782 * @param CRM_Core_Form $qf
783 * Form object (reference).
784 * @param string $elementName
785 * Name of the custom field.
786 * @param int $fieldId
787 * @param bool $inactiveNeeded
789 * @param bool $useRequired
790 * True if required else false.
791 * @param bool $search
792 * True if used for search else false.
793 * @param string $label
794 * Label for custom field.
796 public static function addQuickFormElement(
800 $inactiveNeeded = FALSE,
805 $field = self
::getFieldObject($fieldId);
806 $widget = $field->html_type
;
808 // Custom field HTML should indicate group+field name
809 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
810 $dataCrmCustomVal = $groupName . ':' . $field->name
;
811 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
812 $field->attributes
.= $dataCrmCustomAttr;
814 // Fixed for Issue CRM-2183
815 if ($widget == 'TextArea' && $search) {
819 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
821 // FIXME: Why are select state/country separate widget types?
822 $isSelect = (in_array($widget, array(
825 'Select State/Province',
826 'Multi-Select State/Province',
828 'Multi-Select Country',
835 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array(
836 'field' => "custom_$fieldId",
837 'context' => $search ?
'search' : 'create',
840 // Consolidate widget types to simplify the below switch statement
841 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
844 $selectAttributes = array(
845 'data-crm-custom' => $dataCrmCustomVal,
846 'class' => 'crm-select2',
848 // Search field is always multi-select
849 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
850 $selectAttributes['class'] .= ' huge';
851 $selectAttributes['multiple'] = 'multiple';
852 $selectAttributes['placeholder'] = $placeholder;
854 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
855 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
856 $selectAttributes +
= array(
857 'data-api-entity' => 'contact',
858 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
859 'data-api-field' => 'custom_' . $field->id
,
860 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
865 if (!isset($label)) {
866 $label = $field->label
;
869 // at some point in time we might want to split the below into small functions
874 if ($field->is_search_range
&& $search) {
875 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
876 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
879 $element = &$qf->add('text', $elementName, $label,
881 $useRequired && !$search
887 $attributes = $dataCrmCustomAttr;
888 if ($field->note_rows
) {
889 $attributes .= 'rows=' . $field->note_rows
;
892 $attributes .= 'rows=4';
894 if ($field->note_columns
) {
895 $attributes .= ' cols=' . $field->note_columns
;
898 $attributes .= ' cols=60';
900 if ($field->text_length
) {
901 $attributes .= ' maxlength=' . $field->text_length
;
903 $element = &$qf->add('textarea',
907 $useRequired && !$search
912 if ($field->is_search_range
&& $search) {
913 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
915 'format' => $field->date_format
,
916 'timeFormat' => $field->time_format
,
917 'startOffset' => $field->start_date_years
,
918 'endOffset' => $field->end_date_years
,
919 'data-crm-custom' => $dataCrmCustomVal,
923 $qf->addDate($elementName . '_to', ts('To'), FALSE,
925 'format' => $field->date_format
,
926 'timeFormat' => $field->time_format
,
927 'startOffset' => $field->start_date_years
,
928 'endOffset' => $field->end_date_years
,
929 'data-crm-custom' => $dataCrmCustomVal,
934 $required = $useRequired && !$search;
936 $qf->addDate($elementName, $label, $required, array(
937 'format' => $field->date_format
,
938 'timeFormat' => $field->time_format
,
939 'startOffset' => $field->start_date_years
,
940 'endOffset' => $field->end_date_years
,
941 'data-crm-custom' => $dataCrmCustomVal,
948 foreach ($options as $v => $l) {
949 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
951 $group = $qf->addGroup($choice, $elementName, $label);
952 if ($useRequired && !$search) {
953 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
956 $group->setAttribute('allowClear', TRUE);
960 // For all select elements
962 if (empty($selectAttributes['multiple'])) {
963 $options = array('' => $placeholder) +
$options;
965 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
967 // Add and/or option for fields that store multiple values
968 if ($search && self
::isSerialized($field)) {
971 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
972 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
974 $qf->addGroup($operators, $elementName . '_operator');
975 $qf->setDefaults(array($elementName . '_operator' => 'or'));
979 case 'AdvMulti-Select':
980 $include =& $qf->addElement(
987 'class' => 'advmultiselect',
988 'data-crm-custom' => $dataCrmCustomVal,
992 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
993 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
995 if ($useRequired && !$search) {
996 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
1002 foreach ($options as $v => $l) {
1003 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
1005 $qf->addGroup($check, $elementName, $label);
1006 if ($useRequired && !$search) {
1007 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
1012 // we should not build upload file in search mode
1017 strtolower($field->html_type
),
1021 $useRequired && !$search
1023 $qf->addUploadElement($elementName);
1026 case 'RichTextEditor':
1027 $attributes = array(
1028 'rows' => $field->note_rows
,
1029 'cols' => $field->note_columns
,
1030 'data-crm-custom' => $dataCrmCustomVal,
1032 if ($field->text_length
) {
1033 $attributes['maxlength'] = $field->text_length
;
1035 $qf->add('wysiwyg', $elementName, $label, $attributes, $search);
1038 case 'Autocomplete-Select':
1039 static $customUrls = array();
1040 // Fixme: why is this a string in the first place??
1041 $attributes = array();
1042 if ($field->attributes
) {
1043 foreach (explode(' ', $field->attributes
) as $at) {
1044 if (strpos($at, '=')) {
1045 list($k, $v) = explode('=', $at);
1046 $attributes[$k] = trim($v, ' "');
1050 if ($field->data_type
== 'ContactReference') {
1051 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1052 $attributes['data-api-entity'] = 'contact';
1053 $qf->add('text', $elementName, $label, $attributes,
1054 $useRequired && !$search
1057 $urlParams = "context=customfield&id={$field->id}";
1059 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1066 // FIXME: This won't work with customFieldOptions hook
1067 $attributes +
= array(
1068 'entity' => 'option_value',
1069 'placeholder' => $placeholder,
1070 'multiple' => $search,
1072 'params' => array('option_group_id' => $field->option_group_id
),
1075 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1078 $qf->assign('customUrls', $customUrls);
1082 switch ($field->data_type
) {
1084 // integers will have numeric rule applied to them.
1085 if ($field->is_search_range
&& $search) {
1086 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1087 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1089 elseif ($widget == 'Text') {
1090 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1095 if ($field->is_search_range
&& $search) {
1096 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1097 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1099 elseif ($widget == 'Text') {
1100 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1105 if ($field->is_search_range
&& $search) {
1106 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1107 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1109 elseif ($widget == 'Text') {
1110 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1115 $element->setAttribute('class', "url");
1116 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1119 if ($field->is_view
&& !$search) {
1120 $qf->freeze($elementName);
1125 * Delete the Custom Field.
1127 * @param object $field
1130 public static function deleteField($field) {
1131 CRM_Utils_System
::flushCache();
1133 // first delete the custom option group and values associated with this field
1134 if ($field->option_group_id
) {
1135 //check if option group is related to any other field, if
1136 //not delete the option group and related option values
1137 self
::checkOptionGroup($field->option_group_id
);
1140 // next drop the column from the custom value table
1141 self
::createField($field, 'delete');
1144 CRM_Core_BAO_UFField
::delUFField($field->id
);
1145 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1149 * @param string|int|array|null $value
1150 * @param CRM_Core_BAO_CustomField|int|string $field
1154 * @throws \Exception
1156 public static function displayValue($value, $field, $contactId = NULL) {
1157 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1160 throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1163 if (!isset(self
::$displayInfoCache[$fieldId])) {
1164 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1165 $field = new CRM_Core_BAO_CustomField();
1166 $field->id
= $fieldId;
1168 $options = $field->getOptions();
1169 self
::$displayInfoCache[$fieldId] = array(
1171 'html_type' => $field->html_type
,
1172 'data_type' => $field->data_type
,
1173 'date_format' => $field->date_format
,
1174 'time_format' => $field->time_format
,
1175 'options' => $options,
1178 return self
::formatDisplayValue($value, self
::$displayInfoCache[$fieldId], $contactId);
1182 * Legacy display value formatter.
1186 * @param string $value
1187 * @param array $option
1188 * @param string $html_type
1189 * @param string $data_type
1190 * @param int $contactID
1191 * @param int $fieldID
1193 * @return array|mixed|null|string
1195 public static function getDisplayValueCommon(
1205 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1206 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1207 $html_type == 'Select' ||
1208 $html_type == 'CheckBox' ||
1209 $html_type == 'AdvMulti-Select' ||
1210 $html_type == 'Multi-Select'
1213 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1216 if ($data_type == 'Boolean') {
1217 $option = CRM_Core_SelectValues
::boolean();
1220 if ($data_type == 'Country') {
1221 $option = CRM_Core_PseudoConstant
::country(FALSE, FALSE);
1224 if ($data_type == 'StateProvince') {
1225 $option = CRM_Core_PseudoConstant
::stateProvince(FALSE, FALSE);
1230 'html_type' => $html_type,
1231 'data_type' => $data_type,
1232 'options' => $option,
1235 return self
::formatDisplayValue($value, $field, $contactID);
1240 * Lower-level logic for rendering a custom field value
1242 * @param string|array $value
1243 * @param array $field
1244 * @param int|null $contactID
1248 private static function formatDisplayValue($value, $field, $contactID = NULL) {
1250 if (self
::isSerialized($field) && !is_array($value)) {
1251 $value = (array) CRM_Utils_Array
::explodePadded($value);
1254 if ($field['html_type'] == 'CheckBox') {
1255 CRM_Utils_Array
::formatArrayKeys($value);
1258 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1260 switch ($field['html_type']) {
1263 case 'Autocomplete-Select':
1265 case 'Select Country':
1266 case 'Select State/Province':
1268 case 'AdvMulti-Select':
1269 case 'Multi-Select':
1270 case 'Multi-Select State/Province':
1271 case 'Multi-Select Country':
1272 if ($field['data_type'] == 'ContactReference' && $value) {
1273 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1275 elseif (is_array($value)) {
1277 foreach ($value as $key => $val) {
1278 $v[] = CRM_Utils_Array
::value($val, $field['options']);
1280 $display = implode(', ', $v);
1283 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1288 $customFormat = NULL;
1290 $actualPHPFormats = CRM_Core_SelectValues
::datePluginToPHPFormats();
1291 $format = CRM_Utils_Array
::value('date_format', $field);
1294 if (array_key_exists($format, $actualPHPFormats)) {
1295 $customTimeFormat = (array) $actualPHPFormats[$format];
1296 switch (CRM_Utils_Array
::value('time_format', $field)) {
1298 $customTimeFormat[] = 'g:iA';
1302 $customTimeFormat[] = 'G:i';
1306 // if time is not selected remove time from value
1307 $value = substr($value, 0, 10);
1309 $customFormat = implode(" ", $customTimeFormat);
1312 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1316 // In the context of displaying a profile, show file/image
1317 if ($contactID && $value) {
1318 $url = self
::getFileURL($contactID, $field['id'], $value);
1320 $display = $url['file_url'];
1323 // In other contexts show a paperclip icon
1325 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1326 $display = $icons[$value];
1331 $display = nl2br($display);
1338 * Set default values for custom data used in profile.
1340 * @param int $customFieldId
1342 * @param string $elementName
1343 * Custom field name.
1344 * @param array $defaults
1345 * Associated array of fields.
1346 * @param int $contactId
1350 * @param mixed $value
1351 * If passed - dont fetch value from db,.
1352 * just format the given value
1354 public static function setProfileDefaults(
1362 //get the type of custom field
1363 $customField = new CRM_Core_BAO_CustomField();
1364 $customField->id
= $customFieldId;
1365 $customField->find(TRUE);
1368 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1369 $value = $customField->default_value
;
1373 if (!isset($value)) {
1374 $info = self
::getTableColumnGroup($customFieldId);
1375 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1376 $result = CRM_Core_DAO
::executeQuery($query);
1377 if ($result->fetch()) {
1378 $value = $result->value
;
1382 if ($customField->data_type
== 'Country') {
1384 $config = CRM_Core_Config
::singleton();
1385 if ($config->defaultContactCountry
) {
1386 $value = $config->defaultContactCountry();
1392 //set defaults if mode is registration
1393 if (!trim($value) &&
1395 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1397 $value = $customField->default_value
;
1400 if ($customField->data_type
== 'Money' && isset($value)) {
1401 $value = number_format($value, 2);
1403 switch ($customField->html_type
) {
1405 case 'AdvMulti-Select':
1406 case 'Multi-Select':
1407 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1408 $defaults[$elementName] = array();
1409 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1410 substr($value, 1, -1)
1412 foreach ($customOption as $val) {
1413 if (in_array($val['value'], $checkedValue)) {
1414 if ($customField->html_type
== 'CheckBox') {
1415 $defaults[$elementName][$val['value']] = 1;
1417 elseif ($customField->html_type
== 'Multi-Select' ||
1418 $customField->html_type
== 'AdvMulti-Select'
1420 $defaults[$elementName][$val['value']] = $val['value'];
1428 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1431 $customField->date_format
,
1432 $customField->time_format
1437 case 'Autocomplete-Select':
1438 if ($customField->data_type
== 'ContactReference') {
1439 if (is_numeric($value)) {
1440 $defaults[$elementName . '_id'] = $value;
1441 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1445 $defaults[$elementName] = $value;
1450 $defaults[$elementName] = $value;
1457 * @param int $contactID
1459 * @param int $fileID
1460 * @param bool $absolute
1462 * @param string $multiRecordWhereClause
1466 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1469 $params = array('id' => $cfID);
1470 $defaults = array();
1471 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1472 $columnName = $defaults['column_name'];
1474 //table name of custom data
1475 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1476 $defaults['custom_group_id'],
1480 //query to fetch id from civicrm_file
1481 if ($multiRecordWhereClause) {
1482 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1485 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1487 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1492 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1497 $result['file_id'] = $fileID;
1499 if ($fileType == 'image/jpeg' ||
1500 $fileType == 'image/pjpeg' ||
1501 $fileType == 'image/gif' ||
1502 $fileType == 'image/x-png' ||
1503 $fileType == 'image/png'
1505 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1510 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1511 list($imageWidth, $imageHeight) = getimagesize($path);
1512 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1513 $url = CRM_Utils_System
::url('civicrm/file',
1514 "reset=1&id=$fileID&eid=$contactID",
1515 $absolute, NULL, TRUE, TRUE
1517 $result['file_url'] = "
1518 <a href=\"$url\" class='crm-image-popup'>
1519 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1521 // for non image files
1524 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1528 $url = CRM_Utils_System
::url('civicrm/file',
1529 "reset=1&id=$fileID&eid=$contactID",
1530 $absolute, NULL, TRUE, TRUE
1532 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1540 * Format custom fields before inserting.
1542 * @param int $customFieldId
1544 * @param array $customFormatted
1546 * @param mixed $value
1547 * Value of custom field.
1548 * @param string $customFieldExtend
1549 * Custom field extends.
1550 * @param int $customValueId
1551 * Custom option value id.
1552 * @param int $entityId
1553 * Entity id (contribution, membership...).
1554 * @param bool $inline
1555 * Consider inline custom groups only.
1556 * @param bool $checkPermission
1557 * If false, do not include permissioning clause.
1558 * @param bool $includeViewOnly
1559 * If true, fields marked 'View Only' are included. Required for APIv3.
1561 * @return array|NULL
1562 * formatted custom field array
1564 public static function formatCustomField(
1565 $customFieldId, &$customFormatted, $value,
1566 $customFieldExtend, $customValueId = NULL,
1569 $checkPermission = TRUE,
1570 $includeViewOnly = FALSE
1572 //get the custom fields for the entity
1573 //subtype and basic type
1574 $customDataSubType = NULL;
1575 if ($customFieldExtend) {
1576 // This is the case when getFieldsForImport() requires fields
1577 // of subtype and its parent.CRM-5143
1578 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1579 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1580 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1581 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1582 if (is_array($customFieldExtend)) {
1583 $customFieldExtend = array_unique(array_values($customFieldExtend));
1588 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1598 if (!array_key_exists($customFieldId, $customFields)) {
1602 // return if field is a 'code' field
1603 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1607 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1609 if (!$customValueId &&
1610 // we always create new entites for is_multiple unless specified
1611 !$customFields[$customFieldId]['is_multiple'] &&
1617 WHERE entity_id={$entityId}";
1619 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1622 //fix checkbox, now check box always submits values
1623 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1625 // Note that only during merge this is not an array, and you can directly use value
1626 if (is_array($value)) {
1627 $selectedValues = array();
1628 foreach ($value as $selId => $val) {
1630 $selectedValues[] = $selId;
1633 if (!empty($selectedValues)) {
1634 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1636 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1645 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1646 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1649 $value = CRM_Utils_Array
::implodePadded($value);
1656 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1657 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1658 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1660 $customFields[$customFieldId]['data_type'] == 'String' &&
1661 !empty($customFields[$customFieldId]['text_length']) &&
1664 // lets make sure that value is less than the length, else we'll
1665 // be losing some data, CRM-7481
1666 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1667 // need to do a few things here
1669 // 1. lets find a new length
1670 $newLength = $customFields[$customFieldId]['text_length'];
1671 $minLength = strlen($value);
1672 while ($newLength < $minLength) {
1673 $newLength = $newLength * 2;
1676 // set the custom field meta data to have a length larger than value
1677 // alter the custom value table column to match this length
1678 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1683 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1684 if (!CRM_Utils_System
::isNull($value)) {
1685 $format = $customFields[$customFieldId]['date_format'];
1686 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1691 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1692 $customFields[$customFieldId]['data_type'] == 'Money'
1698 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1699 $value = CRM_Utils_Rule
::cleanMoney($value);
1703 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1704 $customFields[$customFieldId]['data_type'] == 'Country'
1714 if ($customFields[$customFieldId]['data_type'] == 'File') {
1715 if (empty($value)) {
1719 $config = CRM_Core_Config
::singleton();
1721 $fName = $value['name'];
1722 $mimeType = $value['type'];
1724 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1726 // rename this file to go into the secure directory
1727 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1728 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1731 if ($customValueId) {
1736 $params = array(1 => array($customValueId, 'Integer'));
1737 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1740 $fileDAO = new CRM_Core_DAO_File();
1743 $fileDAO->id
= $fileId;
1746 $fileDAO->uri
= $filename;
1747 $fileDAO->mime_type
= $mimeType;
1748 $fileDAO->upload_date
= date('Ymdhis');
1750 $fileId = $fileDAO->id
;
1754 if (!is_array($customFormatted)) {
1755 $customFormatted = array();
1758 if (!array_key_exists($customFieldId, $customFormatted)) {
1759 $customFormatted[$customFieldId] = array();
1763 if ($customValueId) {
1764 $index = $customValueId;
1767 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1768 $customFormatted[$customFieldId][$index] = array();
1770 $customFormatted[$customFieldId][$index] = array(
1771 'id' => $customValueId > 0 ?
$customValueId : NULL,
1773 'type' => $customFields[$customFieldId]['data_type'],
1774 'custom_field_id' => $customFieldId,
1775 'custom_group_id' => $groupID,
1776 'table_name' => $tableName,
1777 'column_name' => $columnName,
1778 'file_id' => $fileId,
1779 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1782 //we need to sort so that custom fields are created in the order of entry
1783 krsort($customFormatted[$customFieldId]);
1784 return $customFormatted;
1788 * Get default custom table schema.
1790 * @param array $params
1794 public static function defaultCustomTableSchema($params) {
1795 // add the id and extends_id
1797 'name' => $params['name'],
1798 'is_multiple' => $params['is_multiple'],
1799 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1803 'type' => 'int unsigned',
1806 'attributes' => 'AUTO_INCREMENT',
1807 'comment' => 'Default MySQL primary key',
1810 'name' => 'entity_id',
1811 'type' => 'int unsigned',
1813 'comment' => 'Table that this extends',
1814 'fk_table_name' => $params['extends_name'],
1815 'fk_field_name' => 'id',
1816 'fk_attributes' => 'ON DELETE CASCADE',
1821 if (!$params['is_multiple']) {
1822 $table['indexes'] = array(
1825 'field_name_1' => 'entity_id',
1833 * Create custom field.
1835 * @param CRM_Core_DAO_CustomField $field
1836 * @param string $operation
1837 * @param bool $indexExist
1838 * @param bool $triggerRebuild
1840 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1841 $tableName = CRM_Core_DAO
::getFieldValue(
1842 'CRM_Core_DAO_CustomGroup',
1843 $field->custom_group_id
,
1848 'table_name' => $tableName,
1849 'operation' => $operation,
1850 'name' => $field->column_name
,
1851 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1855 'required' => $field->is_required
,
1856 'searchable' => $field->is_searchable
,
1859 if ($operation == 'delete') {
1860 $fkName = "{$tableName}_{$field->column_name}";
1861 if (strlen($fkName) >= 48) {
1862 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1864 $params['fkName'] = $fkName;
1866 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1867 $params['fk_table_name'] = 'civicrm_country';
1868 $params['fk_field_name'] = 'id';
1869 $params['fk_attributes'] = 'ON DELETE SET NULL';
1871 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1872 $params['type'] = 'varchar(255)';
1874 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1875 $params['fk_table_name'] = 'civicrm_state_province';
1876 $params['fk_field_name'] = 'id';
1877 $params['fk_attributes'] = 'ON DELETE SET NULL';
1879 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1880 $params['type'] = 'varchar(255)';
1882 elseif ($field->data_type
== 'File') {
1883 $params['fk_table_name'] = 'civicrm_file';
1884 $params['fk_field_name'] = 'id';
1885 $params['fk_attributes'] = 'ON DELETE SET NULL';
1887 elseif ($field->data_type
== 'ContactReference') {
1888 $params['fk_table_name'] = 'civicrm_contact';
1889 $params['fk_field_name'] = 'id';
1890 $params['fk_attributes'] = 'ON DELETE SET NULL';
1892 if (isset($field->default_value
)) {
1893 $params['default'] = "'{$field->default_value}'";
1896 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1900 * Determine whether it would be safe to move a field.
1902 * @param int $fieldID
1903 * FK to civicrm_custom_field.
1904 * @param int $newGroupID
1905 * FK to civicrm_custom_group.
1908 * array(string) or TRUE
1910 public static function _moveFieldValidate($fieldID, $newGroupID) {
1913 $field = new CRM_Core_DAO_CustomField();
1914 $field->id
= $fieldID;
1915 if (!$field->find(TRUE)) {
1916 $errors['fieldID'] = 'Invalid ID for custom field';
1920 $oldGroup = new CRM_Core_DAO_CustomGroup();
1921 $oldGroup->id
= $field->custom_group_id
;
1922 if (!$oldGroup->find(TRUE)) {
1923 $errors['fieldID'] = 'Invalid ID for old custom group';
1927 $newGroup = new CRM_Core_DAO_CustomGroup();
1928 $newGroup->id
= $newGroupID;
1929 if (!$newGroup->find(TRUE)) {
1930 $errors['newGroupID'] = 'Invalid ID for new custom group';
1936 FROM civicrm_custom_field a
1937 INNER JOIN civicrm_custom_field b
1939 AND a.label = b.label
1940 AND b.custom_group_id = %2
1943 1 => array($field->id
, 'Integer'),
1944 2 => array($newGroup->id
, 'Integer'),
1946 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1948 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1951 $tableName = $oldGroup->table_name
;
1952 $columnName = $field->column_name
;
1957 WHERE $columnName is not null
1959 $count = CRM_Core_DAO
::singleValueQuery($query,
1960 CRM_Core_DAO
::$_nullArray
1965 FROM civicrm_custom_group
1966 WHERE id IN ( %1, %2 )
1969 1 => array($oldGroup->id
, 'Integer'),
1970 2 => array($newGroup->id
, 'Integer'),
1973 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1975 while ($dao->fetch()) {
1976 $extends[] = $dao->extends;
1978 if ($extends[0] != $extends[1]) {
1979 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1983 return empty($errors) ?
TRUE : $errors;
1987 * Move a custom data field from one group (table) to another.
1989 * @param int $fieldID
1990 * FK to civicrm_custom_field.
1991 * @param int $newGroupID
1992 * FK to civicrm_custom_group.
1994 public static function moveField($fieldID, $newGroupID) {
1995 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1996 if (TRUE !== $validation) {
1997 CRM_Core_Error
::fatal(implode(' ', $validation));
1999 $field = new CRM_Core_DAO_CustomField();
2000 $field->id
= $fieldID;
2003 $newGroup = new CRM_Core_DAO_CustomGroup();
2004 $newGroup->id
= $newGroupID;
2005 $newGroup->find(TRUE);
2007 $oldGroup = new CRM_Core_DAO_CustomGroup();
2008 $oldGroup->id
= $field->custom_group_id
;
2009 $oldGroup->find(TRUE);
2012 $add->custom_group_id
= $newGroup->id
;
2013 self
::createField($add, 'add');
2015 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2016 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2017 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2019 CRM_Core_DAO
::executeQuery($sql);
2022 $del->custom_group_id
= $oldGroup->id
;
2023 self
::createField($del, 'delete');
2027 CRM_Utils_System
::flushCache();
2031 * Get the database table name and column name for a custom field.
2033 * @param int $fieldID
2034 * The fieldID of the custom field.
2035 * @param bool $force
2036 * Force the sql to be run again (primarily used for tests).
2039 * fatal is fieldID does not exists, else array of tableName, columnName
2041 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2042 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2043 $cache = CRM_Utils_Cache
::singleton();
2044 $fieldValues = $cache->get($cacheKey);
2045 if (empty($fieldValues) ||
$force) {
2047 SELECT cg.table_name, cf.column_name, cg.id
2048 FROM civicrm_custom_group cg,
2049 civicrm_custom_field cf
2050 WHERE cf.custom_group_id = cg.id
2052 $params = array(1 => array($fieldID, 'Integer'));
2053 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2055 if (!$dao->fetch()) {
2056 CRM_Core_Error
::fatal();
2059 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2060 $cache->set($cacheKey, $fieldValues);
2062 return $fieldValues;
2066 * Get custom option groups.
2068 * @param array $includeFieldIds
2069 * Ids of custom fields for which option groups must be included.
2071 * Currently this is required in the cases where option groups are to be included
2072 * for inactive fields : CRM-5369
2076 public static function customOptionGroup($includeFieldIds = NULL) {
2077 static $customOptionGroup = NULL;
2079 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2080 if ($cacheKey == 'force') {
2081 $customOptionGroup[$cacheKey] = NULL;
2084 if (empty($customOptionGroup[$cacheKey])) {
2085 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2087 //support for single as well as array format.
2088 if (!empty($includeFieldIds)) {
2089 if (is_array($includeFieldIds)) {
2090 $includeFieldIds = implode(',', $includeFieldIds);
2092 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2096 SELECT g.id, g.title
2097 FROM civicrm_option_group g
2098 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2099 WHERE {$whereClause}";
2101 $dao = CRM_Core_DAO
::executeQuery($query);
2102 while ($dao->fetch()) {
2103 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2107 return $customOptionGroup[$cacheKey];
2111 * Fix orphan groups.
2113 * @param int $customFieldId
2115 * @param int $optionGroupId
2118 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2119 // check if option group belongs to any custom Field else delete
2120 // get the current option group
2121 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2125 // get the updated option group
2126 // if both are same return
2127 if ($currentOptionGroupId == $optionGroupId) {
2131 // check if option group is related to any other field
2132 self
::checkOptionGroup($currentOptionGroupId);
2136 * Check if option group is related to more than one custom field.
2138 * @param int $optionGroupId
2141 public static function checkOptionGroup($optionGroupId) {
2144 FROM civicrm_custom_field
2145 WHERE option_group_id = {$optionGroupId}";
2147 $count = CRM_Core_DAO
::singleValueQuery($query);
2150 //delete the option group
2151 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2156 * Get option group default.
2158 * @param int $optionGroupId
2159 * @param string $htmlType
2161 * @return null|string
2163 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2165 SELECT default_value, html_type
2166 FROM civicrm_custom_field
2167 WHERE option_group_id = {$optionGroupId}
2168 AND default_value IS NOT NULL
2169 ORDER BY html_type";
2171 $dao = CRM_Core_DAO
::executeQuery($query);
2172 $defaultValue = NULL;
2173 $defaultHTMLType = NULL;
2174 while ($dao->fetch()) {
2175 if ($dao->html_type
== $htmlType) {
2176 return $dao->default_value
;
2178 if ($defaultValue == NULL) {
2179 $defaultValue = $dao->default_value
;
2180 $defaultHTMLType = $dao->html_type
;
2184 // some conversions are needed if either the old or new has a html type which has potential
2185 // multiple default values.
2186 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2187 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2189 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2191 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2192 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2194 $defaultValue = substr($defaultValue, 1, -1);
2195 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2196 substr($defaultValue, 1, -1)
2198 $defaultValue = $values[0];
2201 return $defaultValue;
2205 * Post process function.
2207 * @param array $params
2208 * @param int $entityID
2209 * @param string $customFieldExtends
2210 * @param bool $inline
2211 * @param bool $checkPermissions
2215 public static function postProcess(
2218 $customFieldExtends,
2220 $checkPermissions = TRUE
2222 $customData = array();
2224 foreach ($params as $key => $value) {
2225 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2227 // for autocomplete transfer hidden value instead of label
2228 if ($params[$key] && isset($params[$key . '_id'])) {
2229 $value = $params[$key . '_id'];
2232 // we need to append time with date
2233 if ($params[$key] && isset($params[$key . '_time'])) {
2234 $value .= ' ' . $params[$key . '_time'];
2237 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2240 $customFieldExtends,
2241 $customFieldInfo[1],
2256 * Get custom field ID.
2258 * @param string $fieldLabel
2259 * @param null $groupTitle
2263 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2264 $params = array(1 => array($fieldLabel, 'String'));
2266 $params[2] = array($groupTitle, 'String');
2269 FROM civicrm_custom_field f
2270 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2271 WHERE ( f.label = %1 OR f.name = %1 )
2272 AND ( g.title = %2 OR g.name = %2 )
2278 FROM civicrm_custom_field f
2279 WHERE ( f.label = %1 OR f.name = %1 )
2283 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2284 if ($dao->fetch() &&
2295 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2301 public static function getNameFromID($ids) {
2302 if (is_array($ids)) {
2303 $ids = implode(',', $ids);
2306 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2307 FROM civicrm_custom_field f
2308 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2309 WHERE f.id IN ($ids)";
2311 $dao = CRM_Core_DAO
::executeQuery($sql);
2313 while ($dao->fetch()) {
2314 $result[$dao->id
] = array(
2315 'field_name' => $dao->field_name
,
2316 'field_label' => $dao->field_label
,
2317 'group_name' => $dao->group_name
,
2318 'group_title' => $dao->group_title
,
2325 * Validate custom data.
2327 * @param array $params
2328 * Custom data submitted.
2329 * ie array( 'custom_1' => 'validate me' );
2332 * validation errors.
2334 public static function validateCustomData($params) {
2336 if (!is_array($params) ||
empty($params)) {
2340 //pick up profile fields.
2341 $profileFields = array();
2342 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2344 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2346 CRM_Core_Action
::VIEW
2350 //lets start w/ params.
2351 foreach ($params as $key => $value) {
2352 $customFieldID = self
::getKeyID($key);
2353 if (!$customFieldID) {
2357 //load the structural info for given field.
2358 $field = new CRM_Core_DAO_CustomField();
2359 $field->id
= $customFieldID;
2360 if (!$field->find(TRUE)) {
2363 $dataType = $field->data_type
;
2365 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2366 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2367 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2369 $fieldTitle = $field->label
;
2372 //no need to validate.
2373 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2377 //lets validate first for required field.
2378 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2379 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2383 //now time to take care of custom field form rules.
2384 $ruleName = $errorMsg = NULL;
2385 switch ($dataType) {
2387 $ruleName = 'integer';
2388 $errorMsg = ts('%1 must be an integer (whole number).',
2389 array(1 => $fieldTitle)
2394 $ruleName = 'money';
2395 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2396 array(1 => $fieldTitle)
2401 $ruleName = 'numeric';
2402 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2403 array(1 => $fieldTitle)
2408 $ruleName = 'wikiURL';
2409 $errorMsg = ts('%1 must be valid Website.',
2410 array(1 => $fieldTitle)
2415 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2417 $funName = "CRM_Utils_Rule::{$ruleName}";
2418 if (is_callable($funName)) {
2419 $valid = call_user_func($funName, $value);
2422 $errors[$key] = $errorMsg;
2431 * Is this field a multi record field.
2433 * @param int $customId
2437 public static function isMultiRecordField($customId) {
2438 $isMultipleWithGid = FALSE;
2439 if (!is_numeric($customId)) {
2440 $customId = self
::getKeyID($customId);
2442 if (is_numeric($customId)) {
2443 $sql = "SELECT cg.id cgId
2444 FROM civicrm_custom_group cg
2445 INNER JOIN civicrm_custom_field cf
2446 ON cg.id = cf.custom_group_id
2447 WHERE cf.id = %1 AND cg.is_multiple = 1";
2448 $params[1] = array($customId, 'Integer');
2449 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2450 if ($dao->fetch()) {
2452 $isMultipleWithGid = $dao->cgId
;
2457 return $isMultipleWithGid;
2461 * Does this field store a serialized string?
2463 * @param array $field
2467 public static function isSerialized($field) {
2468 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2469 $field = (array) $field;
2470 // 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.
2471 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2475 * Set pseudoconstant properties for field metadata.
2477 * @param array $field
2478 * @param string|null $optionGroupName
2480 private static function getOptionsForField(&$field, $optionGroupName) {
2481 if ($optionGroupName) {
2482 $field['pseudoconstant'] = array(
2483 'optionGroupName' => $optionGroupName,
2484 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2487 elseif ($field['data_type'] == 'Boolean') {
2488 $field['pseudoconstant'] = array(
2489 'callback' => 'CRM_Core_SelectValues::boolean',
2492 elseif ($field['data_type'] == 'Country') {
2493 $field['pseudoconstant'] = array(
2494 'table' => 'civicrm_country',
2495 'keyColumn' => 'id',
2496 'labelColumn' => 'name',
2497 'nameColumn' => 'iso_code',
2500 elseif ($field['data_type'] == 'StateProvince') {
2501 $field['pseudoconstant'] = array(
2502 'table' => 'civicrm_state_province',
2503 'keyColumn' => 'id',
2504 'labelColumn' => 'name',