3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
35 * Business objects for managing custom data fields.
37 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
40 * Array for valid combinations of data_type & descriptions.
44 public static $_dataType = NULL;
47 * Array for valid combinations of data_type & html_type.
51 public static $_dataToHtml = NULL;
54 * Array to hold (formatted) fields for import
58 public static $_importFields = NULL;
61 * Build and retrieve the list of data types and descriptions.
64 * Data type => Description
66 public static function &dataType() {
67 if (!(self
::$_dataType)) {
68 self
::$_dataType = array(
69 'String' => ts('Alphanumeric'),
70 'Int' => ts('Integer'),
71 'Float' => ts('Number'),
72 'Money' => ts('Money'),
75 'Boolean' => ts('Yes or No'),
76 'StateProvince' => ts('State/Province'),
77 'Country' => ts('Country'),
80 'ContactReference' => ts('Contact Reference'),
83 return self
::$_dataType;
87 * 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 $op = empty($params['id']) ?
'create' : 'edit';
136 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
138 if ($op == 'create') {
139 if (!isset($params['column_name'])) {
140 // if add mode & column_name not present, calculate it.
141 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
143 if (!isset($params['name'])) {
144 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
148 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
153 $columnName = $params['column_name'];
156 //as during create if field is_searchable we had created index.
157 if (!empty($params['id'])) {
158 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
161 switch (CRM_Utils_Array
::value('html_type', $params)) {
163 if (empty($params['date_format'])) {
164 $config = CRM_Core_Config
::singleton();
165 $params['date_format'] = $config->dateInputFormat
;
170 case 'AdvMulti-Select':
172 if (isset($params['default_checkbox_option'])) {
173 $tempArray = array_keys($params['default_checkbox_option']);
174 $defaultArray = array();
175 foreach ($tempArray as $k => $v) {
176 if ($params['option_value'][$v]) {
177 $defaultArray[] = $params['option_value'][$v];
181 if (!empty($defaultArray)) {
182 // also add the separator before and after the value per new convention (CRM-1604)
183 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
187 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
189 $params['default_value'] = $params['option_value'][$params['default_option']];
195 $transaction = new CRM_Core_Transaction();
196 // create any option group & values if required
197 if ($params['html_type'] != 'Text' &&
198 in_array($params['data_type'], array(
206 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
207 $params['custom_group_id'],
211 //CRM-16659: if option_value then create an option group for this custom field.
212 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
213 // first create an option group for this custom group
214 $optionGroup = new CRM_Core_DAO_OptionGroup();
215 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
216 $optionGroup->title
= $params['label'];
217 $optionGroup->is_active
= 1;
218 $optionGroup->data_type
= $params['data_type'];
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
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_Hook
::post($op, 'CustomField', $customField->id
, $customField);
320 CRM_Utils_System
::flushCache();
326 * Fetch object based on array of properties.
328 * @param array $params
329 * (reference ) an assoc array of name/value pairs.
330 * @param array $defaults
331 * (reference ) an assoc array to hold the flattened values.
333 * @return CRM_Core_DAO_CustomField
335 public static function retrieve(&$params, &$defaults) {
336 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
340 * Update the is_active flag in the db.
343 * Id of the database record.
344 * @param bool $is_active
345 * Value we want to set the is_active field.
348 * DAO object on success, null otherwise
350 public static function setIsActive($id, $is_active) {
352 CRM_Utils_System
::flushCache();
354 //enable-disable CustomField
355 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
356 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
360 * Get the field title.
368 public static function getTitle($id) {
369 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
373 * @param string $context
376 public function getOptions($context = NULL) {
377 CRM_Core_DAO
::buildOptionsContext($context);
382 if (!$this->data_type ||
!$this->custom_group_id
) {
386 if (!empty($this->option_group_id
)) {
387 $options = CRM_Core_OptionGroup
::valuesByID(
388 $this->option_group_id
,
393 !($context == 'validate' ||
$context == 'get')
396 elseif ($this->data_type
=== 'StateProvince') {
397 $options = CRM_Core_Pseudoconstant
::stateProvince();
399 elseif ($this->data_type
=== 'Country') {
400 $options = $context == 'validate' ? CRM_Core_Pseudoconstant
::countryIsoCode() : CRM_Core_Pseudoconstant
::country();
402 elseif ($this->data_type
=== 'Boolean') {
403 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
408 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
409 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "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 $cfTable.column_name,
553 $cgTable.extends, $cfTable.is_search_range,
554 $cgTable.extends_entity_column_value,
555 $cgTable.extends_entity_column_id,
557 $cfTable.option_group_id,
558 $cfTable.date_format,
559 $cfTable.time_format,
560 $cgTable.is_multiple,
562 og.name as option_group_name
565 ON $cfTable.custom_group_id = $cgTable.id
566 LEFT JOIN civicrm_option_group og
567 ON $cfTable.option_group_id = og.id
571 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
575 $query .= " AND $cgTable.style = 'Inline' ";
578 //get the custom fields for specific type in
579 //combination with fields those support any type.
580 if (!empty($customDataSubType)) {
581 $subtypeClause = array();
582 foreach ($customDataSubType as $subtype) {
583 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
584 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
587 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
589 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
592 if ($customDataSubName) {
593 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
596 // also get the permission stuff here
597 if ($checkPermission) {
598 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
603 $permissionClause = '(1)';
606 $query .= " $extends AND $permissionClause
607 ORDER BY $cgTable.weight, $cgTable.title,
608 $cfTable.weight, $cfTable.label";
610 $dao = CRM_Core_DAO
::executeQuery($query);
613 while (($dao->fetch()) != NULL) {
614 $fields[$dao->id
]['label'] = $dao->label
;
615 $fields[$dao->id
]['groupTitle'] = $dao->title
;
616 $fields[$dao->id
]['data_type'] = $dao->data_type
;
617 $fields[$dao->id
]['html_type'] = $dao->html_type
;
618 $fields[$dao->id
]['default_value'] = $dao->default_value
;
619 $fields[$dao->id
]['text_length'] = $dao->text_length
;
620 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
621 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
622 $fields[$dao->id
]['extends'] = $dao->extends;
623 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
624 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
625 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
626 $fields[$dao->id
]['is_view'] = $dao->is_view
;
627 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
628 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
629 $fields[$dao->id
]['date_format'] = $dao->date_format
;
630 $fields[$dao->id
]['time_format'] = $dao->time_format
;
631 $fields[$dao->id
]['is_required'] = $dao->is_required
;
632 $fields[$dao->id
]['table_name'] = $dao->table_name
;
633 $fields[$dao->id
]['column_name'] = $dao->column_name
;
634 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
637 CRM_Core_BAO_Cache
::setItem($fields,
639 "custom importableFields $cacheKey"
642 self
::$_importFields[$cacheKey] = $fields;
645 return self
::$_importFields[$cacheKey];
649 * Return the field ids and names (with groups) for import purpose.
651 * @param int|string $contactType Contact type
652 * @param bool $showAll
653 * If true returns all fields (includes disabled fields).
654 * @param bool $onlyParent
655 * Return fields ONLY related to basic types.
656 * @param bool $search
657 * When called from search and multiple records need to be returned.
658 * @param bool $checkPermission
659 * If false, do not include permissioning clause.
661 * @param bool $withMultiple
665 public static function getFieldsForImport(
666 $contactType = 'Individual',
670 $checkPermission = TRUE,
671 $withMultiple = FALSE
673 // Note: there are situations when we want getFieldsForImport() return fields related
674 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
675 $fields = &self
::getFields($contactType,
685 $importableFields = array();
686 foreach ($fields as $id => $values) {
687 // for now we should not allow multiple fields in profile / export etc, hence unsetting
689 (!empty($values['is_multiple']) && !$withMultiple)
694 /* generate the key for the fields array */
698 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
699 $importableFields[$key] = array(
701 'title' => CRM_Utils_Array
::value('label', $values),
702 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
704 'custom_field_id' => $id,
705 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
706 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
707 'data_type' => CRM_Utils_Array
::value('data_type', $values),
708 'html_type' => CRM_Utils_Array
::value('html_type', $values),
709 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
712 // CRM-6681, pass date and time format when html_type = Select Date
713 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
714 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
715 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
719 return $importableFields;
723 * Get the field id from an import key.
733 public static function getKeyID($key, $all = FALSE) {
735 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
742 CRM_Utils_Array
::value(2, $match),
746 return $all ?
array(NULL, NULL) : NULL;
750 * Use the cache to get all values of a specific custom field.
752 * @param int $fieldID
753 * The custom field ID.
755 * @return CRM_Core_BAO_CustomField
758 public static function getFieldObject($fieldID) {
759 $field = new CRM_Core_BAO_CustomField();
761 // check if we can get the field values from the system cache
762 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
763 $cache = CRM_Utils_Cache
::singleton();
764 $fieldValues = $cache->get($cacheKey);
765 if (empty($fieldValues)) {
766 $field->id
= $fieldID;
767 if (!$field->find(TRUE)) {
768 CRM_Core_Error
::fatal();
771 $fieldValues = array();
772 CRM_Core_DAO
::storeValues($field, $fieldValues);
774 $cache->set($cacheKey, $fieldValues);
777 $field->copyValues($fieldValues);
784 * Add a custom field to an existing form.
786 * @param CRM_Core_Form $qf
787 * Form object (reference).
788 * @param string $elementName
789 * Name of the custom field.
790 * @param int $fieldId
791 * @param bool $useRequired
792 * True if required else false.
793 * @param bool $search
794 * True if used for search else false.
795 * @param string $label
796 * Label for custom field.
797 * @return \HTML_QuickForm_Element|null
798 * @throws \CiviCRM_API3_Exception
800 public static function addQuickFormElement(
801 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
803 $field = self
::getFieldObject($fieldId);
804 $widget = $field->html_type
;
807 // Custom field HTML should indicate group+field name
808 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
809 $dataCrmCustomVal = $groupName . ':' . $field->name
;
810 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
811 $field->attributes
.= $dataCrmCustomAttr;
813 // Fixed for Issue CRM-2183
814 if ($widget == 'TextArea' && $search) {
818 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
820 // FIXME: Why are select state/country separate widget types?
821 $isSelect = (in_array($widget, array(
824 'Select State/Province',
825 'Multi-Select State/Province',
827 'Multi-Select Country',
834 $options = $field->getOptions($search ?
'search' : 'create');
836 // Consolidate widget types to simplify the below switch statement
837 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
840 $selectAttributes = array(
841 'data-crm-custom' => $dataCrmCustomVal,
842 'class' => 'crm-select2',
844 // Search field is always multi-select
845 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
846 $selectAttributes['class'] .= ' huge';
847 $selectAttributes['multiple'] = 'multiple';
848 $selectAttributes['placeholder'] = $placeholder;
850 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
851 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
852 $selectAttributes +
= array(
853 'data-api-entity' => $field->getEntity(),
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 if ($field->text_length
) {
875 $field->attributes
.= ' maxlength=' . $field->text_length
;
876 if ($field->text_length
< 20) {
877 $field->attributes
.= ' size=' . $field->text_length
;
880 $element = $qf->add('text', $elementName, $label,
882 $useRequired && !$search
888 $attributes = $dataCrmCustomAttr;
889 if ($field->note_rows
) {
890 $attributes .= 'rows=' . $field->note_rows
;
893 $attributes .= 'rows=4';
895 if ($field->note_columns
) {
896 $attributes .= ' cols=' . $field->note_columns
;
899 $attributes .= ' cols=60';
901 if ($field->text_length
) {
902 $attributes .= ' maxlength=' . $field->text_length
;
904 $element = $qf->add('textarea',
908 $useRequired && !$search
913 $attr = array('data-crm-custom' => $dataCrmCustomVal);
914 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
915 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
916 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
919 'date' => $field->date_format
,
920 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
921 //CRM-18487 - max date should be the last date of the year.
922 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
923 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
925 if ($field->is_search_range
&& $search) {
926 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
927 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
930 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
936 foreach ($options as $v => $l) {
937 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
939 $element = $qf->addGroup($choice, $elementName, $label);
940 if ($useRequired && !$search) {
941 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
944 $element->setAttribute('allowClear', TRUE);
948 // For all select elements
950 if (empty($selectAttributes['multiple'])) {
951 $options = array('' => $placeholder) +
$options;
953 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
955 // Add and/or option for fields that store multiple values
956 if ($search && self
::isSerialized($field)) {
959 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
960 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
962 $qf->addGroup($operators, $elementName . '_operator');
963 $qf->setDefaults(array($elementName . '_operator' => 'or'));
967 case 'AdvMulti-Select':
968 $element = $qf->addElement(
975 'class' => 'advmultiselect',
976 'data-crm-custom' => $dataCrmCustomVal,
980 $element->setButtonAttributes('add', array('value' => ts('Add >>')));
981 $element->setButtonAttributes('remove', array('value' => ts('<< Remove')));
983 if ($useRequired && !$search) {
984 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
990 foreach ($options as $v => $l) {
991 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
993 $element = $qf->addGroup($check, $elementName, $label);
994 if ($useRequired && !$search) {
995 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
1000 // we should not build upload file in search mode
1004 $element = $qf->add(
1005 strtolower($field->html_type
),
1009 $useRequired && !$search
1011 $qf->addUploadElement($elementName);
1014 case 'RichTextEditor':
1015 $attributes = array(
1016 'rows' => $field->note_rows
,
1017 'cols' => $field->note_columns
,
1018 'data-crm-custom' => $dataCrmCustomVal,
1020 if ($field->text_length
) {
1021 $attributes['maxlength'] = $field->text_length
;
1023 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
1026 case 'Autocomplete-Select':
1027 static $customUrls = array();
1028 // Fixme: why is this a string in the first place??
1029 $attributes = array();
1030 if ($field->attributes
) {
1031 foreach (explode(' ', $field->attributes
) as $at) {
1032 if (strpos($at, '=')) {
1033 list($k, $v) = explode('=', $at);
1034 $attributes[$k] = trim($v, ' "');
1038 if ($field->data_type
== 'ContactReference') {
1039 // break if contact does not have permission to access ContactReference
1040 if (!CRM_Core_Permission
::check('access contact reference fields')) {
1043 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1044 $attributes['data-api-entity'] = 'Contact';
1045 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
1047 $urlParams = "context=customfield&id={$field->id}";
1049 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1056 // FIXME: This won't work with customFieldOptions hook
1057 $attributes +
= array(
1058 'entity' => 'option_value',
1059 'placeholder' => $placeholder,
1060 'multiple' => $search,
1062 'params' => array('option_group_id' => $field->option_group_id
),
1065 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1068 $qf->assign('customUrls', $customUrls);
1072 switch ($field->data_type
) {
1074 // integers will have numeric rule applied to them.
1075 if ($field->is_search_range
&& $search) {
1076 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1077 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1079 elseif ($widget == 'Text') {
1080 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1085 if ($field->is_search_range
&& $search) {
1086 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1087 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1089 elseif ($widget == 'Text') {
1090 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1095 if ($field->is_search_range
&& $search) {
1096 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1097 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1099 elseif ($widget == 'Text') {
1100 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1105 $element->setAttribute('class', "url");
1106 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1109 if ($field->is_view
&& !$search) {
1110 $qf->freeze($elementName);
1116 * Delete the Custom Field.
1118 * @param object $field
1121 public static function deleteField($field) {
1122 CRM_Utils_System
::flushCache();
1124 // first delete the custom option group and values associated with this field
1125 if ($field->option_group_id
) {
1126 //check if option group is related to any other field, if
1127 //not delete the option group and related option values
1128 self
::checkOptionGroup($field->option_group_id
);
1131 // next drop the column from the custom value table
1132 self
::createField($field, 'delete');
1135 CRM_Core_BAO_UFField
::delUFField($field->id
);
1136 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1138 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
1142 * @param string|int|array|null $value
1143 * @param CRM_Core_BAO_CustomField|int|array|string $field
1144 * @param int $entityId
1147 * @throws \Exception
1149 public static function displayValue($value, $field, $entityId = NULL) {
1150 $field = is_array($field) ?
$field['id'] : $field;
1151 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1154 throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1157 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1158 $field = self
::getFieldObject($fieldId);
1161 $fieldInfo = array('options' => $field->getOptions()) +
(array) $field;
1163 return self
::formatDisplayValue($value, $fieldInfo, $entityId);
1167 * Lower-level logic for rendering a custom field value
1169 * @param string|array $value
1170 * @param array $field
1171 * @param int|null $entityId
1175 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1177 if (self
::isSerialized($field) && !is_array($value)) {
1178 $value = CRM_Utils_Array
::explodePadded($value);
1181 if ($field['html_type'] == 'CheckBox') {
1182 CRM_Utils_Array
::formatArrayKeys($value);
1185 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1187 switch ($field['html_type']) {
1190 case 'Autocomplete-Select':
1192 case 'Select Country':
1193 case 'Select State/Province':
1195 case 'AdvMulti-Select':
1196 case 'Multi-Select':
1197 case 'Multi-Select State/Province':
1198 case 'Multi-Select Country':
1199 if ($field['data_type'] == 'ContactReference' && $value) {
1200 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1202 elseif (is_array($value)) {
1204 foreach ($value as $key => $val) {
1205 $v[] = CRM_Utils_Array
::value($val, $field['options']);
1207 $display = implode(', ', $v);
1210 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1215 $customFormat = NULL;
1217 // FIXME: Are there any legitimate reasons why $value would be an array?
1218 // Or should we throw an exception here if it is?
1219 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1221 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1222 $format = CRM_Utils_Array
::value('date_format', $field);
1225 if (array_key_exists($format, $actualPHPFormats)) {
1226 $customTimeFormat = (array) $actualPHPFormats[$format];
1227 switch (CRM_Utils_Array
::value('time_format', $field)) {
1229 $customTimeFormat[] = 'g:iA';
1233 $customTimeFormat[] = 'G:i';
1237 //If time is not selected remove time from value.
1238 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1240 $customFormat = implode(" ", $customTimeFormat);
1243 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1247 // In the context of displaying a profile, show file/image
1250 if (CRM_Utils_Rule
::positiveInteger($value)) {
1254 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1256 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1258 $display = $url['file_url'];
1262 // In other contexts show a paperclip icon
1263 if (CRM_Utils_Rule
::integer($value)) {
1264 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1265 $display = $icons[$value];
1268 //CRM-18396, if filename is passed instead
1276 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1280 $display = nl2br($display);
1284 if ($field['data_type'] == 'Money' && isset($value)) {
1285 //$value can also be an array(while using IN operator from search builder or api).
1286 foreach ((array) $value as $val) {
1287 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1289 $display = implode(', ', $disp);
1297 * Set default values for custom data used in profile.
1299 * @param int $customFieldId
1301 * @param string $elementName
1302 * Custom field name.
1303 * @param array $defaults
1304 * Associated array of fields.
1305 * @param int $contactId
1309 * @param mixed $value
1310 * If passed - dont fetch value from db,.
1311 * just format the given value
1313 public static function setProfileDefaults(
1321 //get the type of custom field
1322 $customField = new CRM_Core_BAO_CustomField();
1323 $customField->id
= $customFieldId;
1324 $customField->find(TRUE);
1327 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1328 $value = $customField->default_value
;
1332 if (!isset($value)) {
1333 $info = self
::getTableColumnGroup($customFieldId);
1334 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1335 $result = CRM_Core_DAO
::executeQuery($query);
1336 if ($result->fetch()) {
1337 $value = $result->value
;
1341 if ($customField->data_type
== 'Country') {
1343 $config = CRM_Core_Config
::singleton();
1344 if ($config->defaultContactCountry
) {
1345 $value = $config->defaultContactCountry();
1351 //set defaults if mode is registration
1352 if (!trim($value) &&
1354 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1356 $value = $customField->default_value
;
1359 if ($customField->data_type
== 'Money' && isset($value)) {
1360 $value = number_format($value, 2);
1362 switch ($customField->html_type
) {
1364 case 'AdvMulti-Select':
1365 case 'Multi-Select':
1366 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1367 $defaults[$elementName] = array();
1368 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1369 substr($value, 1, -1)
1371 foreach ($customOption as $val) {
1372 if (in_array($val['value'], $checkedValue)) {
1373 if ($customField->html_type
== 'CheckBox') {
1374 $defaults[$elementName][$val['value']] = 1;
1376 elseif ($customField->html_type
== 'Multi-Select' ||
1377 $customField->html_type
== 'AdvMulti-Select'
1379 $defaults[$elementName][$val['value']] = $val['value'];
1385 case 'Autocomplete-Select':
1386 if ($customField->data_type
== 'ContactReference') {
1387 if (is_numeric($value)) {
1388 $defaults[$elementName . '_id'] = $value;
1389 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1393 $defaults[$elementName] = $value;
1398 $defaults[$elementName] = $value;
1405 * @param int $contactID
1407 * @param int $fileID
1408 * @param bool $absolute
1410 * @param string $multiRecordWhereClause
1414 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1417 $params = array('id' => $cfID);
1418 $defaults = array();
1419 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1420 $columnName = $defaults['column_name'];
1422 //table name of custom data
1423 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1424 $defaults['custom_group_id'],
1428 //query to fetch id from civicrm_file
1429 if ($multiRecordWhereClause) {
1430 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1433 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1435 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1440 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1445 $result['file_id'] = $fileID;
1447 if ($fileType == 'image/jpeg' ||
1448 $fileType == 'image/pjpeg' ||
1449 $fileType == 'image/gif' ||
1450 $fileType == 'image/x-png' ||
1451 $fileType == 'image/png'
1453 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1458 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1459 $url = CRM_Utils_System
::url('civicrm/file',
1460 "reset=1&id=$fileID&eid=$contactID",
1461 $absolute, NULL, TRUE, TRUE
1463 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1465 // 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'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
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 // If we are already passing the file id as a value then retrieve and set the file data
1665 if (CRM_Utils_Rule
::integer($value)) {
1666 $fileDAO = new CRM_Core_DAO_File();
1667 $fileDAO->id
= $value;
1668 $fileDAO->find(TRUE);
1671 $fName = $fileDAO->uri
;
1672 $mimeType = $fileDAO->mime_type
;
1676 $fName = $value['name'];
1677 $mimeType = $value['type'];
1680 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1682 // rename this file to go into the secure directory only if
1683 // user has uploaded new file not existing verfied on the basis of $fileID
1684 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1685 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1688 if ($customValueId && empty($fileID)) {
1693 $params = array(1 => array($customValueId, 'Integer'));
1694 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1697 $fileDAO = new CRM_Core_DAO_File();
1700 $fileDAO->id
= $fileId;
1703 $fileDAO->uri
= $filename;
1704 $fileDAO->mime_type
= $mimeType;
1705 $fileDAO->upload_date
= date('YmdHis');
1707 $fileId = $fileDAO->id
;
1711 if (!is_array($customFormatted)) {
1712 $customFormatted = array();
1715 if (!array_key_exists($customFieldId, $customFormatted)) {
1716 $customFormatted[$customFieldId] = array();
1720 if ($customValueId) {
1721 $index = $customValueId;
1724 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1725 $customFormatted[$customFieldId][$index] = array();
1727 $customFormatted[$customFieldId][$index] = array(
1728 'id' => $customValueId > 0 ?
$customValueId : NULL,
1730 'type' => $customFields[$customFieldId]['data_type'],
1731 'custom_field_id' => $customFieldId,
1732 'custom_group_id' => $groupID,
1733 'table_name' => $tableName,
1734 'column_name' => $columnName,
1735 'file_id' => $fileId,
1736 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1739 //we need to sort so that custom fields are created in the order of entry
1740 krsort($customFormatted[$customFieldId]);
1741 return $customFormatted;
1745 * Get default custom table schema.
1747 * @param array $params
1751 public static function defaultCustomTableSchema($params) {
1752 // add the id and extends_id
1754 'name' => $params['name'],
1755 'is_multiple' => $params['is_multiple'],
1756 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1760 'type' => 'int unsigned',
1763 'attributes' => 'AUTO_INCREMENT',
1764 'comment' => 'Default MySQL primary key',
1767 'name' => 'entity_id',
1768 'type' => 'int unsigned',
1770 'comment' => 'Table that this extends',
1771 'fk_table_name' => $params['extends_name'],
1772 'fk_field_name' => 'id',
1773 'fk_attributes' => 'ON DELETE CASCADE',
1778 if (!$params['is_multiple']) {
1779 $table['indexes'] = array(
1782 'field_name_1' => 'entity_id',
1790 * Create custom field.
1792 * @param CRM_Core_DAO_CustomField $field
1793 * @param string $operation
1794 * @param bool $indexExist
1795 * @param bool $triggerRebuild
1797 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1798 $tableName = CRM_Core_DAO
::getFieldValue(
1799 'CRM_Core_DAO_CustomGroup',
1800 $field->custom_group_id
,
1805 'table_name' => $tableName,
1806 'operation' => $operation,
1807 'name' => $field->column_name
,
1808 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1812 'required' => $field->is_required
,
1813 'searchable' => $field->is_searchable
,
1816 if ($operation == 'delete') {
1817 $fkName = "{$tableName}_{$field->column_name}";
1818 if (strlen($fkName) >= 48) {
1819 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1821 $params['fkName'] = $fkName;
1823 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1824 $params['fk_table_name'] = 'civicrm_country';
1825 $params['fk_field_name'] = 'id';
1826 $params['fk_attributes'] = 'ON DELETE SET NULL';
1828 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1829 $params['type'] = 'varchar(255)';
1831 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1832 $params['fk_table_name'] = 'civicrm_state_province';
1833 $params['fk_field_name'] = 'id';
1834 $params['fk_attributes'] = 'ON DELETE SET NULL';
1836 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1837 $params['type'] = 'varchar(255)';
1839 elseif ($field->data_type
== 'File') {
1840 $params['fk_table_name'] = 'civicrm_file';
1841 $params['fk_field_name'] = 'id';
1842 $params['fk_attributes'] = 'ON DELETE SET NULL';
1844 elseif ($field->data_type
== 'ContactReference') {
1845 $params['fk_table_name'] = 'civicrm_contact';
1846 $params['fk_field_name'] = 'id';
1847 $params['fk_attributes'] = 'ON DELETE SET NULL';
1849 if (isset($field->default_value
)) {
1850 $params['default'] = "'{$field->default_value}'";
1853 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1857 * Determine whether it would be safe to move a field.
1859 * @param int $fieldID
1860 * FK to civicrm_custom_field.
1861 * @param int $newGroupID
1862 * FK to civicrm_custom_group.
1865 * array(string) or TRUE
1867 public static function _moveFieldValidate($fieldID, $newGroupID) {
1870 $field = new CRM_Core_DAO_CustomField();
1871 $field->id
= $fieldID;
1872 if (!$field->find(TRUE)) {
1873 $errors['fieldID'] = 'Invalid ID for custom field';
1877 $oldGroup = new CRM_Core_DAO_CustomGroup();
1878 $oldGroup->id
= $field->custom_group_id
;
1879 if (!$oldGroup->find(TRUE)) {
1880 $errors['fieldID'] = 'Invalid ID for old custom group';
1884 $newGroup = new CRM_Core_DAO_CustomGroup();
1885 $newGroup->id
= $newGroupID;
1886 if (!$newGroup->find(TRUE)) {
1887 $errors['newGroupID'] = 'Invalid ID for new custom group';
1893 FROM civicrm_custom_field a
1894 INNER JOIN civicrm_custom_field b
1896 AND a.label = b.label
1897 AND b.custom_group_id = %2
1900 1 => array($field->id
, 'Integer'),
1901 2 => array($newGroup->id
, 'Integer'),
1903 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1905 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1908 $tableName = $oldGroup->table_name
;
1909 $columnName = $field->column_name
;
1914 WHERE $columnName is not null
1916 $count = CRM_Core_DAO
::singleValueQuery($query,
1917 CRM_Core_DAO
::$_nullArray
1922 FROM civicrm_custom_group
1923 WHERE id IN ( %1, %2 )
1926 1 => array($oldGroup->id
, 'Integer'),
1927 2 => array($newGroup->id
, 'Integer'),
1930 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1932 while ($dao->fetch()) {
1933 $extends[] = $dao->extends;
1935 if ($extends[0] != $extends[1]) {
1936 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1940 return empty($errors) ?
TRUE : $errors;
1944 * Move a custom data field from one group (table) to another.
1946 * @param int $fieldID
1947 * FK to civicrm_custom_field.
1948 * @param int $newGroupID
1949 * FK to civicrm_custom_group.
1951 public static function moveField($fieldID, $newGroupID) {
1952 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1953 if (TRUE !== $validation) {
1954 CRM_Core_Error
::fatal(implode(' ', $validation));
1956 $field = new CRM_Core_DAO_CustomField();
1957 $field->id
= $fieldID;
1960 $newGroup = new CRM_Core_DAO_CustomGroup();
1961 $newGroup->id
= $newGroupID;
1962 $newGroup->find(TRUE);
1964 $oldGroup = new CRM_Core_DAO_CustomGroup();
1965 $oldGroup->id
= $field->custom_group_id
;
1966 $oldGroup->find(TRUE);
1969 $add->custom_group_id
= $newGroup->id
;
1970 self
::createField($add, 'add');
1972 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1973 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1974 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1976 CRM_Core_DAO
::executeQuery($sql);
1979 $del->custom_group_id
= $oldGroup->id
;
1980 self
::createField($del, 'delete');
1984 CRM_Utils_System
::flushCache();
1988 * Get the database table name and column name for a custom field.
1990 * @param int $fieldID
1991 * The fieldID of the custom field.
1992 * @param bool $force
1993 * Force the sql to be run again (primarily used for tests).
1996 * fatal is fieldID does not exists, else array of tableName, columnName
1998 public static function getTableColumnGroup($fieldID, $force = FALSE) {
1999 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2000 $cache = CRM_Utils_Cache
::singleton();
2001 $fieldValues = $cache->get($cacheKey);
2002 if (empty($fieldValues) ||
$force) {
2004 SELECT cg.table_name, cf.column_name, cg.id
2005 FROM civicrm_custom_group cg,
2006 civicrm_custom_field cf
2007 WHERE cf.custom_group_id = cg.id
2009 $params = array(1 => array($fieldID, 'Integer'));
2010 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2012 if (!$dao->fetch()) {
2013 CRM_Core_Error
::fatal();
2016 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2017 $cache->set($cacheKey, $fieldValues);
2019 return $fieldValues;
2023 * Get custom option groups.
2025 * @param array $includeFieldIds
2026 * Ids of custom fields for which option groups must be included.
2028 * Currently this is required in the cases where option groups are to be included
2029 * for inactive fields : CRM-5369
2033 public static function customOptionGroup($includeFieldIds = NULL) {
2034 static $customOptionGroup = NULL;
2036 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2037 if ($cacheKey == 'force') {
2038 $customOptionGroup[$cacheKey] = NULL;
2041 if (empty($customOptionGroup[$cacheKey])) {
2042 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2044 //support for single as well as array format.
2045 if (!empty($includeFieldIds)) {
2046 if (is_array($includeFieldIds)) {
2047 $includeFieldIds = implode(',', $includeFieldIds);
2049 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2053 SELECT g.id, g.title
2054 FROM civicrm_option_group g
2055 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2056 WHERE {$whereClause}";
2058 $dao = CRM_Core_DAO
::executeQuery($query);
2059 while ($dao->fetch()) {
2060 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2064 return $customOptionGroup[$cacheKey];
2068 * Fix orphan groups.
2070 * @param int $customFieldId
2072 * @param int $optionGroupId
2075 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2076 // check if option group belongs to any custom Field else delete
2077 // get the current option group
2078 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2082 // get the updated option group
2083 // if both are same return
2084 if ($currentOptionGroupId == $optionGroupId) {
2088 // check if option group is related to any other field
2089 self
::checkOptionGroup($currentOptionGroupId);
2093 * Check if option group is related to more than one custom field.
2095 * @param int $optionGroupId
2098 public static function checkOptionGroup($optionGroupId) {
2101 FROM civicrm_custom_field
2102 WHERE option_group_id = {$optionGroupId}";
2104 $count = CRM_Core_DAO
::singleValueQuery($query);
2107 //delete the option group
2108 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2113 * Get option group default.
2115 * @param int $optionGroupId
2116 * @param string $htmlType
2118 * @return null|string
2120 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2122 SELECT default_value, html_type
2123 FROM civicrm_custom_field
2124 WHERE option_group_id = {$optionGroupId}
2125 AND default_value IS NOT NULL
2126 ORDER BY html_type";
2128 $dao = CRM_Core_DAO
::executeQuery($query);
2129 $defaultValue = NULL;
2130 $defaultHTMLType = NULL;
2131 while ($dao->fetch()) {
2132 if ($dao->html_type
== $htmlType) {
2133 return $dao->default_value
;
2135 if ($defaultValue == NULL) {
2136 $defaultValue = $dao->default_value
;
2137 $defaultHTMLType = $dao->html_type
;
2141 // some conversions are needed if either the old or new has a html type which has potential
2142 // multiple default values.
2143 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2144 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2146 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2148 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2149 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2151 $defaultValue = substr($defaultValue, 1, -1);
2152 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2153 substr($defaultValue, 1, -1)
2155 $defaultValue = $values[0];
2158 return $defaultValue;
2162 * Post process function.
2164 * @param array $params
2165 * @param int $entityID
2166 * @param string $customFieldExtends
2167 * @param bool $inline
2168 * @param bool $checkPermissions
2172 public static function postProcess(
2175 $customFieldExtends,
2177 $checkPermissions = TRUE
2179 $customData = array();
2181 foreach ($params as $key => $value) {
2182 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2184 // for autocomplete transfer hidden value instead of label
2185 if ($params[$key] && isset($params[$key . '_id'])) {
2186 $value = $params[$key . '_id'];
2189 // we need to append time with date
2190 if ($params[$key] && isset($params[$key . '_time'])) {
2191 $value .= ' ' . $params[$key . '_time'];
2194 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2197 $customFieldExtends,
2198 $customFieldInfo[1],
2213 * Get custom field ID.
2215 * @param string $fieldLabel
2216 * @param null $groupTitle
2220 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2221 $params = array(1 => array($fieldLabel, 'String'));
2223 $params[2] = array($groupTitle, 'String');
2226 FROM civicrm_custom_field f
2227 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2228 WHERE ( f.label = %1 OR f.name = %1 )
2229 AND ( g.title = %2 OR g.name = %2 )
2235 FROM civicrm_custom_field f
2236 WHERE ( f.label = %1 OR f.name = %1 )
2240 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2241 if ($dao->fetch() &&
2252 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2258 public static function getNameFromID($ids) {
2259 if (is_array($ids)) {
2260 $ids = implode(',', $ids);
2263 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2264 FROM civicrm_custom_field f
2265 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2266 WHERE f.id IN ($ids)";
2268 $dao = CRM_Core_DAO
::executeQuery($sql);
2270 while ($dao->fetch()) {
2271 $result[$dao->id
] = array(
2272 'field_name' => $dao->field_name
,
2273 'field_label' => $dao->field_label
,
2274 'group_name' => $dao->group_name
,
2275 'group_title' => $dao->group_title
,
2282 * Validate custom data.
2284 * @param array $params
2285 * Custom data submitted.
2286 * ie array( 'custom_1' => 'validate me' );
2289 * validation errors.
2291 public static function validateCustomData($params) {
2293 if (!is_array($params) ||
empty($params)) {
2297 //pick up profile fields.
2298 $profileFields = array();
2299 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2301 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2303 CRM_Core_Action
::VIEW
2307 //lets start w/ params.
2308 foreach ($params as $key => $value) {
2309 $customFieldID = self
::getKeyID($key);
2310 if (!$customFieldID) {
2314 //load the structural info for given field.
2315 $field = new CRM_Core_DAO_CustomField();
2316 $field->id
= $customFieldID;
2317 if (!$field->find(TRUE)) {
2320 $dataType = $field->data_type
;
2322 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2323 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2324 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2326 $fieldTitle = $field->label
;
2329 //no need to validate.
2330 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2334 //lets validate first for required field.
2335 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2336 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2340 //now time to take care of custom field form rules.
2341 $ruleName = $errorMsg = NULL;
2342 switch ($dataType) {
2344 $ruleName = 'integer';
2345 $errorMsg = ts('%1 must be an integer (whole number).',
2346 array(1 => $fieldTitle)
2351 $ruleName = 'money';
2352 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2353 array(1 => $fieldTitle)
2358 $ruleName = 'numeric';
2359 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2360 array(1 => $fieldTitle)
2365 $ruleName = 'wikiURL';
2366 $errorMsg = ts('%1 must be valid Website.',
2367 array(1 => $fieldTitle)
2372 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2374 $funName = "CRM_Utils_Rule::{$ruleName}";
2375 if (is_callable($funName)) {
2376 $valid = call_user_func($funName, $value);
2379 $errors[$key] = $errorMsg;
2388 * Is this field a multi record field.
2390 * @param int $customId
2394 public static function isMultiRecordField($customId) {
2395 $isMultipleWithGid = FALSE;
2396 if (!is_numeric($customId)) {
2397 $customId = self
::getKeyID($customId);
2399 if (is_numeric($customId)) {
2400 $sql = "SELECT cg.id cgId
2401 FROM civicrm_custom_group cg
2402 INNER JOIN civicrm_custom_field cf
2403 ON cg.id = cf.custom_group_id
2404 WHERE cf.id = %1 AND cg.is_multiple = 1";
2405 $params[1] = array($customId, 'Integer');
2406 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2407 if ($dao->fetch()) {
2409 $isMultipleWithGid = $dao->cgId
;
2414 return $isMultipleWithGid;
2418 * Does this field store a serialized string?
2420 * @param array $field
2424 public static function isSerialized($field) {
2425 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2426 $field = (array) $field;
2427 // 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.
2428 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2432 * Get api entity for this field
2436 public function getEntity() {
2437 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2438 return in_array($entity, array('Individual', 'Household', 'Organization')) ?
'Contact' : $entity;
2442 * Set pseudoconstant properties for field metadata.
2444 * @param array $field
2445 * @param string|null $optionGroupName
2447 private static function getOptionsForField(&$field, $optionGroupName) {
2448 if ($optionGroupName) {
2449 $field['pseudoconstant'] = array(
2450 'optionGroupName' => $optionGroupName,
2451 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2454 elseif ($field['data_type'] == 'Boolean') {
2455 $field['pseudoconstant'] = array(
2456 'callback' => 'CRM_Core_SelectValues::boolean',
2459 elseif ($field['data_type'] == 'Country') {
2460 $field['pseudoconstant'] = array(
2461 'table' => 'civicrm_country',
2462 'keyColumn' => 'id',
2463 'labelColumn' => 'name',
2464 'nameColumn' => 'iso_code',
2467 elseif ($field['data_type'] == 'StateProvince') {
2468 $field['pseudoconstant'] = array(
2469 'table' => 'civicrm_state_province',
2470 'keyColumn' => 'id',
2471 'labelColumn' => 'name',