3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
35 * Business objects for managing custom data fields.
37 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
40 * Array for valid combinations of data_type & descriptions.
44 public static $_dataType = NULL;
47 * Array for valid combinations of data_type & html_type.
51 public static $_dataToHtml = NULL;
54 * Array to hold (formatted) fields for import
58 public static $_importFields = NULL;
61 * Build and retrieve the list of data types and descriptions.
64 * Data type => Description
66 public static function &dataType() {
67 if (!(self
::$_dataType)) {
68 self
::$_dataType = array(
69 'String' => ts('Alphanumeric'),
70 'Int' => ts('Integer'),
71 'Float' => ts('Number'),
72 'Money' => ts('Money'),
75 'Boolean' => ts('Yes or No'),
76 'StateProvince' => ts('State/Province'),
77 'Country' => ts('Country'),
80 'ContactReference' => ts('Contact Reference'),
83 return self
::$_dataType;
87 * Get data to html array.
89 * (Does this caching achieve anything?)
93 public static function dataToHtml() {
94 if (!self
::$_dataToHtml) {
95 self
::$_dataToHtml = array(
100 'CheckBox' => 'CheckBox',
101 'Multi-Select' => 'Multi-Select',
102 'AdvMulti-Select' => 'AdvMulti-Select',
103 'Autocomplete-Select' => 'Autocomplete-Select',
105 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
106 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
107 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
108 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
109 array('Date' => 'Select Date'),
110 array('Radio' => 'Radio'),
111 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
112 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
113 array('File' => 'File'),
114 array('Link' => 'Link'),
115 array('ContactReference' => 'Autocomplete-Select'),
118 return self
::$_dataToHtml;
122 * Takes an associative array and creates a custom field object.
124 * This function is invoked from within the web form layer and also from the api layer
126 * @param array $params
127 * (reference) an assoc array of name/value pairs.
129 * @return CRM_Core_DAO_CustomField
131 public static function create(&$params) {
132 $origParams = array_merge(array(), $params);
134 if (!isset($params['id'])) {
135 if (!isset($params['column_name'])) {
136 // if add mode & column_name not present, calculate it.
137 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
139 if (!isset($params['name'])) {
140 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
144 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
149 $columnName = $params['column_name'];
152 //as during create if field is_searchable we had created index.
153 if (!empty($params['id'])) {
154 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
157 switch (CRM_Utils_Array
::value('html_type', $params)) {
159 if (empty($params['date_format'])) {
160 $config = CRM_Core_Config
::singleton();
161 $params['date_format'] = $config->dateInputFormat
;
166 case 'AdvMulti-Select':
168 if (isset($params['default_checkbox_option'])) {
169 $tempArray = array_keys($params['default_checkbox_option']);
170 $defaultArray = array();
171 foreach ($tempArray as $k => $v) {
172 if ($params['option_value'][$v]) {
173 $defaultArray[] = $params['option_value'][$v];
177 if (!empty($defaultArray)) {
178 // also add the separator before and after the value per new convention (CRM-1604)
179 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
183 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
185 $params['default_value'] = $params['option_value'][$params['default_option']];
191 $transaction = new CRM_Core_Transaction();
192 // create any option group & values if required
193 if ($params['html_type'] != 'Text' &&
194 in_array($params['data_type'], array(
202 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
203 $params['custom_group_id'],
207 //CRM-16659: if option_value then create an option group for this custom field.
208 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
209 // first create an option group for this custom group
210 $optionGroup = new CRM_Core_DAO_OptionGroup();
211 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
212 $optionGroup->title
= $params['label'];
213 $optionGroup->is_active
= 1;
214 $optionGroup->save();
215 $params['option_group_id'] = $optionGroup->id
;
216 if (!empty($params['option_value']) && is_array($params['option_value'])) {
217 foreach ($params['option_value'] as $k => $v) {
218 if (strlen(trim($v))) {
219 $optionValue = new CRM_Core_DAO_OptionValue();
220 $optionValue->option_group_id
= $optionGroup->id
;
221 $optionValue->label
= $params['option_label'][$k];
222 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
223 switch ($params['data_type']) {
225 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
229 $optionValue->value
= intval($v);
233 $optionValue->value
= floatval($v);
237 $optionValue->value
= trim($v);
240 $optionValue->weight
= $params['option_weight'][$k];
241 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
242 $optionValue->save();
249 // check for orphan option groups
250 if (!empty($params['option_group_id'])) {
251 if (!empty($params['id'])) {
252 self
::fixOptionGroups($params['id'], $params['option_group_id']);
255 // if we do not have a default value
256 // retrieve it from one of the other custom fields which use this option group
257 if (empty($params['default_value'])) {
258 //don't insert only value separator as default value, CRM-4579
259 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
263 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
267 $params['default_value'] = $defaultValue;
272 // since we need to save option group id :)
273 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
274 $params['attributes'] = 'rows=4, cols=60';
277 $customField = new CRM_Core_DAO_CustomField();
278 $customField->copyValues($params);
279 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
280 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
281 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $params, FALSE);
282 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
283 //CRM-15792 - Custom field gets disabled if is_active not set
284 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, TRUE);
285 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
286 $customField->save();
288 // make sure all values are present in the object for further processing
289 $customField->find(TRUE);
291 $triggerRebuild = CRM_Utils_Array
::value('triggerRebuild', $params, TRUE);
292 //create/drop the index when we toggle the is_searchable flag
293 if (!empty($params['id'])) {
294 self
::createField($customField, 'modify', $indexExist, $triggerRebuild);
297 if (!isset($origParams['column_name'])) {
298 $columnName .= "_{$customField->id}";
299 $params['column_name'] = $columnName;
301 $customField->column_name
= $columnName;
302 $customField->save();
303 // make sure all values are present in the object
304 $customField->find(TRUE);
307 self
::createField($customField, 'add', $indexExist, $triggerRebuild);
310 // complete transaction
311 $transaction->commit();
313 CRM_Utils_System
::flushCache();
319 * Fetch object based on array of properties.
321 * @param array $params
322 * (reference ) an assoc array of name/value pairs.
323 * @param array $defaults
324 * (reference ) an assoc array to hold the flattened values.
326 * @return CRM_Core_DAO_CustomField
328 public static function retrieve(&$params, &$defaults) {
329 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
333 * Update the is_active flag in the db.
336 * Id of the database record.
337 * @param bool $is_active
338 * Value we want to set the is_active field.
341 * DAO object on success, null otherwise
343 public static function setIsActive($id, $is_active) {
345 CRM_Utils_System
::flushCache();
347 //enable-disable CustomField
348 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
349 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
353 * Get the field title.
361 public static function getTitle($id) {
362 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
366 * @param string $context
369 public function getOptions($context = 'get') {
370 CRM_Core_DAO
::buildOptionsContext($context);
376 if (!$this->data_type ||
!$this->custom_group_id
) {
380 if (!empty($this->option_group_id
)) {
381 $options = CRM_Core_OptionGroup
::valuesByID(
382 $this->option_group_id
,
387 !($context == 'validate' ||
$context == 'get')
391 if ($this->data_type
=== 'StateProvince') {
392 $options = CRM_Core_Pseudoconstant
::stateProvince();
394 elseif ($this->data_type
=== 'Country') {
395 $options = $context == 'validate' ? CRM_Core_Pseudoconstant
::countryIsoCode() : CRM_Core_Pseudoconstant
::country();
397 elseif ($this->data_type
=== 'Boolean') {
398 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
401 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
402 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
403 $entity = in_array($entity, array('Individual', 'Household', 'Organization')) ?
'Contact' : $entity;
404 CRM_Utils_Hook
::fieldOptions($entity, "custom_{$this->id}", $options, array('context' => $context));
409 * Store and return an array of all active custom fields.
411 * @param string $customDataType
412 * Type of Custom Data; empty is a synonym for "all contact data types".
413 * @param bool $showAll
414 * If true returns all fields (includes disabled fields).
415 * @param bool $inline
416 * If true returns all inline fields (includes disabled fields).
417 * @param int $customDataSubType
418 * Custom Data sub type value.
419 * @param int $customDataSubName
420 * Custom Data sub name value.
421 * @param bool $onlyParent
422 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
423 * @param bool $onlySubType
424 * Return only custom data for subtype.
425 * @param bool $checkPermission
426 * If false, do not include permissioning clause.
429 * an array of active custom fields.
431 public static function &getFields(
432 $customDataType = 'Individual',
435 $customDataSubType = NULL,
436 $customDataSubName = NULL,
438 $onlySubType = FALSE,
439 $checkPermission = TRUE
441 if (empty($customDataType)) {
442 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
444 if ($customDataType && !is_array($customDataType)) {
446 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
447 // This is the case when getFieldsForImport() requires fields
448 // limited strictly to a subtype.
449 $customDataSubType = $customDataType;
450 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
454 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
455 // this makes the method flexible to support retrieving fields
456 // for multiple extends value.
457 $customDataType = array($customDataType);
461 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
463 if (is_array($customDataType)) {
464 $cacheKey = implode('_', $customDataType);
467 $cacheKey = $customDataType;
470 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
471 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
472 $cacheKey .= $showAll ?
'_1' : '_0';
473 $cacheKey .= $inline ?
'_1_' : '_0_';
474 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
475 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
476 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
478 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
480 // also get the permission stuff here
481 if ($checkPermission) {
482 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
487 $permissionClause = '(1)';
490 // lets md5 permission clause and take first 8 characters
491 $cacheKey .= substr(md5($permissionClause), 0, 8);
493 if (strlen($cacheKey) > 40) {
494 $cacheKey = md5($cacheKey);
497 if (!self
::$_importFields ||
498 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
500 if (!self
::$_importFields) {
501 self
::$_importFields = array();
504 // check if we can retrieve from database cache
505 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
507 if ($fields === NULL) {
508 $cfTable = self
::getTableName();
511 if (is_array($customDataType)) {
513 foreach ($customDataType as $dataType) {
514 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
515 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
516 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
519 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
521 $value = $value ?
$value . ", {$val}" : $val;
525 $extends = "AND $cgTable.extends IN ( $value ) ";
529 if (!empty($customDataType) && empty($extends)) {
530 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
531 self
::$_importFields[$cacheKey] = array();
532 return self
::$_importFields[$cacheKey];
536 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
539 $query = "SELECT $cfTable.id, $cfTable.label,
543 $cfTable.default_value,
544 $cfTable.options_per_line, $cfTable.text_length,
545 $cfTable.custom_group_id,
546 $cfTable.is_required,
547 $cgTable.extends, $cfTable.is_search_range,
548 $cgTable.extends_entity_column_value,
549 $cgTable.extends_entity_column_id,
551 $cfTable.option_group_id,
552 $cfTable.date_format,
553 $cfTable.time_format,
554 $cgTable.is_multiple,
555 og.name as option_group_name
558 ON $cfTable.custom_group_id = $cgTable.id
559 LEFT JOIN civicrm_option_group og
560 ON $cfTable.option_group_id = og.id
564 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
568 $query .= " AND $cgTable.style = 'Inline' ";
571 //get the custom fields for specific type in
572 //combination with fields those support any type.
573 if (!empty($customDataSubType)) {
574 $subtypeClause = array();
575 foreach ($customDataSubType as $subtype) {
576 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
577 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
580 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
582 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
585 if ($customDataSubName) {
586 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
589 // also get the permission stuff here
590 if ($checkPermission) {
591 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
596 $permissionClause = '(1)';
599 $query .= " $extends AND $permissionClause
600 ORDER BY $cgTable.weight, $cgTable.title,
601 $cfTable.weight, $cfTable.label";
603 $dao = CRM_Core_DAO
::executeQuery($query);
606 while (($dao->fetch()) != NULL) {
607 $fields[$dao->id
]['label'] = $dao->label
;
608 $fields[$dao->id
]['groupTitle'] = $dao->title
;
609 $fields[$dao->id
]['data_type'] = $dao->data_type
;
610 $fields[$dao->id
]['html_type'] = $dao->html_type
;
611 $fields[$dao->id
]['default_value'] = $dao->default_value
;
612 $fields[$dao->id
]['text_length'] = $dao->text_length
;
613 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
614 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
615 $fields[$dao->id
]['extends'] = $dao->extends;
616 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
617 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
618 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
619 $fields[$dao->id
]['is_view'] = $dao->is_view
;
620 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
621 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
622 $fields[$dao->id
]['date_format'] = $dao->date_format
;
623 $fields[$dao->id
]['time_format'] = $dao->time_format
;
624 $fields[$dao->id
]['is_required'] = $dao->is_required
;
625 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
628 CRM_Core_BAO_Cache
::setItem($fields,
630 "custom importableFields $cacheKey"
633 self
::$_importFields[$cacheKey] = $fields;
636 return self
::$_importFields[$cacheKey];
640 * Return the field ids and names (with groups) for import purpose.
642 * @param int|string $contactType Contact type
643 * @param bool $showAll
644 * If true returns all fields (includes disabled fields).
645 * @param bool $onlyParent
646 * Return fields ONLY related to basic types.
647 * @param bool $search
648 * When called from search and multiple records need to be returned.
649 * @param bool $checkPermission
650 * If false, do not include permissioning clause.
652 * @param bool $withMultiple
656 public static function getFieldsForImport(
657 $contactType = 'Individual',
661 $checkPermission = TRUE,
662 $withMultiple = FALSE
664 // Note: there are situations when we want getFieldsForImport() return fields related
665 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
666 $fields = &self
::getFields($contactType,
676 $importableFields = array();
677 foreach ($fields as $id => $values) {
678 // for now we should not allow multiple fields in profile / export etc, hence unsetting
680 (!empty($values['is_multiple']) && !$withMultiple)
685 /* generate the key for the fields array */
689 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
690 $importableFields[$key] = array(
692 'title' => CRM_Utils_Array
::value('label', $values),
693 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
695 'custom_field_id' => $id,
696 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
697 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
698 'data_type' => CRM_Utils_Array
::value('data_type', $values),
699 'html_type' => CRM_Utils_Array
::value('html_type', $values),
700 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
703 // CRM-6681, pass date and time format when html_type = Select Date
704 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
705 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
706 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
710 return $importableFields;
714 * Get the field id from an import key.
724 public static function getKeyID($key, $all = FALSE) {
726 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
733 CRM_Utils_Array
::value(2, $match),
737 return $all ?
array(NULL, NULL) : NULL;
741 * Use the cache to get all values of a specific custom field.
743 * @param int $fieldID
744 * The custom field ID.
746 * @return CRM_Core_DAO_CustomField
749 public static function getFieldObject($fieldID) {
750 $field = new CRM_Core_DAO_CustomField();
752 // check if we can get the field values from the system cache
753 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
754 $cache = CRM_Utils_Cache
::singleton();
755 $fieldValues = $cache->get($cacheKey);
756 if (empty($fieldValues)) {
757 $field->id
= $fieldID;
758 if (!$field->find(TRUE)) {
759 CRM_Core_Error
::fatal();
762 $fieldValues = array();
763 CRM_Core_DAO
::storeValues($field, $fieldValues);
765 $cache->set($cacheKey, $fieldValues);
768 $field->copyValues($fieldValues);
775 * This function for building custom fields.
777 * @param CRM_Core_Form $qf
778 * Form object (reference).
779 * @param string $elementName
780 * Name of the custom field.
781 * @param int $fieldId
782 * @param bool $inactiveNeeded
784 * @param bool $useRequired
785 * True if required else false.
786 * @param bool $search
787 * True if used for search else false.
788 * @param string $label
789 * Label for custom field.
791 public static function addQuickFormElement(
795 $inactiveNeeded = FALSE,
800 $field = self
::getFieldObject($fieldId);
801 $widget = $field->html_type
;
803 // Custom field HTML should indicate group+field name
804 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
805 $dataCrmCustomVal = $groupName . ':' . $field->name
;
806 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
807 $field->attributes
.= $dataCrmCustomAttr;
809 // Fixed for Issue CRM-2183
810 if ($widget == 'TextArea' && $search) {
814 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
816 // FIXME: Why are select state/country separate widget types?
817 $isSelect = (in_array($widget, array(
820 'Select State/Province',
821 'Multi-Select State/Province',
823 'Multi-Select Country',
830 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array(
831 'field' => "custom_$fieldId",
832 'context' => $search ?
'search' : 'create',
835 // Consolidate widget types to simplify the below switch statement
836 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
839 $selectAttributes = array(
840 'data-crm-custom' => $dataCrmCustomVal,
841 'class' => 'crm-select2',
843 // Search field is always multi-select
844 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
845 $selectAttributes['class'] .= ' huge';
846 $selectAttributes['multiple'] = 'multiple';
847 $selectAttributes['placeholder'] = $placeholder;
849 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
850 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
851 $selectAttributes +
= array(
852 'data-api-entity' => 'contact',
853 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
854 'data-api-field' => 'custom_' . $field->id
,
855 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
860 if (!isset($label)) {
861 $label = $field->label
;
864 // at some point in time we might want to split the below into small functions
869 if ($field->is_search_range
&& $search) {
870 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
871 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
874 $element = &$qf->add('text', $elementName, $label,
876 $useRequired && !$search
882 $attributes = $dataCrmCustomAttr;
883 if ($field->note_rows
) {
884 $attributes .= 'rows=' . $field->note_rows
;
887 $attributes .= 'rows=4';
889 if ($field->note_columns
) {
890 $attributes .= ' cols=' . $field->note_columns
;
893 $attributes .= ' cols=60';
895 if ($field->text_length
) {
896 $attributes .= ' maxlength=' . $field->text_length
;
898 $element = &$qf->add('textarea',
902 $useRequired && !$search
907 if ($field->is_search_range
&& $search) {
908 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
910 'format' => $field->date_format
,
911 'timeFormat' => $field->time_format
,
912 'startOffset' => $field->start_date_years
,
913 'endOffset' => $field->end_date_years
,
914 'data-crm-custom' => $dataCrmCustomVal,
918 $qf->addDate($elementName . '_to', ts('To'), FALSE,
920 'format' => $field->date_format
,
921 'timeFormat' => $field->time_format
,
922 'startOffset' => $field->start_date_years
,
923 'endOffset' => $field->end_date_years
,
924 'data-crm-custom' => $dataCrmCustomVal,
929 $required = $useRequired && !$search;
931 $qf->addDate($elementName, $label, $required, array(
932 'format' => $field->date_format
,
933 'timeFormat' => $field->time_format
,
934 'startOffset' => $field->start_date_years
,
935 'endOffset' => $field->end_date_years
,
936 'data-crm-custom' => $dataCrmCustomVal,
943 foreach ($options as $v => $l) {
944 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
946 $group = $qf->addGroup($choice, $elementName, $label);
947 if ($useRequired && !$search) {
948 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
951 $group->setAttribute('allowClear', TRUE);
955 // For all select elements
957 if (empty($selectAttributes['multiple'])) {
958 $options = array('' => $placeholder) +
$options;
960 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
962 // Add and/or option for fields that store multiple values
963 if ($search && self
::isSerialized($field)) {
966 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
967 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
969 $qf->addGroup($operators, $elementName . '_operator');
970 $qf->setDefaults(array($elementName . '_operator' => 'or'));
974 case 'AdvMulti-Select':
975 $include =& $qf->addElement(
982 'class' => 'advmultiselect',
983 'data-crm-custom' => $dataCrmCustomVal,
987 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
988 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
990 if ($useRequired && !$search) {
991 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
997 foreach ($options as $v => $l) {
998 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
1000 $qf->addGroup($check, $elementName, $label);
1001 if ($useRequired && !$search) {
1002 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
1007 // we should not build upload file in search mode
1012 strtolower($field->html_type
),
1016 $useRequired && !$search
1018 $qf->addUploadElement($elementName);
1021 case 'RichTextEditor':
1022 $attributes = array(
1023 'rows' => $field->note_rows
,
1024 'cols' => $field->note_columns
,
1025 'data-crm-custom' => $dataCrmCustomVal,
1027 if ($field->text_length
) {
1028 $attributes['maxlength'] = $field->text_length
;
1030 $qf->add('wysiwyg', $elementName, $label, $attributes, $search);
1033 case 'Autocomplete-Select':
1034 static $customUrls = array();
1035 // Fixme: why is this a string in the first place??
1036 $attributes = array();
1037 if ($field->attributes
) {
1038 foreach (explode(' ', $field->attributes
) as $at) {
1039 if (strpos($at, '=')) {
1040 list($k, $v) = explode('=', $at);
1041 $attributes[$k] = trim($v, ' "');
1045 if ($field->data_type
== 'ContactReference') {
1046 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1047 $attributes['data-api-entity'] = 'contact';
1048 $qf->add('text', $elementName, $label, $attributes,
1049 $useRequired && !$search
1052 $urlParams = "context=customfield&id={$field->id}";
1054 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1061 // FIXME: This won't work with customFieldOptions hook
1062 $attributes +
= array(
1063 'entity' => 'option_value',
1064 'placeholder' => $placeholder,
1065 'multiple' => $search,
1067 'params' => array('option_group_id' => $field->option_group_id
),
1070 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1073 $qf->assign('customUrls', $customUrls);
1077 switch ($field->data_type
) {
1079 // integers will have numeric rule applied to them.
1080 if ($field->is_search_range
&& $search) {
1081 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1082 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1084 elseif ($widget == 'Text') {
1085 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1090 if ($field->is_search_range
&& $search) {
1091 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1092 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1094 elseif ($widget == 'Text') {
1095 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1100 if ($field->is_search_range
&& $search) {
1101 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1102 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1104 elseif ($widget == 'Text') {
1105 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1110 $element->setAttribute('class', "url");
1111 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1114 if ($field->is_view
&& !$search) {
1115 $qf->freeze($elementName);
1120 * Delete the Custom Field.
1122 * @param object $field
1125 public static function deleteField($field) {
1126 CRM_Utils_System
::flushCache();
1128 // first delete the custom option group and values associated with this field
1129 if ($field->option_group_id
) {
1130 //check if option group is related to any other field, if
1131 //not delete the option group and related option values
1132 self
::checkOptionGroup($field->option_group_id
);
1135 // next drop the column from the custom value table
1136 self
::createField($field, 'delete');
1139 CRM_Core_BAO_UFField
::delUFField($field->id
);
1140 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1144 * Find the display value for this field.
1146 * @param mixed $value
1147 * The custom field value.
1149 * The custom field id.
1150 * @param array $options
1151 * The assoc array of option name/value pairs.
1153 * @param int $contactID
1154 * @param int $fieldID
1159 public static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1160 $option = &$options[$id];
1161 $attributes = &$option['attributes'];
1162 $html_type = $attributes['html_type'];
1163 $data_type = $attributes['data_type'];
1164 // set $id as $fieldID if not passed in the params.
1165 if (empty($fieldID)) {
1169 return self
::getDisplayValueCommon($value,
1179 * Get display value.
1181 * @param string $value
1182 * @param array $option
1183 * @param string $html_type
1184 * @param string $data_type
1185 * @param int $contactID
1186 * @param int $fieldID
1188 * @return array|mixed|null|string
1190 public static function getDisplayValueCommon(
1201 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1202 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1203 $html_type == 'Select' ||
1204 $html_type == 'CheckBox' ||
1205 $html_type == 'AdvMulti-Select' ||
1206 $html_type == 'Multi-Select'
1209 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1212 switch ($html_type) {
1214 if ($data_type == 'Boolean') {
1215 $options = array('No', 'Yes');
1220 if (is_array($value)) {
1222 foreach ($value as $data) {
1223 $display .= $display ?
', ' . $options[$data] : $options[$data];
1227 $display = CRM_Utils_Array
::value($value, $options);
1231 case 'Autocomplete-Select':
1232 if ($data_type == 'ContactReference' &&
1235 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1237 elseif (is_array($value)) {
1239 foreach ($value as $data) {
1240 $display .= $display ?
', ' . $option[$data] : $option[$data];
1244 $display = CRM_Utils_Array
::value($value, $option);
1249 if (is_array($value)) {
1251 foreach ($value as $data) {
1252 $display .= $display ?
', ' . $option[$data] : $option[$data];
1256 $display = CRM_Utils_Array
::value($value, $option);
1261 case 'AdvMulti-Select':
1262 case 'Multi-Select':
1263 if (is_array($value)) {
1264 if ($html_type == 'CheckBox') {
1266 CRM_Utils_Array
::formatArrayKeys($value);
1269 $checkedData = $value;
1272 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1273 substr($value, 1, -1)
1275 if ($html_type == 'CheckBox') {
1277 foreach ($checkedData as $v) {
1278 $v = str_replace(CRM_Core_DAO
::VALUE_SEPARATOR
, '', $v);
1281 $checkedData = $newData;
1286 foreach ($checkedData as $key => $val) {
1287 $v[] = CRM_Utils_Array
::value($val, $option);
1290 $display = implode(', ', $v);
1295 if (is_array($value)) {
1296 foreach ($value as $key => $val) {
1297 $display[$key] = CRM_Utils_Date
::customFormat($val);
1301 // remove time element display if time is not set
1302 if (empty($option['attributes']['time_format'])) {
1303 $value = substr($value, 0, 10);
1305 $display = CRM_Utils_Date
::customFormat($value);
1309 case 'Select State/Province':
1310 case 'Multi-Select State/Province':
1311 case 'Select Country':
1312 case 'Multi-Select Country':
1313 if (strstr($html_type, 'State/Province')) {
1314 $option = CRM_Core_PseudoConstant
::stateProvince(FALSE, FALSE);
1317 $option = CRM_Core_PseudoConstant
::country(FALSE, FALSE);
1319 // process multi-select state/country field values
1320 if (!is_array($value)) {
1321 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1325 foreach ($value as $data) {
1326 $display .= ($display && !empty($option[$data])) ?
', ' . $option[$data] : $option[$data];
1331 // In the context of displaying a profile, show file/image
1332 if ($contactID && $value) {
1333 $url = self
::getFileURL($contactID, $fieldID, $value);
1335 $display = $url['file_url'];
1338 // In other contexts show a paperclip icon
1340 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1341 $display = $icons[$value];
1346 if (empty($value)) {
1350 $display = is_array($value) ?
nl2br(implode(', ', $value)) : nl2br($value);
1356 if (empty($value)) {
1360 $display = is_array($value) ?
implode(', ', $value) : $value;
1363 return $display ?
$display : $value;
1367 * Set default values for custom data used in profile.
1369 * @param int $customFieldId
1371 * @param string $elementName
1372 * Custom field name.
1373 * @param array $defaults
1374 * Associated array of fields.
1375 * @param int $contactId
1379 * @param mixed $value
1380 * If passed - dont fetch value from db,.
1381 * just format the given value
1383 public static function setProfileDefaults(
1391 //get the type of custom field
1392 $customField = new CRM_Core_BAO_CustomField();
1393 $customField->id
= $customFieldId;
1394 $customField->find(TRUE);
1397 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1398 $value = $customField->default_value
;
1402 if (!isset($value)) {
1403 $info = self
::getTableColumnGroup($customFieldId);
1404 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1405 $result = CRM_Core_DAO
::executeQuery($query);
1406 if ($result->fetch()) {
1407 $value = $result->value
;
1411 if ($customField->data_type
== 'Country') {
1413 $config = CRM_Core_Config
::singleton();
1414 if ($config->defaultContactCountry
) {
1415 $value = $config->defaultContactCountry();
1421 //set defaults if mode is registration
1422 if (!trim($value) &&
1424 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1426 $value = $customField->default_value
;
1429 if ($customField->data_type
== 'Money' && isset($value)) {
1430 $value = number_format($value, 2);
1432 switch ($customField->html_type
) {
1434 case 'AdvMulti-Select':
1435 case 'Multi-Select':
1436 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1437 $defaults[$elementName] = array();
1438 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1439 substr($value, 1, -1)
1441 foreach ($customOption as $val) {
1442 if (in_array($val['value'], $checkedValue)) {
1443 if ($customField->html_type
== 'CheckBox') {
1444 $defaults[$elementName][$val['value']] = 1;
1446 elseif ($customField->html_type
== 'Multi-Select' ||
1447 $customField->html_type
== 'AdvMulti-Select'
1449 $defaults[$elementName][$val['value']] = $val['value'];
1457 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1460 $customField->date_format
,
1461 $customField->time_format
1466 case 'Autocomplete-Select':
1467 if ($customField->data_type
== 'ContactReference') {
1468 if (is_numeric($value)) {
1469 $defaults[$elementName . '_id'] = $value;
1470 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1474 $defaults[$elementName] = $value;
1479 $defaults[$elementName] = $value;
1486 * @param int $contactID
1488 * @param int $fileID
1489 * @param bool $absolute
1491 * @param string $multiRecordWhereClause
1495 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1498 $params = array('id' => $cfID);
1499 $defaults = array();
1500 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1501 $columnName = $defaults['column_name'];
1503 //table name of custom data
1504 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1505 $defaults['custom_group_id'],
1509 //query to fetch id from civicrm_file
1510 if ($multiRecordWhereClause) {
1511 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1514 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1516 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1521 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1526 $result['file_id'] = $fileID;
1528 if ($fileType == 'image/jpeg' ||
1529 $fileType == 'image/pjpeg' ||
1530 $fileType == 'image/gif' ||
1531 $fileType == 'image/x-png' ||
1532 $fileType == 'image/png'
1534 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1539 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1540 list($imageWidth, $imageHeight) = getimagesize($path);
1541 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1542 $url = CRM_Utils_System
::url('civicrm/file',
1543 "reset=1&id=$fileID&eid=$contactID",
1544 $absolute, NULL, TRUE, TRUE
1546 $result['file_url'] = "
1547 <a href=\"$url\" class='crm-image-popup'>
1548 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1550 // for non image files
1553 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1557 $url = CRM_Utils_System
::url('civicrm/file',
1558 "reset=1&id=$fileID&eid=$contactID",
1559 $absolute, NULL, TRUE, TRUE
1561 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1569 * Format custom fields before inserting.
1571 * @param int $customFieldId
1573 * @param array $customFormatted
1575 * @param mixed $value
1576 * Value of custom field.
1577 * @param string $customFieldExtend
1578 * Custom field extends.
1579 * @param int $customValueId
1580 * Custom option value id.
1581 * @param int $entityId
1582 * Entity id (contribution, membership...).
1583 * @param bool $inline
1584 * Consider inline custom groups only.
1585 * @param bool $checkPermission
1586 * If false, do not include permissioning clause.
1587 * @param bool $includeViewOnly
1588 * If true, fields marked 'View Only' are included. Required for APIv3.
1590 * @return array|NULL
1591 * formatted custom field array
1593 public static function formatCustomField(
1594 $customFieldId, &$customFormatted, $value,
1595 $customFieldExtend, $customValueId = NULL,
1598 $checkPermission = TRUE,
1599 $includeViewOnly = FALSE
1601 //get the custom fields for the entity
1602 //subtype and basic type
1603 $customDataSubType = NULL;
1604 if ($customFieldExtend) {
1605 // This is the case when getFieldsForImport() requires fields
1606 // of subtype and its parent.CRM-5143
1607 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1608 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1609 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1610 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1611 if (is_array($customFieldExtend)) {
1612 $customFieldExtend = array_unique(array_values($customFieldExtend));
1617 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1627 if (!array_key_exists($customFieldId, $customFields)) {
1631 // return if field is a 'code' field
1632 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1636 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1638 if (!$customValueId &&
1639 // we always create new entites for is_multiple unless specified
1640 !$customFields[$customFieldId]['is_multiple'] &&
1646 WHERE entity_id={$entityId}";
1648 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1651 //fix checkbox, now check box always submits values
1652 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1654 // Note that only during merge this is not an array, and you can directly use value
1655 if (is_array($value)) {
1656 $selectedValues = array();
1657 foreach ($value as $selId => $val) {
1659 $selectedValues[] = $selId;
1662 if (!empty($selectedValues)) {
1663 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1665 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1674 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1675 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1678 $value = CRM_Utils_Array
::implodePadded($value);
1685 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1686 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1687 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1689 $customFields[$customFieldId]['data_type'] == 'String' &&
1690 !empty($customFields[$customFieldId]['text_length']) &&
1693 // lets make sure that value is less than the length, else we'll
1694 // be losing some data, CRM-7481
1695 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1696 // need to do a few things here
1698 // 1. lets find a new length
1699 $newLength = $customFields[$customFieldId]['text_length'];
1700 $minLength = strlen($value);
1701 while ($newLength < $minLength) {
1702 $newLength = $newLength * 2;
1705 // set the custom field meta data to have a length larger than value
1706 // alter the custom value table column to match this length
1707 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1712 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1713 if (!CRM_Utils_System
::isNull($value)) {
1714 $format = $customFields[$customFieldId]['date_format'];
1715 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1720 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1721 $customFields[$customFieldId]['data_type'] == 'Money'
1727 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1728 $value = CRM_Utils_Rule
::cleanMoney($value);
1732 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1733 $customFields[$customFieldId]['data_type'] == 'Country'
1743 if ($customFields[$customFieldId]['data_type'] == 'File') {
1744 if (empty($value)) {
1748 $config = CRM_Core_Config
::singleton();
1750 $fName = $value['name'];
1751 $mimeType = $value['type'];
1753 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1755 // rename this file to go into the secure directory
1756 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1757 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1760 if ($customValueId) {
1765 $params = array(1 => array($customValueId, 'Integer'));
1766 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1769 $fileDAO = new CRM_Core_DAO_File();
1772 $fileDAO->id
= $fileId;
1775 $fileDAO->uri
= $filename;
1776 $fileDAO->mime_type
= $mimeType;
1777 $fileDAO->upload_date
= date('Ymdhis');
1779 $fileId = $fileDAO->id
;
1783 if (!is_array($customFormatted)) {
1784 $customFormatted = array();
1787 if (!array_key_exists($customFieldId, $customFormatted)) {
1788 $customFormatted[$customFieldId] = array();
1792 if ($customValueId) {
1793 $index = $customValueId;
1796 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1797 $customFormatted[$customFieldId][$index] = array();
1799 $customFormatted[$customFieldId][$index] = array(
1800 'id' => $customValueId > 0 ?
$customValueId : NULL,
1802 'type' => $customFields[$customFieldId]['data_type'],
1803 'custom_field_id' => $customFieldId,
1804 'custom_group_id' => $groupID,
1805 'table_name' => $tableName,
1806 'column_name' => $columnName,
1807 'file_id' => $fileId,
1808 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1811 //we need to sort so that custom fields are created in the order of entry
1812 krsort($customFormatted[$customFieldId]);
1813 return $customFormatted;
1817 * Get default custom table schema.
1819 * @param array $params
1823 public static function defaultCustomTableSchema($params) {
1824 // add the id and extends_id
1826 'name' => $params['name'],
1827 'is_multiple' => $params['is_multiple'],
1828 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1832 'type' => 'int unsigned',
1835 'attributes' => 'AUTO_INCREMENT',
1836 'comment' => 'Default MySQL primary key',
1839 'name' => 'entity_id',
1840 'type' => 'int unsigned',
1842 'comment' => 'Table that this extends',
1843 'fk_table_name' => $params['extends_name'],
1844 'fk_field_name' => 'id',
1845 'fk_attributes' => 'ON DELETE CASCADE',
1850 if (!$params['is_multiple']) {
1851 $table['indexes'] = array(
1854 'field_name_1' => 'entity_id',
1862 * Create custom field.
1864 * @param CRM_Core_DAO_CustomField $field
1865 * @param string $operation
1866 * @param bool $indexExist
1867 * @param bool $triggerRebuild
1869 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1870 $tableName = CRM_Core_DAO
::getFieldValue(
1871 'CRM_Core_DAO_CustomGroup',
1872 $field->custom_group_id
,
1877 'table_name' => $tableName,
1878 'operation' => $operation,
1879 'name' => $field->column_name
,
1880 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1884 'required' => $field->is_required
,
1885 'searchable' => $field->is_searchable
,
1888 if ($operation == 'delete') {
1889 $fkName = "{$tableName}_{$field->column_name}";
1890 if (strlen($fkName) >= 48) {
1891 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1893 $params['fkName'] = $fkName;
1895 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1896 $params['fk_table_name'] = 'civicrm_country';
1897 $params['fk_field_name'] = 'id';
1898 $params['fk_attributes'] = 'ON DELETE SET NULL';
1900 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1901 $params['type'] = 'varchar(255)';
1903 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1904 $params['fk_table_name'] = 'civicrm_state_province';
1905 $params['fk_field_name'] = 'id';
1906 $params['fk_attributes'] = 'ON DELETE SET NULL';
1908 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1909 $params['type'] = 'varchar(255)';
1911 elseif ($field->data_type
== 'File') {
1912 $params['fk_table_name'] = 'civicrm_file';
1913 $params['fk_field_name'] = 'id';
1914 $params['fk_attributes'] = 'ON DELETE SET NULL';
1916 elseif ($field->data_type
== 'ContactReference') {
1917 $params['fk_table_name'] = 'civicrm_contact';
1918 $params['fk_field_name'] = 'id';
1919 $params['fk_attributes'] = 'ON DELETE SET NULL';
1921 if (isset($field->default_value
)) {
1922 $params['default'] = "'{$field->default_value}'";
1925 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1929 * Determine whether it would be safe to move a field.
1931 * @param int $fieldID
1932 * FK to civicrm_custom_field.
1933 * @param int $newGroupID
1934 * FK to civicrm_custom_group.
1937 * array(string) or TRUE
1939 public static function _moveFieldValidate($fieldID, $newGroupID) {
1942 $field = new CRM_Core_DAO_CustomField();
1943 $field->id
= $fieldID;
1944 if (!$field->find(TRUE)) {
1945 $errors['fieldID'] = 'Invalid ID for custom field';
1949 $oldGroup = new CRM_Core_DAO_CustomGroup();
1950 $oldGroup->id
= $field->custom_group_id
;
1951 if (!$oldGroup->find(TRUE)) {
1952 $errors['fieldID'] = 'Invalid ID for old custom group';
1956 $newGroup = new CRM_Core_DAO_CustomGroup();
1957 $newGroup->id
= $newGroupID;
1958 if (!$newGroup->find(TRUE)) {
1959 $errors['newGroupID'] = 'Invalid ID for new custom group';
1965 FROM civicrm_custom_field a
1966 INNER JOIN civicrm_custom_field b
1968 AND a.label = b.label
1969 AND b.custom_group_id = %2
1972 1 => array($field->id
, 'Integer'),
1973 2 => array($newGroup->id
, 'Integer'),
1975 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1977 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1980 $tableName = $oldGroup->table_name
;
1981 $columnName = $field->column_name
;
1986 WHERE $columnName is not null
1988 $count = CRM_Core_DAO
::singleValueQuery($query,
1989 CRM_Core_DAO
::$_nullArray
1994 FROM civicrm_custom_group
1995 WHERE id IN ( %1, %2 )
1998 1 => array($oldGroup->id
, 'Integer'),
1999 2 => array($newGroup->id
, 'Integer'),
2002 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2004 while ($dao->fetch()) {
2005 $extends[] = $dao->extends;
2007 if ($extends[0] != $extends[1]) {
2008 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
2012 return empty($errors) ?
TRUE : $errors;
2016 * Move a custom data field from one group (table) to another.
2018 * @param int $fieldID
2019 * FK to civicrm_custom_field.
2020 * @param int $newGroupID
2021 * FK to civicrm_custom_group.
2023 public static function moveField($fieldID, $newGroupID) {
2024 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
2025 if (TRUE !== $validation) {
2026 CRM_Core_Error
::fatal(implode(' ', $validation));
2028 $field = new CRM_Core_DAO_CustomField();
2029 $field->id
= $fieldID;
2032 $newGroup = new CRM_Core_DAO_CustomGroup();
2033 $newGroup->id
= $newGroupID;
2034 $newGroup->find(TRUE);
2036 $oldGroup = new CRM_Core_DAO_CustomGroup();
2037 $oldGroup->id
= $field->custom_group_id
;
2038 $oldGroup->find(TRUE);
2041 $add->custom_group_id
= $newGroup->id
;
2042 self
::createField($add, 'add');
2044 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2045 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2046 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2048 CRM_Core_DAO
::executeQuery($sql);
2051 $del->custom_group_id
= $oldGroup->id
;
2052 self
::createField($del, 'delete');
2056 CRM_Utils_System
::flushCache();
2060 * Get the database table name and column name for a custom field.
2062 * @param int $fieldID
2063 * The fieldID of the custom field.
2064 * @param bool $force
2065 * Force the sql to be run again (primarily used for tests).
2068 * fatal is fieldID does not exists, else array of tableName, columnName
2070 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2071 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2072 $cache = CRM_Utils_Cache
::singleton();
2073 $fieldValues = $cache->get($cacheKey);
2074 if (empty($fieldValues) ||
$force) {
2076 SELECT cg.table_name, cf.column_name, cg.id
2077 FROM civicrm_custom_group cg,
2078 civicrm_custom_field cf
2079 WHERE cf.custom_group_id = cg.id
2081 $params = array(1 => array($fieldID, 'Integer'));
2082 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2084 if (!$dao->fetch()) {
2085 CRM_Core_Error
::fatal();
2088 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2089 $cache->set($cacheKey, $fieldValues);
2091 return $fieldValues;
2095 * Get custom option groups.
2097 * @param array $includeFieldIds
2098 * Ids of custom fields for which option groups must be included.
2100 * Currently this is required in the cases where option groups are to be included
2101 * for inactive fields : CRM-5369
2105 public static function customOptionGroup($includeFieldIds = NULL) {
2106 static $customOptionGroup = NULL;
2108 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2109 if ($cacheKey == 'force') {
2110 $customOptionGroup[$cacheKey] = NULL;
2113 if (empty($customOptionGroup[$cacheKey])) {
2114 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2116 //support for single as well as array format.
2117 if (!empty($includeFieldIds)) {
2118 if (is_array($includeFieldIds)) {
2119 $includeFieldIds = implode(',', $includeFieldIds);
2121 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2125 SELECT g.id, g.title
2126 FROM civicrm_option_group g
2127 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2128 WHERE {$whereClause}";
2130 $dao = CRM_Core_DAO
::executeQuery($query);
2131 while ($dao->fetch()) {
2132 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2136 return $customOptionGroup[$cacheKey];
2140 * Fix orphan groups.
2142 * @param int $customFieldId
2144 * @param int $optionGroupId
2147 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2148 // check if option group belongs to any custom Field else delete
2149 // get the current option group
2150 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2154 // get the updated option group
2155 // if both are same return
2156 if ($currentOptionGroupId == $optionGroupId) {
2160 // check if option group is related to any other field
2161 self
::checkOptionGroup($currentOptionGroupId);
2165 * Check if option group is related to more than one custom field.
2167 * @param int $optionGroupId
2170 public static function checkOptionGroup($optionGroupId) {
2173 FROM civicrm_custom_field
2174 WHERE option_group_id = {$optionGroupId}";
2176 $count = CRM_Core_DAO
::singleValueQuery($query);
2179 //delete the option group
2180 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2185 * Get option group default.
2187 * @param int $optionGroupId
2188 * @param string $htmlType
2190 * @return null|string
2192 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2194 SELECT default_value, html_type
2195 FROM civicrm_custom_field
2196 WHERE option_group_id = {$optionGroupId}
2197 AND default_value IS NOT NULL
2198 ORDER BY html_type";
2200 $dao = CRM_Core_DAO
::executeQuery($query);
2201 $defaultValue = NULL;
2202 $defaultHTMLType = NULL;
2203 while ($dao->fetch()) {
2204 if ($dao->html_type
== $htmlType) {
2205 return $dao->default_value
;
2207 if ($defaultValue == NULL) {
2208 $defaultValue = $dao->default_value
;
2209 $defaultHTMLType = $dao->html_type
;
2213 // some conversions are needed if either the old or new has a html type which has potential
2214 // multiple default values.
2215 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2216 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2218 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2220 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2221 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2223 $defaultValue = substr($defaultValue, 1, -1);
2224 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2225 substr($defaultValue, 1, -1)
2227 $defaultValue = $values[0];
2230 return $defaultValue;
2234 * Post process function.
2236 * @param array $params
2237 * @param int $entityID
2238 * @param string $customFieldExtends
2239 * @param bool $inline
2240 * @param bool $checkPermissions
2244 public static function postProcess(
2247 $customFieldExtends,
2249 $checkPermissions = TRUE
2251 $customData = array();
2253 foreach ($params as $key => $value) {
2254 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2256 // for autocomplete transfer hidden value instead of label
2257 if ($params[$key] && isset($params[$key . '_id'])) {
2258 $value = $params[$key . '_id'];
2261 // we need to append time with date
2262 if ($params[$key] && isset($params[$key . '_time'])) {
2263 $value .= ' ' . $params[$key . '_time'];
2266 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2269 $customFieldExtends,
2270 $customFieldInfo[1],
2285 * Get custom field ID.
2287 * @param string $fieldLabel
2288 * @param null $groupTitle
2292 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2293 $params = array(1 => array($fieldLabel, 'String'));
2295 $params[2] = array($groupTitle, 'String');
2298 FROM civicrm_custom_field f
2299 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2300 WHERE ( f.label = %1 OR f.name = %1 )
2301 AND ( g.title = %2 OR g.name = %2 )
2307 FROM civicrm_custom_field f
2308 WHERE ( f.label = %1 OR f.name = %1 )
2312 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2313 if ($dao->fetch() &&
2324 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2330 public static function getNameFromID($ids) {
2331 if (is_array($ids)) {
2332 $ids = implode(',', $ids);
2335 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2336 FROM civicrm_custom_field f
2337 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2338 WHERE f.id IN ($ids)";
2340 $dao = CRM_Core_DAO
::executeQuery($sql);
2342 while ($dao->fetch()) {
2343 $result[$dao->id
] = array(
2344 'field_name' => $dao->field_name
,
2345 'field_label' => $dao->field_label
,
2346 'group_name' => $dao->group_name
,
2347 'group_title' => $dao->group_title
,
2354 * Validate custom data.
2356 * @param array $params
2357 * Custom data submitted.
2358 * ie array( 'custom_1' => 'validate me' );
2361 * validation errors.
2363 public static function validateCustomData($params) {
2365 if (!is_array($params) ||
empty($params)) {
2369 //pick up profile fields.
2370 $profileFields = array();
2371 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2373 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2375 CRM_Core_Action
::VIEW
2379 //lets start w/ params.
2380 foreach ($params as $key => $value) {
2381 $customFieldID = self
::getKeyID($key);
2382 if (!$customFieldID) {
2386 //load the structural info for given field.
2387 $field = new CRM_Core_DAO_CustomField();
2388 $field->id
= $customFieldID;
2389 if (!$field->find(TRUE)) {
2392 $dataType = $field->data_type
;
2394 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2395 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2396 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2398 $fieldTitle = $field->label
;
2401 //no need to validate.
2402 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2406 //lets validate first for required field.
2407 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2408 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2412 //now time to take care of custom field form rules.
2413 $ruleName = $errorMsg = NULL;
2414 switch ($dataType) {
2416 $ruleName = 'integer';
2417 $errorMsg = ts('%1 must be an integer (whole number).',
2418 array(1 => $fieldTitle)
2423 $ruleName = 'money';
2424 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2425 array(1 => $fieldTitle)
2430 $ruleName = 'numeric';
2431 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2432 array(1 => $fieldTitle)
2437 $ruleName = 'wikiURL';
2438 $errorMsg = ts('%1 must be valid Website.',
2439 array(1 => $fieldTitle)
2444 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2446 $funName = "CRM_Utils_Rule::{$ruleName}";
2447 if (is_callable($funName)) {
2448 $valid = call_user_func($funName, $value);
2451 $errors[$key] = $errorMsg;
2460 * Is this field a multi record field.
2462 * @param int $customId
2466 public static function isMultiRecordField($customId) {
2467 $isMultipleWithGid = FALSE;
2468 if (!is_numeric($customId)) {
2469 $customId = self
::getKeyID($customId);
2471 if (is_numeric($customId)) {
2472 $sql = "SELECT cg.id cgId
2473 FROM civicrm_custom_group cg
2474 INNER JOIN civicrm_custom_field cf
2475 ON cg.id = cf.custom_group_id
2476 WHERE cf.id = %1 AND cg.is_multiple = 1";
2477 $params[1] = array($customId, 'Integer');
2478 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2479 if ($dao->fetch()) {
2481 $isMultipleWithGid = $dao->cgId
;
2486 return $isMultipleWithGid;
2490 * Does this field store a serialized string?
2492 * @param array $field
2496 public static function isSerialized($field) {
2497 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2498 $field = (array) $field;
2499 // 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.
2500 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2504 * Get options for field.
2506 * @param array $field
2507 * @param string|null $optionGroupName
2509 private static function getOptionsForField(&$field, $optionGroupName) {
2510 if ($optionGroupName) {
2511 $field['pseudoconstant'] = array(
2512 'optionGroupName' => $optionGroupName,
2513 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2516 elseif ($field['data_type'] == 'Boolean') {
2517 $field['pseudoconstant'] = array(
2518 'callback' => 'CRM_Core_SelectValues::boolean',
2521 elseif ($field['data_type'] == 'Country') {
2522 $field['pseudoconstant'] = array(
2523 'table' => 'civicrm_country',
2524 'keyColumn' => 'id',
2525 'labelColumn' => 'name',
2526 'nameColumn' => 'iso_code',
2529 elseif ($field['data_type'] == 'StateProvince') {
2530 $field['pseudoconstant'] = array(
2531 'table' => 'civicrm_state_province',
2532 'keyColumn' => 'id',
2533 'labelColumn' => 'name',