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|array|string $field
1154 * @throws \Exception
1156 public static function displayValue($value, $field, $contactId = NULL) {
1157 $field = is_array($field) ?
$field['id'] : $field;
1158 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1161 throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1164 if (!isset(self
::$displayInfoCache[$fieldId])) {
1165 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1166 $field = new CRM_Core_BAO_CustomField();
1167 $field->id
= $fieldId;
1169 $options = $field->getOptions();
1170 self
::$displayInfoCache[$fieldId] = array(
1172 'html_type' => $field->html_type
,
1173 'data_type' => $field->data_type
,
1174 'date_format' => $field->date_format
,
1175 'time_format' => $field->time_format
,
1176 'options' => $options,
1179 return self
::formatDisplayValue($value, self
::$displayInfoCache[$fieldId], $contactId);
1183 * Lower-level logic for rendering a custom field value
1185 * @param string|array $value
1186 * @param array $field
1187 * @param int|null $contactID
1191 private static function formatDisplayValue($value, $field, $contactID = NULL) {
1193 if (self
::isSerialized($field) && !is_array($value)) {
1194 $value = (array) CRM_Utils_Array
::explodePadded($value);
1197 if ($field['html_type'] == 'CheckBox') {
1198 CRM_Utils_Array
::formatArrayKeys($value);
1201 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1203 switch ($field['html_type']) {
1206 case 'Autocomplete-Select':
1208 case 'Select Country':
1209 case 'Select State/Province':
1211 case 'AdvMulti-Select':
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 $actualPHPFormats = CRM_Core_SelectValues
::datePluginToPHPFormats();
1234 $format = CRM_Utils_Array
::value('date_format', $field);
1237 if (array_key_exists($format, $actualPHPFormats)) {
1238 $customTimeFormat = (array) $actualPHPFormats[$format];
1239 switch (CRM_Utils_Array
::value('time_format', $field)) {
1241 $customTimeFormat[] = 'g:iA';
1245 $customTimeFormat[] = 'G:i';
1249 // if time is not selected remove time from value
1250 $value = substr($value, 0, 10);
1252 $customFormat = implode(" ", $customTimeFormat);
1255 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1259 // In the context of displaying a profile, show file/image
1260 if ($contactID && $value) {
1261 $url = self
::getFileURL($contactID, $field['id'], $value);
1263 $display = $url['file_url'];
1266 // In other contexts show a paperclip icon
1268 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1269 $display = $icons[$value];
1274 $display = nl2br($display);
1281 * Set default values for custom data used in profile.
1283 * @param int $customFieldId
1285 * @param string $elementName
1286 * Custom field name.
1287 * @param array $defaults
1288 * Associated array of fields.
1289 * @param int $contactId
1293 * @param mixed $value
1294 * If passed - dont fetch value from db,.
1295 * just format the given value
1297 public static function setProfileDefaults(
1305 //get the type of custom field
1306 $customField = new CRM_Core_BAO_CustomField();
1307 $customField->id
= $customFieldId;
1308 $customField->find(TRUE);
1311 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1312 $value = $customField->default_value
;
1316 if (!isset($value)) {
1317 $info = self
::getTableColumnGroup($customFieldId);
1318 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1319 $result = CRM_Core_DAO
::executeQuery($query);
1320 if ($result->fetch()) {
1321 $value = $result->value
;
1325 if ($customField->data_type
== 'Country') {
1327 $config = CRM_Core_Config
::singleton();
1328 if ($config->defaultContactCountry
) {
1329 $value = $config->defaultContactCountry();
1335 //set defaults if mode is registration
1336 if (!trim($value) &&
1338 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1340 $value = $customField->default_value
;
1343 if ($customField->data_type
== 'Money' && isset($value)) {
1344 $value = number_format($value, 2);
1346 switch ($customField->html_type
) {
1348 case 'AdvMulti-Select':
1349 case 'Multi-Select':
1350 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1351 $defaults[$elementName] = array();
1352 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1353 substr($value, 1, -1)
1355 foreach ($customOption as $val) {
1356 if (in_array($val['value'], $checkedValue)) {
1357 if ($customField->html_type
== 'CheckBox') {
1358 $defaults[$elementName][$val['value']] = 1;
1360 elseif ($customField->html_type
== 'Multi-Select' ||
1361 $customField->html_type
== 'AdvMulti-Select'
1363 $defaults[$elementName][$val['value']] = $val['value'];
1371 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1374 $customField->date_format
,
1375 $customField->time_format
1380 case 'Autocomplete-Select':
1381 if ($customField->data_type
== 'ContactReference') {
1382 if (is_numeric($value)) {
1383 $defaults[$elementName . '_id'] = $value;
1384 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1388 $defaults[$elementName] = $value;
1393 $defaults[$elementName] = $value;
1400 * @param int $contactID
1402 * @param int $fileID
1403 * @param bool $absolute
1405 * @param string $multiRecordWhereClause
1409 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1412 $params = array('id' => $cfID);
1413 $defaults = array();
1414 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1415 $columnName = $defaults['column_name'];
1417 //table name of custom data
1418 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1419 $defaults['custom_group_id'],
1423 //query to fetch id from civicrm_file
1424 if ($multiRecordWhereClause) {
1425 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1428 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1430 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1435 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1440 $result['file_id'] = $fileID;
1442 if ($fileType == 'image/jpeg' ||
1443 $fileType == 'image/pjpeg' ||
1444 $fileType == 'image/gif' ||
1445 $fileType == 'image/x-png' ||
1446 $fileType == 'image/png'
1448 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1453 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1454 list($imageWidth, $imageHeight) = getimagesize($path);
1455 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1456 $url = CRM_Utils_System
::url('civicrm/file',
1457 "reset=1&id=$fileID&eid=$contactID",
1458 $absolute, NULL, TRUE, TRUE
1460 $result['file_url'] = "
1461 <a href=\"$url\" class='crm-image-popup'>
1462 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1464 // for non image files
1467 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1471 $url = CRM_Utils_System
::url('civicrm/file',
1472 "reset=1&id=$fileID&eid=$contactID",
1473 $absolute, NULL, TRUE, TRUE
1475 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1483 * Format custom fields before inserting.
1485 * @param int $customFieldId
1487 * @param array $customFormatted
1489 * @param mixed $value
1490 * Value of custom field.
1491 * @param string $customFieldExtend
1492 * Custom field extends.
1493 * @param int $customValueId
1494 * Custom option value id.
1495 * @param int $entityId
1496 * Entity id (contribution, membership...).
1497 * @param bool $inline
1498 * Consider inline custom groups only.
1499 * @param bool $checkPermission
1500 * If false, do not include permissioning clause.
1501 * @param bool $includeViewOnly
1502 * If true, fields marked 'View Only' are included. Required for APIv3.
1504 * @return array|NULL
1505 * formatted custom field array
1507 public static function formatCustomField(
1508 $customFieldId, &$customFormatted, $value,
1509 $customFieldExtend, $customValueId = NULL,
1512 $checkPermission = TRUE,
1513 $includeViewOnly = FALSE
1515 //get the custom fields for the entity
1516 //subtype and basic type
1517 $customDataSubType = NULL;
1518 if ($customFieldExtend) {
1519 // This is the case when getFieldsForImport() requires fields
1520 // of subtype and its parent.CRM-5143
1521 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1522 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1523 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1524 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1525 if (is_array($customFieldExtend)) {
1526 $customFieldExtend = array_unique(array_values($customFieldExtend));
1531 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1541 if (!array_key_exists($customFieldId, $customFields)) {
1545 // return if field is a 'code' field
1546 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1550 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1552 if (!$customValueId &&
1553 // we always create new entites for is_multiple unless specified
1554 !$customFields[$customFieldId]['is_multiple'] &&
1560 WHERE entity_id={$entityId}";
1562 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1565 //fix checkbox, now check box always submits values
1566 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1568 // Note that only during merge this is not an array, and you can directly use value
1569 if (is_array($value)) {
1570 $selectedValues = array();
1571 foreach ($value as $selId => $val) {
1573 $selectedValues[] = $selId;
1576 if (!empty($selectedValues)) {
1577 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1579 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1588 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1589 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1592 $value = CRM_Utils_Array
::implodePadded($value);
1599 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1600 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1601 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1603 $customFields[$customFieldId]['data_type'] == 'String' &&
1604 !empty($customFields[$customFieldId]['text_length']) &&
1607 // lets make sure that value is less than the length, else we'll
1608 // be losing some data, CRM-7481
1609 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1610 // need to do a few things here
1612 // 1. lets find a new length
1613 $newLength = $customFields[$customFieldId]['text_length'];
1614 $minLength = strlen($value);
1615 while ($newLength < $minLength) {
1616 $newLength = $newLength * 2;
1619 // set the custom field meta data to have a length larger than value
1620 // alter the custom value table column to match this length
1621 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1626 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1627 if (!CRM_Utils_System
::isNull($value)) {
1628 $format = $customFields[$customFieldId]['date_format'];
1629 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1634 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1635 $customFields[$customFieldId]['data_type'] == 'Money'
1641 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1642 $value = CRM_Utils_Rule
::cleanMoney($value);
1646 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1647 $customFields[$customFieldId]['data_type'] == 'Country'
1657 if ($customFields[$customFieldId]['data_type'] == 'File') {
1658 if (empty($value)) {
1662 $config = CRM_Core_Config
::singleton();
1664 $fName = $value['name'];
1665 $mimeType = $value['type'];
1667 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1669 // rename this file to go into the secure directory
1670 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1671 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1674 if ($customValueId) {
1679 $params = array(1 => array($customValueId, 'Integer'));
1680 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1683 $fileDAO = new CRM_Core_DAO_File();
1686 $fileDAO->id
= $fileId;
1689 $fileDAO->uri
= $filename;
1690 $fileDAO->mime_type
= $mimeType;
1691 $fileDAO->upload_date
= date('Ymdhis');
1693 $fileId = $fileDAO->id
;
1697 if (!is_array($customFormatted)) {
1698 $customFormatted = array();
1701 if (!array_key_exists($customFieldId, $customFormatted)) {
1702 $customFormatted[$customFieldId] = array();
1706 if ($customValueId) {
1707 $index = $customValueId;
1710 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1711 $customFormatted[$customFieldId][$index] = array();
1713 $customFormatted[$customFieldId][$index] = array(
1714 'id' => $customValueId > 0 ?
$customValueId : NULL,
1716 'type' => $customFields[$customFieldId]['data_type'],
1717 'custom_field_id' => $customFieldId,
1718 'custom_group_id' => $groupID,
1719 'table_name' => $tableName,
1720 'column_name' => $columnName,
1721 'file_id' => $fileId,
1722 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1725 //we need to sort so that custom fields are created in the order of entry
1726 krsort($customFormatted[$customFieldId]);
1727 return $customFormatted;
1731 * Get default custom table schema.
1733 * @param array $params
1737 public static function defaultCustomTableSchema($params) {
1738 // add the id and extends_id
1740 'name' => $params['name'],
1741 'is_multiple' => $params['is_multiple'],
1742 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1746 'type' => 'int unsigned',
1749 'attributes' => 'AUTO_INCREMENT',
1750 'comment' => 'Default MySQL primary key',
1753 'name' => 'entity_id',
1754 'type' => 'int unsigned',
1756 'comment' => 'Table that this extends',
1757 'fk_table_name' => $params['extends_name'],
1758 'fk_field_name' => 'id',
1759 'fk_attributes' => 'ON DELETE CASCADE',
1764 if (!$params['is_multiple']) {
1765 $table['indexes'] = array(
1768 'field_name_1' => 'entity_id',
1776 * Create custom field.
1778 * @param CRM_Core_DAO_CustomField $field
1779 * @param string $operation
1780 * @param bool $indexExist
1781 * @param bool $triggerRebuild
1783 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1784 $tableName = CRM_Core_DAO
::getFieldValue(
1785 'CRM_Core_DAO_CustomGroup',
1786 $field->custom_group_id
,
1791 'table_name' => $tableName,
1792 'operation' => $operation,
1793 'name' => $field->column_name
,
1794 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1798 'required' => $field->is_required
,
1799 'searchable' => $field->is_searchable
,
1802 if ($operation == 'delete') {
1803 $fkName = "{$tableName}_{$field->column_name}";
1804 if (strlen($fkName) >= 48) {
1805 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1807 $params['fkName'] = $fkName;
1809 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1810 $params['fk_table_name'] = 'civicrm_country';
1811 $params['fk_field_name'] = 'id';
1812 $params['fk_attributes'] = 'ON DELETE SET NULL';
1814 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1815 $params['type'] = 'varchar(255)';
1817 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1818 $params['fk_table_name'] = 'civicrm_state_province';
1819 $params['fk_field_name'] = 'id';
1820 $params['fk_attributes'] = 'ON DELETE SET NULL';
1822 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1823 $params['type'] = 'varchar(255)';
1825 elseif ($field->data_type
== 'File') {
1826 $params['fk_table_name'] = 'civicrm_file';
1827 $params['fk_field_name'] = 'id';
1828 $params['fk_attributes'] = 'ON DELETE SET NULL';
1830 elseif ($field->data_type
== 'ContactReference') {
1831 $params['fk_table_name'] = 'civicrm_contact';
1832 $params['fk_field_name'] = 'id';
1833 $params['fk_attributes'] = 'ON DELETE SET NULL';
1835 if (isset($field->default_value
)) {
1836 $params['default'] = "'{$field->default_value}'";
1839 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1843 * Determine whether it would be safe to move a field.
1845 * @param int $fieldID
1846 * FK to civicrm_custom_field.
1847 * @param int $newGroupID
1848 * FK to civicrm_custom_group.
1851 * array(string) or TRUE
1853 public static function _moveFieldValidate($fieldID, $newGroupID) {
1856 $field = new CRM_Core_DAO_CustomField();
1857 $field->id
= $fieldID;
1858 if (!$field->find(TRUE)) {
1859 $errors['fieldID'] = 'Invalid ID for custom field';
1863 $oldGroup = new CRM_Core_DAO_CustomGroup();
1864 $oldGroup->id
= $field->custom_group_id
;
1865 if (!$oldGroup->find(TRUE)) {
1866 $errors['fieldID'] = 'Invalid ID for old custom group';
1870 $newGroup = new CRM_Core_DAO_CustomGroup();
1871 $newGroup->id
= $newGroupID;
1872 if (!$newGroup->find(TRUE)) {
1873 $errors['newGroupID'] = 'Invalid ID for new custom group';
1879 FROM civicrm_custom_field a
1880 INNER JOIN civicrm_custom_field b
1882 AND a.label = b.label
1883 AND b.custom_group_id = %2
1886 1 => array($field->id
, 'Integer'),
1887 2 => array($newGroup->id
, 'Integer'),
1889 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1891 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1894 $tableName = $oldGroup->table_name
;
1895 $columnName = $field->column_name
;
1900 WHERE $columnName is not null
1902 $count = CRM_Core_DAO
::singleValueQuery($query,
1903 CRM_Core_DAO
::$_nullArray
1908 FROM civicrm_custom_group
1909 WHERE id IN ( %1, %2 )
1912 1 => array($oldGroup->id
, 'Integer'),
1913 2 => array($newGroup->id
, 'Integer'),
1916 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1918 while ($dao->fetch()) {
1919 $extends[] = $dao->extends;
1921 if ($extends[0] != $extends[1]) {
1922 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1926 return empty($errors) ?
TRUE : $errors;
1930 * Move a custom data field from one group (table) to another.
1932 * @param int $fieldID
1933 * FK to civicrm_custom_field.
1934 * @param int $newGroupID
1935 * FK to civicrm_custom_group.
1937 public static function moveField($fieldID, $newGroupID) {
1938 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1939 if (TRUE !== $validation) {
1940 CRM_Core_Error
::fatal(implode(' ', $validation));
1942 $field = new CRM_Core_DAO_CustomField();
1943 $field->id
= $fieldID;
1946 $newGroup = new CRM_Core_DAO_CustomGroup();
1947 $newGroup->id
= $newGroupID;
1948 $newGroup->find(TRUE);
1950 $oldGroup = new CRM_Core_DAO_CustomGroup();
1951 $oldGroup->id
= $field->custom_group_id
;
1952 $oldGroup->find(TRUE);
1955 $add->custom_group_id
= $newGroup->id
;
1956 self
::createField($add, 'add');
1958 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1959 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1960 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1962 CRM_Core_DAO
::executeQuery($sql);
1965 $del->custom_group_id
= $oldGroup->id
;
1966 self
::createField($del, 'delete');
1970 CRM_Utils_System
::flushCache();
1974 * Get the database table name and column name for a custom field.
1976 * @param int $fieldID
1977 * The fieldID of the custom field.
1978 * @param bool $force
1979 * Force the sql to be run again (primarily used for tests).
1982 * fatal is fieldID does not exists, else array of tableName, columnName
1984 public static function getTableColumnGroup($fieldID, $force = FALSE) {
1985 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
1986 $cache = CRM_Utils_Cache
::singleton();
1987 $fieldValues = $cache->get($cacheKey);
1988 if (empty($fieldValues) ||
$force) {
1990 SELECT cg.table_name, cf.column_name, cg.id
1991 FROM civicrm_custom_group cg,
1992 civicrm_custom_field cf
1993 WHERE cf.custom_group_id = cg.id
1995 $params = array(1 => array($fieldID, 'Integer'));
1996 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1998 if (!$dao->fetch()) {
1999 CRM_Core_Error
::fatal();
2002 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2003 $cache->set($cacheKey, $fieldValues);
2005 return $fieldValues;
2009 * Get custom option groups.
2011 * @param array $includeFieldIds
2012 * Ids of custom fields for which option groups must be included.
2014 * Currently this is required in the cases where option groups are to be included
2015 * for inactive fields : CRM-5369
2019 public static function customOptionGroup($includeFieldIds = NULL) {
2020 static $customOptionGroup = NULL;
2022 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2023 if ($cacheKey == 'force') {
2024 $customOptionGroup[$cacheKey] = NULL;
2027 if (empty($customOptionGroup[$cacheKey])) {
2028 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2030 //support for single as well as array format.
2031 if (!empty($includeFieldIds)) {
2032 if (is_array($includeFieldIds)) {
2033 $includeFieldIds = implode(',', $includeFieldIds);
2035 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2039 SELECT g.id, g.title
2040 FROM civicrm_option_group g
2041 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2042 WHERE {$whereClause}";
2044 $dao = CRM_Core_DAO
::executeQuery($query);
2045 while ($dao->fetch()) {
2046 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2050 return $customOptionGroup[$cacheKey];
2054 * Fix orphan groups.
2056 * @param int $customFieldId
2058 * @param int $optionGroupId
2061 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2062 // check if option group belongs to any custom Field else delete
2063 // get the current option group
2064 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2068 // get the updated option group
2069 // if both are same return
2070 if ($currentOptionGroupId == $optionGroupId) {
2074 // check if option group is related to any other field
2075 self
::checkOptionGroup($currentOptionGroupId);
2079 * Check if option group is related to more than one custom field.
2081 * @param int $optionGroupId
2084 public static function checkOptionGroup($optionGroupId) {
2087 FROM civicrm_custom_field
2088 WHERE option_group_id = {$optionGroupId}";
2090 $count = CRM_Core_DAO
::singleValueQuery($query);
2093 //delete the option group
2094 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2099 * Get option group default.
2101 * @param int $optionGroupId
2102 * @param string $htmlType
2104 * @return null|string
2106 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2108 SELECT default_value, html_type
2109 FROM civicrm_custom_field
2110 WHERE option_group_id = {$optionGroupId}
2111 AND default_value IS NOT NULL
2112 ORDER BY html_type";
2114 $dao = CRM_Core_DAO
::executeQuery($query);
2115 $defaultValue = NULL;
2116 $defaultHTMLType = NULL;
2117 while ($dao->fetch()) {
2118 if ($dao->html_type
== $htmlType) {
2119 return $dao->default_value
;
2121 if ($defaultValue == NULL) {
2122 $defaultValue = $dao->default_value
;
2123 $defaultHTMLType = $dao->html_type
;
2127 // some conversions are needed if either the old or new has a html type which has potential
2128 // multiple default values.
2129 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2130 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2132 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2134 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2135 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2137 $defaultValue = substr($defaultValue, 1, -1);
2138 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2139 substr($defaultValue, 1, -1)
2141 $defaultValue = $values[0];
2144 return $defaultValue;
2148 * Post process function.
2150 * @param array $params
2151 * @param int $entityID
2152 * @param string $customFieldExtends
2153 * @param bool $inline
2154 * @param bool $checkPermissions
2158 public static function postProcess(
2161 $customFieldExtends,
2163 $checkPermissions = TRUE
2165 $customData = array();
2167 foreach ($params as $key => $value) {
2168 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2170 // for autocomplete transfer hidden value instead of label
2171 if ($params[$key] && isset($params[$key . '_id'])) {
2172 $value = $params[$key . '_id'];
2175 // we need to append time with date
2176 if ($params[$key] && isset($params[$key . '_time'])) {
2177 $value .= ' ' . $params[$key . '_time'];
2180 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2183 $customFieldExtends,
2184 $customFieldInfo[1],
2199 * Get custom field ID.
2201 * @param string $fieldLabel
2202 * @param null $groupTitle
2206 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2207 $params = array(1 => array($fieldLabel, 'String'));
2209 $params[2] = array($groupTitle, 'String');
2212 FROM civicrm_custom_field f
2213 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2214 WHERE ( f.label = %1 OR f.name = %1 )
2215 AND ( g.title = %2 OR g.name = %2 )
2221 FROM civicrm_custom_field f
2222 WHERE ( f.label = %1 OR f.name = %1 )
2226 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2227 if ($dao->fetch() &&
2238 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2244 public static function getNameFromID($ids) {
2245 if (is_array($ids)) {
2246 $ids = implode(',', $ids);
2249 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2250 FROM civicrm_custom_field f
2251 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2252 WHERE f.id IN ($ids)";
2254 $dao = CRM_Core_DAO
::executeQuery($sql);
2256 while ($dao->fetch()) {
2257 $result[$dao->id
] = array(
2258 'field_name' => $dao->field_name
,
2259 'field_label' => $dao->field_label
,
2260 'group_name' => $dao->group_name
,
2261 'group_title' => $dao->group_title
,
2268 * Validate custom data.
2270 * @param array $params
2271 * Custom data submitted.
2272 * ie array( 'custom_1' => 'validate me' );
2275 * validation errors.
2277 public static function validateCustomData($params) {
2279 if (!is_array($params) ||
empty($params)) {
2283 //pick up profile fields.
2284 $profileFields = array();
2285 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2287 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2289 CRM_Core_Action
::VIEW
2293 //lets start w/ params.
2294 foreach ($params as $key => $value) {
2295 $customFieldID = self
::getKeyID($key);
2296 if (!$customFieldID) {
2300 //load the structural info for given field.
2301 $field = new CRM_Core_DAO_CustomField();
2302 $field->id
= $customFieldID;
2303 if (!$field->find(TRUE)) {
2306 $dataType = $field->data_type
;
2308 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2309 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2310 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2312 $fieldTitle = $field->label
;
2315 //no need to validate.
2316 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2320 //lets validate first for required field.
2321 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2322 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2326 //now time to take care of custom field form rules.
2327 $ruleName = $errorMsg = NULL;
2328 switch ($dataType) {
2330 $ruleName = 'integer';
2331 $errorMsg = ts('%1 must be an integer (whole number).',
2332 array(1 => $fieldTitle)
2337 $ruleName = 'money';
2338 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2339 array(1 => $fieldTitle)
2344 $ruleName = 'numeric';
2345 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2346 array(1 => $fieldTitle)
2351 $ruleName = 'wikiURL';
2352 $errorMsg = ts('%1 must be valid Website.',
2353 array(1 => $fieldTitle)
2358 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2360 $funName = "CRM_Utils_Rule::{$ruleName}";
2361 if (is_callable($funName)) {
2362 $valid = call_user_func($funName, $value);
2365 $errors[$key] = $errorMsg;
2374 * Is this field a multi record field.
2376 * @param int $customId
2380 public static function isMultiRecordField($customId) {
2381 $isMultipleWithGid = FALSE;
2382 if (!is_numeric($customId)) {
2383 $customId = self
::getKeyID($customId);
2385 if (is_numeric($customId)) {
2386 $sql = "SELECT cg.id cgId
2387 FROM civicrm_custom_group cg
2388 INNER JOIN civicrm_custom_field cf
2389 ON cg.id = cf.custom_group_id
2390 WHERE cf.id = %1 AND cg.is_multiple = 1";
2391 $params[1] = array($customId, 'Integer');
2392 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2393 if ($dao->fetch()) {
2395 $isMultipleWithGid = $dao->cgId
;
2400 return $isMultipleWithGid;
2404 * Does this field store a serialized string?
2406 * @param array $field
2410 public static function isSerialized($field) {
2411 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2412 $field = (array) $field;
2413 // 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.
2414 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2418 * Set pseudoconstant properties for field metadata.
2420 * @param array $field
2421 * @param string|null $optionGroupName
2423 private static function getOptionsForField(&$field, $optionGroupName) {
2424 if ($optionGroupName) {
2425 $field['pseudoconstant'] = array(
2426 'optionGroupName' => $optionGroupName,
2427 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2430 elseif ($field['data_type'] == 'Boolean') {
2431 $field['pseudoconstant'] = array(
2432 'callback' => 'CRM_Core_SelectValues::boolean',
2435 elseif ($field['data_type'] == 'Country') {
2436 $field['pseudoconstant'] = array(
2437 'table' => 'civicrm_country',
2438 'keyColumn' => 'id',
2439 'labelColumn' => 'name',
2440 'nameColumn' => 'iso_code',
2443 elseif ($field['data_type'] == 'StateProvince') {
2444 $field['pseudoconstant'] = array(
2445 'table' => 'civicrm_state_province',
2446 'keyColumn' => 'id',
2447 'labelColumn' => 'name',