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 * Store and return an array of all active custom fields.
368 * @param string $customDataType
369 * Type of Custom Data; empty is a synonym for "all contact data types".
370 * @param bool $showAll
371 * If true returns all fields (includes disabled fields).
372 * @param bool $inline
373 * If true returns all inline fields (includes disabled fields).
374 * @param int $customDataSubType
375 * Custom Data sub type value.
376 * @param int $customDataSubName
377 * Custom Data sub name value.
378 * @param bool $onlyParent
379 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
380 * @param bool $onlySubType
381 * Return only custom data for subtype.
382 * @param bool $checkPermission
383 * If false, do not include permissioning clause.
386 * an array of active custom fields.
388 public static function &getFields(
389 $customDataType = 'Individual',
392 $customDataSubType = NULL,
393 $customDataSubName = NULL,
395 $onlySubType = FALSE,
396 $checkPermission = TRUE
398 if (empty($customDataType)) {
399 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
401 if ($customDataType && !is_array($customDataType)) {
403 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
404 // This is the case when getFieldsForImport() requires fields
405 // limited strictly to a subtype.
406 $customDataSubType = $customDataType;
407 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
411 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
412 // this makes the method flexible to support retrieving fields
413 // for multiple extends value.
414 $customDataType = array($customDataType);
418 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
420 if (is_array($customDataType)) {
421 $cacheKey = implode('_', $customDataType);
424 $cacheKey = $customDataType;
427 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
428 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
429 $cacheKey .= $showAll ?
'_1' : '_0';
430 $cacheKey .= $inline ?
'_1_' : '_0_';
431 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
432 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
433 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
435 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
437 // also get the permission stuff here
438 if ($checkPermission) {
439 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
444 $permissionClause = '(1)';
447 // lets md5 permission clause and take first 8 characters
448 $cacheKey .= substr(md5($permissionClause), 0, 8);
450 if (strlen($cacheKey) > 40) {
451 $cacheKey = md5($cacheKey);
454 if (!self
::$_importFields ||
455 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
457 if (!self
::$_importFields) {
458 self
::$_importFields = array();
461 // check if we can retrieve from database cache
462 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
464 if ($fields === NULL) {
465 $cfTable = self
::getTableName();
468 if (is_array($customDataType)) {
470 foreach ($customDataType as $dataType) {
471 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
472 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
473 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
476 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
478 $value = $value ?
$value . ", {$val}" : $val;
482 $extends = "AND $cgTable.extends IN ( $value ) ";
486 if (!empty($customDataType) && empty($extends)) {
487 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
488 self
::$_importFields[$cacheKey] = array();
489 return self
::$_importFields[$cacheKey];
493 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
496 $query = "SELECT $cfTable.id, $cfTable.label,
500 $cfTable.default_value,
501 $cfTable.options_per_line, $cfTable.text_length,
502 $cfTable.custom_group_id,
503 $cfTable.is_required,
504 $cgTable.extends, $cfTable.is_search_range,
505 $cgTable.extends_entity_column_value,
506 $cgTable.extends_entity_column_id,
508 $cfTable.option_group_id,
509 $cfTable.date_format,
510 $cfTable.time_format,
511 $cgTable.is_multiple,
512 og.name as option_group_name
515 ON $cfTable.custom_group_id = $cgTable.id
516 LEFT JOIN civicrm_option_group og
517 ON $cfTable.option_group_id = og.id
521 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
525 $query .= " AND $cgTable.style = 'Inline' ";
528 //get the custom fields for specific type in
529 //combination with fields those support any type.
530 if (!empty($customDataSubType)) {
531 $subtypeClause = array();
532 foreach ($customDataSubType as $subtype) {
533 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
534 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
537 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
539 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
542 if ($customDataSubName) {
543 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
546 // also get the permission stuff here
547 if ($checkPermission) {
548 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
553 $permissionClause = '(1)';
556 $query .= " $extends AND $permissionClause
557 ORDER BY $cgTable.weight, $cgTable.title,
558 $cfTable.weight, $cfTable.label";
560 $dao = CRM_Core_DAO
::executeQuery($query);
563 while (($dao->fetch()) != NULL) {
564 $fields[$dao->id
]['label'] = $dao->label
;
565 $fields[$dao->id
]['groupTitle'] = $dao->title
;
566 $fields[$dao->id
]['data_type'] = $dao->data_type
;
567 $fields[$dao->id
]['html_type'] = $dao->html_type
;
568 $fields[$dao->id
]['default_value'] = $dao->default_value
;
569 $fields[$dao->id
]['text_length'] = $dao->text_length
;
570 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
571 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
572 $fields[$dao->id
]['extends'] = $dao->extends;
573 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
574 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
575 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
576 $fields[$dao->id
]['is_view'] = $dao->is_view
;
577 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
578 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
579 $fields[$dao->id
]['date_format'] = $dao->date_format
;
580 $fields[$dao->id
]['time_format'] = $dao->time_format
;
581 $fields[$dao->id
]['is_required'] = $dao->is_required
;
582 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
585 CRM_Core_BAO_Cache
::setItem($fields,
587 "custom importableFields $cacheKey"
590 self
::$_importFields[$cacheKey] = $fields;
593 return self
::$_importFields[$cacheKey];
597 * Return the field ids and names (with groups) for import purpose.
599 * @param int|string $contactType Contact type
600 * @param bool $showAll
601 * If true returns all fields (includes disabled fields).
602 * @param bool $onlyParent
603 * Return fields ONLY related to basic types.
604 * @param bool $search
605 * When called from search and multiple records need to be returned.
606 * @param bool $checkPermission
607 * If false, do not include permissioning clause.
609 * @param bool $withMultiple
613 public static function getFieldsForImport(
614 $contactType = 'Individual',
618 $checkPermission = TRUE,
619 $withMultiple = FALSE
621 // Note: there are situations when we want getFieldsForImport() return fields related
622 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
623 $fields = &self
::getFields($contactType,
633 $importableFields = array();
634 foreach ($fields as $id => $values) {
635 // for now we should not allow multiple fields in profile / export etc, hence unsetting
637 (!empty($values['is_multiple']) && !$withMultiple)
642 /* generate the key for the fields array */
646 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
647 $importableFields[$key] = array(
649 'title' => CRM_Utils_Array
::value('label', $values),
650 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
652 'custom_field_id' => $id,
653 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
654 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
655 'data_type' => CRM_Utils_Array
::value('data_type', $values),
656 'html_type' => CRM_Utils_Array
::value('html_type', $values),
657 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
660 // CRM-6681, pass date and time format when html_type = Select Date
661 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
662 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
663 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
667 return $importableFields;
671 * Get the field id from an import key.
681 public static function getKeyID($key, $all = FALSE) {
683 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
690 CRM_Utils_Array
::value(2, $match),
694 return $all ?
array(NULL, NULL) : NULL;
698 * Use the cache to get all values of a specific custom field.
700 * @param int $fieldID
701 * The custom field ID.
703 * @return CRM_Core_DAO_CustomField
706 public static function getFieldObject($fieldID) {
707 $field = new CRM_Core_DAO_CustomField();
709 // check if we can get the field values from the system cache
710 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
711 $cache = CRM_Utils_Cache
::singleton();
712 $fieldValues = $cache->get($cacheKey);
713 if (empty($fieldValues)) {
714 $field->id
= $fieldID;
715 if (!$field->find(TRUE)) {
716 CRM_Core_Error
::fatal();
719 $fieldValues = array();
720 CRM_Core_DAO
::storeValues($field, $fieldValues);
722 $cache->set($cacheKey, $fieldValues);
725 $field->copyValues($fieldValues);
732 * This function for building custom fields.
734 * @param CRM_Core_Form $qf
735 * Form object (reference).
736 * @param string $elementName
737 * Name of the custom field.
738 * @param int $fieldId
739 * @param bool $inactiveNeeded
741 * @param bool $useRequired
742 * True if required else false.
743 * @param bool $search
744 * True if used for search else false.
745 * @param string $label
746 * Label for custom field.
748 public static function addQuickFormElement(
752 $inactiveNeeded = FALSE,
757 $field = self
::getFieldObject($fieldId);
758 $widget = $field->html_type
;
760 // Custom field HTML should indicate group+field name
761 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
762 $dataCrmCustomVal = $groupName . ':' . $field->name
;
763 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
764 $field->attributes
.= $dataCrmCustomAttr;
766 // Fixed for Issue CRM-2183
767 if ($widget == 'TextArea' && $search) {
771 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
773 // FIXME: Why are select state/country separate widget types?
774 $isSelect = (in_array($widget, array(
777 'Select State/Province',
778 'Multi-Select State/Province',
780 'Multi-Select Country',
787 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array(
788 'field' => "custom_$fieldId",
789 'context' => $search ?
'search' : 'create',
792 // Consolidate widget types to simplify the below switch statement
793 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
796 $selectAttributes = array(
797 'data-crm-custom' => $dataCrmCustomVal,
798 'class' => 'crm-select2',
800 // Search field is always multi-select
801 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
802 $selectAttributes['class'] .= ' huge';
803 $selectAttributes['multiple'] = 'multiple';
804 $selectAttributes['placeholder'] = $placeholder;
806 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
807 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
808 $selectAttributes +
= array(
809 'data-api-entity' => 'contact',
810 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
811 'data-api-field' => 'custom_' . $field->id
,
812 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
817 if (!isset($label)) {
818 $label = $field->label
;
821 // at some point in time we might want to split the below into small functions
826 if ($field->is_search_range
&& $search) {
827 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
828 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
831 $element = &$qf->add('text', $elementName, $label,
833 $useRequired && !$search
839 $attributes = $dataCrmCustomAttr;
840 if ($field->note_rows
) {
841 $attributes .= 'rows=' . $field->note_rows
;
844 $attributes .= 'rows=4';
846 if ($field->note_columns
) {
847 $attributes .= ' cols=' . $field->note_columns
;
850 $attributes .= ' cols=60';
852 if ($field->text_length
) {
853 $attributes .= ' maxlength=' . $field->text_length
;
855 $element = &$qf->add('textarea',
859 $useRequired && !$search
864 if ($field->is_search_range
&& $search) {
865 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
867 'format' => $field->date_format
,
868 'timeFormat' => $field->time_format
,
869 'startOffset' => $field->start_date_years
,
870 'endOffset' => $field->end_date_years
,
871 'data-crm-custom' => $dataCrmCustomVal,
875 $qf->addDate($elementName . '_to', ts('To'), FALSE,
877 'format' => $field->date_format
,
878 'timeFormat' => $field->time_format
,
879 'startOffset' => $field->start_date_years
,
880 'endOffset' => $field->end_date_years
,
881 'data-crm-custom' => $dataCrmCustomVal,
886 $required = $useRequired && !$search;
888 $qf->addDate($elementName, $label, $required, array(
889 'format' => $field->date_format
,
890 'timeFormat' => $field->time_format
,
891 'startOffset' => $field->start_date_years
,
892 'endOffset' => $field->end_date_years
,
893 'data-crm-custom' => $dataCrmCustomVal,
900 foreach ($options as $v => $l) {
901 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
903 $group = $qf->addGroup($choice, $elementName, $label);
904 if ($useRequired && !$search) {
905 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
908 $group->setAttribute('allowClear', TRUE);
912 // For all select elements
914 if (empty($selectAttributes['multiple'])) {
915 $options = array('' => $placeholder) +
$options;
917 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
919 // Add and/or option for fields that store multiple values
920 if ($search && self
::isSerialized($field)) {
923 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
924 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
926 $qf->addGroup($operators, $elementName . '_operator');
927 $qf->setDefaults(array($elementName . '_operator' => 'or'));
931 case 'AdvMulti-Select':
932 $include =& $qf->addElement(
939 'class' => 'advmultiselect',
940 'data-crm-custom' => $dataCrmCustomVal,
944 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
945 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
947 if ($useRequired && !$search) {
948 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
954 foreach ($options as $v => $l) {
955 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
957 $qf->addGroup($check, $elementName, $label);
958 if ($useRequired && !$search) {
959 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
964 // we should not build upload file in search mode
969 strtolower($field->html_type
),
973 $useRequired && !$search
975 $qf->addUploadElement($elementName);
978 case 'RichTextEditor':
980 'rows' => $field->note_rows
,
981 'cols' => $field->note_columns
,
982 'data-crm-custom' => $dataCrmCustomVal,
984 if ($field->text_length
) {
985 $attributes['maxlength'] = $field->text_length
;
987 $qf->add('wysiwyg', $elementName, $label, $attributes, $search);
990 case 'Autocomplete-Select':
991 static $customUrls = array();
992 // Fixme: why is this a string in the first place??
993 $attributes = array();
994 if ($field->attributes
) {
995 foreach (explode(' ', $field->attributes
) as $at) {
996 if (strpos($at, '=')) {
997 list($k, $v) = explode('=', $at);
998 $attributes[$k] = trim($v, ' "');
1002 if ($field->data_type
== 'ContactReference') {
1003 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1004 $attributes['data-api-entity'] = 'contact';
1005 $qf->add('text', $elementName, $label, $attributes,
1006 $useRequired && !$search
1009 $urlParams = "context=customfield&id={$field->id}";
1011 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1018 // FIXME: This won't work with customFieldOptions hook
1019 $attributes +
= array(
1020 'entity' => 'option_value',
1021 'placeholder' => $placeholder,
1022 'multiple' => $search,
1024 'params' => array('option_group_id' => $field->option_group_id
),
1027 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1030 $qf->assign('customUrls', $customUrls);
1034 switch ($field->data_type
) {
1036 // integers will have numeric rule applied to them.
1037 if ($field->is_search_range
&& $search) {
1038 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1039 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1041 elseif ($widget == 'Text') {
1042 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1047 if ($field->is_search_range
&& $search) {
1048 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1049 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1051 elseif ($widget == 'Text') {
1052 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1057 if ($field->is_search_range
&& $search) {
1058 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1059 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1061 elseif ($widget == 'Text') {
1062 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1067 $element->setAttribute('class', "url");
1068 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1071 if ($field->is_view
&& !$search) {
1072 $qf->freeze($elementName);
1077 * Delete the Custom Field.
1079 * @param object $field
1082 public static function deleteField($field) {
1083 CRM_Utils_System
::flushCache();
1085 // first delete the custom option group and values associated with this field
1086 if ($field->option_group_id
) {
1087 //check if option group is related to any other field, if
1088 //not delete the option group and related option values
1089 self
::checkOptionGroup($field->option_group_id
);
1092 // next drop the column from the custom value table
1093 self
::createField($field, 'delete');
1096 CRM_Core_BAO_UFField
::delUFField($field->id
);
1097 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1101 * Find the display value for this field.
1103 * @param mixed $value
1104 * The custom field value.
1106 * The custom field id.
1107 * @param array $options
1108 * The assoc array of option name/value pairs.
1110 * @param int $contactID
1111 * @param int $fieldID
1116 public static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1117 $option = &$options[$id];
1118 $attributes = &$option['attributes'];
1119 $html_type = $attributes['html_type'];
1120 $data_type = $attributes['data_type'];
1122 return self
::getDisplayValueCommon($value,
1132 * Get display value.
1134 * @param string $value
1135 * @param array $option
1136 * @param string $html_type
1137 * @param string $data_type
1138 * @param int $contactID
1139 * @param int $fieldID
1141 * @return array|mixed|null|string
1143 public static function getDisplayValueCommon(
1154 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1155 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1156 $html_type == 'Select' ||
1157 $html_type == 'CheckBox' ||
1158 $html_type == 'AdvMulti-Select' ||
1159 $html_type == 'Multi-Select'
1162 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1165 switch ($html_type) {
1167 if ($data_type == 'Boolean') {
1168 $option = array('No', 'Yes');
1170 if (is_array($value)) {
1172 foreach ($value as $data) {
1173 $display .= $display ?
', ' . $option[$data] : $option[$data];
1177 $display = CRM_Utils_Array
::value($value, $option);
1181 case 'Autocomplete-Select':
1182 if ($data_type == 'ContactReference' &&
1185 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1187 elseif (is_array($value)) {
1189 foreach ($value as $data) {
1190 $display .= $display ?
', ' . $option[$data] : $option[$data];
1194 $display = CRM_Utils_Array
::value($value, $option);
1199 if (is_array($value)) {
1201 foreach ($value as $data) {
1202 $display .= $display ?
', ' . $option[$data] : $option[$data];
1206 $display = CRM_Utils_Array
::value($value, $option);
1211 case 'AdvMulti-Select':
1212 case 'Multi-Select':
1213 if (is_array($value)) {
1214 $checkedData = $value;
1217 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1218 substr($value, 1, -1)
1220 if ($html_type == 'CheckBox') {
1222 foreach ($checkedData as $v) {
1223 $v = str_replace(CRM_Core_DAO
::VALUE_SEPARATOR
, '', $v);
1226 $checkedData = $newData;
1231 foreach ($checkedData as $key => $val) {
1232 $v[] = CRM_Utils_Array
::value($val, $option);
1235 $display = implode(', ', $v);
1240 if (is_array($value)) {
1241 foreach ($value as $key => $val) {
1242 $display[$key] = CRM_Utils_Date
::customFormat($val);
1246 // remove time element display if time is not set
1247 if (empty($option['attributes']['time_format'])) {
1248 $value = substr($value, 0, 10);
1250 $display = CRM_Utils_Date
::customFormat($value);
1254 case 'Select State/Province':
1255 case 'Multi-Select State/Province':
1256 case 'Select Country':
1257 case 'Multi-Select Country':
1258 if (strstr($html_type, 'State/Province')) {
1259 $option = CRM_Core_PseudoConstant
::stateProvince(FALSE, FALSE);
1262 $option = CRM_Core_PseudoConstant
::country(FALSE, FALSE);
1264 // process multi-select state/country field values
1265 if (!is_array($value)) {
1266 $value = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1270 foreach ($value as $data) {
1271 $display .= ($display && !empty($option[$data])) ?
', ' . $option[$data] : $option[$data];
1276 // In the context of displaying a profile, show file/image
1277 if ($contactID && $value) {
1278 $url = self
::getFileURL($contactID, $fieldID, $value);
1280 $display = $url['file_url'];
1283 // In other contexts show a paperclip icon
1285 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1286 $display = $icons[$value];
1291 if (empty($value)) {
1295 $display = is_array($value) ?
nl2br(implode(', ', $value)) : nl2br($value);
1301 if (empty($value)) {
1305 $display = is_array($value) ?
implode(', ', $value) : $value;
1308 return $display ?
$display : $value;
1312 * Set default values for custom data used in profile.
1314 * @param int $customFieldId
1316 * @param string $elementName
1317 * Custom field name.
1318 * @param array $defaults
1319 * Associated array of fields.
1320 * @param int $contactId
1324 * @param mixed $value
1325 * If passed - dont fetch value from db,.
1326 * just format the given value
1328 public static function setProfileDefaults(
1336 //get the type of custom field
1337 $customField = new CRM_Core_BAO_CustomField();
1338 $customField->id
= $customFieldId;
1339 $customField->find(TRUE);
1342 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1343 $value = $customField->default_value
;
1347 if (!isset($value)) {
1348 $info = self
::getTableColumnGroup($customFieldId);
1349 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1350 $result = CRM_Core_DAO
::executeQuery($query);
1351 if ($result->fetch()) {
1352 $value = $result->value
;
1356 if ($customField->data_type
== 'Country') {
1358 $config = CRM_Core_Config
::singleton();
1359 if ($config->defaultContactCountry
) {
1360 $value = $config->defaultContactCountry();
1366 //set defaults if mode is registration
1367 if (!trim($value) &&
1369 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1371 $value = $customField->default_value
;
1374 if ($customField->data_type
== 'Money' && isset($value)) {
1375 $value = number_format($value, 2);
1377 switch ($customField->html_type
) {
1379 case 'AdvMulti-Select':
1380 case 'Multi-Select':
1381 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1382 $defaults[$elementName] = array();
1383 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1384 substr($value, 1, -1)
1386 foreach ($customOption as $val) {
1387 if (in_array($val['value'], $checkedValue)) {
1388 if ($customField->html_type
== 'CheckBox') {
1389 $defaults[$elementName][$val['value']] = 1;
1391 elseif ($customField->html_type
== 'Multi-Select' ||
1392 $customField->html_type
== 'AdvMulti-Select'
1394 $defaults[$elementName][$val['value']] = $val['value'];
1402 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1405 $customField->date_format
,
1406 $customField->time_format
1411 case 'Autocomplete-Select':
1412 if ($customField->data_type
== 'ContactReference') {
1413 if (is_numeric($value)) {
1414 $defaults[$elementName . '_id'] = $value;
1415 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1419 $defaults[$elementName] = $value;
1424 $defaults[$elementName] = $value;
1431 * @param int $contactID
1433 * @param int $fileID
1434 * @param bool $absolute
1438 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1441 $params = array('id' => $cfID);
1442 $defaults = array();
1443 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1444 $columnName = $defaults['column_name'];
1446 //table name of custom data
1447 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1448 $defaults['custom_group_id'],
1452 //query to fetch id from civicrm_file
1453 if ($multiRecordWhereClause) {
1454 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1457 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1459 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1464 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1469 $result['file_id'] = $fileID;
1471 if ($fileType == 'image/jpeg' ||
1472 $fileType == 'image/pjpeg' ||
1473 $fileType == 'image/gif' ||
1474 $fileType == 'image/x-png' ||
1475 $fileType == 'image/png'
1477 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1482 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1483 list($imageWidth, $imageHeight) = getimagesize($path);
1484 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1485 $url = CRM_Utils_System
::url('civicrm/file',
1486 "reset=1&id=$fileID&eid=$contactID",
1487 $absolute, NULL, TRUE, TRUE
1489 $result['file_url'] = "
1490 <a href=\"$url\" class='crm-image-popup'>
1491 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1493 // for non image files
1496 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1500 $url = CRM_Utils_System
::url('civicrm/file',
1501 "reset=1&id=$fileID&eid=$contactID",
1502 $absolute, NULL, TRUE, TRUE
1504 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1512 * Format custom fields before inserting.
1514 * @param int $customFieldId
1516 * @param array $customFormatted
1518 * @param mixed $value
1519 * Value of custom field.
1520 * @param string $customFieldExtend
1521 * Custom field extends.
1522 * @param int $customValueId
1523 * Custom option value id.
1524 * @param int $entityId
1525 * Entity id (contribution, membership...).
1526 * @param bool $inline
1527 * Consider inline custom groups only.
1528 * @param bool $checkPermission
1529 * If false, do not include permissioning clause.
1530 * @param bool $includeViewOnly
1531 * If true, fields marked 'View Only' are included. Required for APIv3.
1533 * @return array|NULL
1534 * formatted custom field array
1536 public static function formatCustomField(
1537 $customFieldId, &$customFormatted, $value,
1538 $customFieldExtend, $customValueId = NULL,
1541 $checkPermission = TRUE,
1542 $includeViewOnly = FALSE
1544 //get the custom fields for the entity
1545 //subtype and basic type
1546 $customDataSubType = NULL;
1547 if ($customFieldExtend) {
1548 // This is the case when getFieldsForImport() requires fields
1549 // of subtype and its parent.CRM-5143
1550 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1551 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1552 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1553 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1554 if (is_array($customFieldExtend)) {
1555 $customFieldExtend = array_unique(array_values($customFieldExtend));
1560 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1570 if (!array_key_exists($customFieldId, $customFields)) {
1574 // return if field is a 'code' field
1575 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1579 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1581 if (!$customValueId &&
1582 // we always create new entites for is_multiple unless specified
1583 !$customFields[$customFieldId]['is_multiple'] &&
1589 WHERE entity_id={$entityId}";
1591 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1594 //fix checkbox, now check box always submits values
1595 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1597 // Note that only during merge this is not an array, and you can directly use value
1598 if (is_array($value)) {
1599 $selectedValues = array();
1600 foreach ($value as $selId => $val) {
1602 $selectedValues[] = $selId;
1605 if (!empty($selectedValues)) {
1606 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1608 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1617 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1618 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1621 // Note that only during merge this is not an array,
1622 // and you can directly use value, CRM-4385
1623 if (is_array($value)) {
1624 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1625 array_values($value)
1626 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1634 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1635 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1636 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1638 $customFields[$customFieldId]['data_type'] == 'String' &&
1639 !empty($customFields[$customFieldId]['text_length']) &&
1642 // lets make sure that value is less than the length, else we'll
1643 // be losing some data, CRM-7481
1644 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1645 // need to do a few things here
1647 // 1. lets find a new length
1648 $newLength = $customFields[$customFieldId]['text_length'];
1649 $minLength = strlen($value);
1650 while ($newLength < $minLength) {
1651 $newLength = $newLength * 2;
1654 // set the custom field meta data to have a length larger than value
1655 // alter the custom value table column to match this length
1656 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1661 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1662 if (!CRM_Utils_System
::isNull($value)) {
1663 $format = $customFields[$customFieldId]['date_format'];
1664 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1669 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1670 $customFields[$customFieldId]['data_type'] == 'Money'
1676 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1677 $value = CRM_Utils_Rule
::cleanMoney($value);
1681 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1682 $customFields[$customFieldId]['data_type'] == 'Country'
1692 if ($customFields[$customFieldId]['data_type'] == 'File') {
1693 if (empty($value)) {
1697 $config = CRM_Core_Config
::singleton();
1699 $fName = $value['name'];
1700 $mimeType = $value['type'];
1702 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1704 // rename this file to go into the secure directory
1705 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1706 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1709 if ($customValueId) {
1714 $params = array(1 => array($customValueId, 'Integer'));
1715 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1718 $fileDAO = new CRM_Core_DAO_File();
1721 $fileDAO->id
= $fileId;
1724 $fileDAO->uri
= $filename;
1725 $fileDAO->mime_type
= $mimeType;
1726 $fileDAO->upload_date
= date('Ymdhis');
1728 $fileId = $fileDAO->id
;
1732 if (!is_array($customFormatted)) {
1733 $customFormatted = array();
1736 if (!array_key_exists($customFieldId, $customFormatted)) {
1737 $customFormatted[$customFieldId] = array();
1741 if ($customValueId) {
1742 $index = $customValueId;
1745 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1746 $customFormatted[$customFieldId][$index] = array();
1748 $customFormatted[$customFieldId][$index] = array(
1749 'id' => $customValueId > 0 ?
$customValueId : NULL,
1751 'type' => $customFields[$customFieldId]['data_type'],
1752 'custom_field_id' => $customFieldId,
1753 'custom_group_id' => $groupID,
1754 'table_name' => $tableName,
1755 'column_name' => $columnName,
1756 'file_id' => $fileId,
1757 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1760 //we need to sort so that custom fields are created in the order of entry
1761 krsort($customFormatted[$customFieldId]);
1762 return $customFormatted;
1766 * Get default custom table schema.
1768 * @param array $params
1772 public static function defaultCustomTableSchema($params) {
1773 // add the id and extends_id
1775 'name' => $params['name'],
1776 'is_multiple' => $params['is_multiple'],
1777 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1781 'type' => 'int unsigned',
1784 'attributes' => 'AUTO_INCREMENT',
1785 'comment' => 'Default MySQL primary key',
1788 'name' => 'entity_id',
1789 'type' => 'int unsigned',
1791 'comment' => 'Table that this extends',
1792 'fk_table_name' => $params['extends_name'],
1793 'fk_field_name' => 'id',
1794 'fk_attributes' => 'ON DELETE CASCADE',
1799 if (!$params['is_multiple']) {
1800 $table['indexes'] = array(
1803 'field_name_1' => 'entity_id',
1811 * Create custom field.
1813 * @param CRM_Core_DAO_CustomField $field
1814 * @param string $operation
1815 * @param bool $indexExist
1816 * @param bool $triggerRebuild
1818 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1819 $tableName = CRM_Core_DAO
::getFieldValue(
1820 'CRM_Core_DAO_CustomGroup',
1821 $field->custom_group_id
,
1826 'table_name' => $tableName,
1827 'operation' => $operation,
1828 'name' => $field->column_name
,
1829 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1833 'required' => $field->is_required
,
1834 'searchable' => $field->is_searchable
,
1837 if ($operation == 'delete') {
1838 $fkName = "{$tableName}_{$field->column_name}";
1839 if (strlen($fkName) >= 48) {
1840 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1842 $params['fkName'] = $fkName;
1844 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1845 $params['fk_table_name'] = 'civicrm_country';
1846 $params['fk_field_name'] = 'id';
1847 $params['fk_attributes'] = 'ON DELETE SET NULL';
1849 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1850 $params['type'] = 'varchar(255)';
1852 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1853 $params['fk_table_name'] = 'civicrm_state_province';
1854 $params['fk_field_name'] = 'id';
1855 $params['fk_attributes'] = 'ON DELETE SET NULL';
1857 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1858 $params['type'] = 'varchar(255)';
1860 elseif ($field->data_type
== 'File') {
1861 $params['fk_table_name'] = 'civicrm_file';
1862 $params['fk_field_name'] = 'id';
1863 $params['fk_attributes'] = 'ON DELETE SET NULL';
1865 elseif ($field->data_type
== 'ContactReference') {
1866 $params['fk_table_name'] = 'civicrm_contact';
1867 $params['fk_field_name'] = 'id';
1868 $params['fk_attributes'] = 'ON DELETE SET NULL';
1870 if (isset($field->default_value
)) {
1871 $params['default'] = "'{$field->default_value}'";
1874 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1878 * Determine whether it would be safe to move a field.
1880 * @param int $fieldID
1881 * FK to civicrm_custom_field.
1882 * @param int $newGroupID
1883 * FK to civicrm_custom_group.
1886 * array(string) or TRUE
1888 public static function _moveFieldValidate($fieldID, $newGroupID) {
1891 $field = new CRM_Core_DAO_CustomField();
1892 $field->id
= $fieldID;
1893 if (!$field->find(TRUE)) {
1894 $errors['fieldID'] = 'Invalid ID for custom field';
1898 $oldGroup = new CRM_Core_DAO_CustomGroup();
1899 $oldGroup->id
= $field->custom_group_id
;
1900 if (!$oldGroup->find(TRUE)) {
1901 $errors['fieldID'] = 'Invalid ID for old custom group';
1905 $newGroup = new CRM_Core_DAO_CustomGroup();
1906 $newGroup->id
= $newGroupID;
1907 if (!$newGroup->find(TRUE)) {
1908 $errors['newGroupID'] = 'Invalid ID for new custom group';
1914 FROM civicrm_custom_field a
1915 INNER JOIN civicrm_custom_field b
1917 AND a.label = b.label
1918 AND b.custom_group_id = %2
1921 1 => array($field->id
, 'Integer'),
1922 2 => array($newGroup->id
, 'Integer'),
1924 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1926 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1929 $tableName = $oldGroup->table_name
;
1930 $columnName = $field->column_name
;
1935 WHERE $columnName is not null
1937 $count = CRM_Core_DAO
::singleValueQuery($query,
1938 CRM_Core_DAO
::$_nullArray
1943 FROM civicrm_custom_group
1944 WHERE id IN ( %1, %2 )
1947 1 => array($oldGroup->id
, 'Integer'),
1948 2 => array($newGroup->id
, 'Integer'),
1951 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1953 while ($dao->fetch()) {
1954 $extends[] = $dao->extends;
1956 if ($extends[0] != $extends[1]) {
1957 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1961 return empty($errors) ?
TRUE : $errors;
1965 * Move a custom data field from one group (table) to another.
1967 * @param int $fieldID
1968 * FK to civicrm_custom_field.
1969 * @param int $newGroupID
1970 * FK to civicrm_custom_group.
1972 public static function moveField($fieldID, $newGroupID) {
1973 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1974 if (TRUE !== $validation) {
1975 CRM_Core_Error
::fatal(implode(' ', $validation));
1977 $field = new CRM_Core_DAO_CustomField();
1978 $field->id
= $fieldID;
1981 $newGroup = new CRM_Core_DAO_CustomGroup();
1982 $newGroup->id
= $newGroupID;
1983 $newGroup->find(TRUE);
1985 $oldGroup = new CRM_Core_DAO_CustomGroup();
1986 $oldGroup->id
= $field->custom_group_id
;
1987 $oldGroup->find(TRUE);
1990 $add->custom_group_id
= $newGroup->id
;
1991 self
::createField($add, 'add');
1993 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1994 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1995 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1997 CRM_Core_DAO
::executeQuery($sql);
2000 $del->custom_group_id
= $oldGroup->id
;
2001 self
::createField($del, 'delete');
2005 CRM_Utils_System
::flushCache();
2009 * Get the database table name and column name for a custom field.
2011 * @param int $fieldID
2012 * The fieldID of the custom field.
2013 * @param bool $force
2014 * Force the sql to be run again (primarily used for tests).
2017 * fatal is fieldID does not exists, else array of tableName, columnName
2019 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2020 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2021 $cache = CRM_Utils_Cache
::singleton();
2022 $fieldValues = $cache->get($cacheKey);
2023 if (empty($fieldValues) ||
$force) {
2025 SELECT cg.table_name, cf.column_name, cg.id
2026 FROM civicrm_custom_group cg,
2027 civicrm_custom_field cf
2028 WHERE cf.custom_group_id = cg.id
2030 $params = array(1 => array($fieldID, 'Integer'));
2031 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2033 if (!$dao->fetch()) {
2034 CRM_Core_Error
::fatal();
2037 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2038 $cache->set($cacheKey, $fieldValues);
2040 return $fieldValues;
2044 * Get custom option groups.
2046 * @param array $includeFieldIds
2047 * Ids of custom fields for which option groups must be included.
2049 * Currently this is required in the cases where option groups are to be included
2050 * for inactive fields : CRM-5369
2054 public static function customOptionGroup($includeFieldIds = NULL) {
2055 static $customOptionGroup = NULL;
2057 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2058 if ($cacheKey == 'force') {
2059 $customOptionGroup[$cacheKey] = NULL;
2062 if (empty($customOptionGroup[$cacheKey])) {
2063 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2065 //support for single as well as array format.
2066 if (!empty($includeFieldIds)) {
2067 if (is_array($includeFieldIds)) {
2068 $includeFieldIds = implode(',', $includeFieldIds);
2070 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2074 SELECT g.id, g.title
2075 FROM civicrm_option_group g
2076 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2077 WHERE {$whereClause}";
2079 $dao = CRM_Core_DAO
::executeQuery($query);
2080 while ($dao->fetch()) {
2081 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2085 return $customOptionGroup[$cacheKey];
2089 * Fix orphan groups.
2091 * @param int $customFieldId
2093 * @param int $optionGroupId
2096 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2097 // check if option group belongs to any custom Field else delete
2098 // get the current option group
2099 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2103 // get the updated option group
2104 // if both are same return
2105 if ($currentOptionGroupId == $optionGroupId) {
2109 // check if option group is related to any other field
2110 self
::checkOptionGroup($currentOptionGroupId);
2114 * Check if option group is related to more than one custom field.
2116 * @param int $optionGroupId
2119 public static function checkOptionGroup($optionGroupId) {
2122 FROM civicrm_custom_field
2123 WHERE option_group_id = {$optionGroupId}";
2125 $count = CRM_Core_DAO
::singleValueQuery($query);
2128 //delete the option group
2129 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2134 * Get option group default.
2136 * @param int $optionGroupId
2137 * @param string $htmlType
2139 * @return null|string
2141 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2143 SELECT default_value, html_type
2144 FROM civicrm_custom_field
2145 WHERE option_group_id = {$optionGroupId}
2146 AND default_value IS NOT NULL
2147 ORDER BY html_type";
2149 $dao = CRM_Core_DAO
::executeQuery($query);
2150 $defaultValue = NULL;
2151 $defaultHTMLType = NULL;
2152 while ($dao->fetch()) {
2153 if ($dao->html_type
== $htmlType) {
2154 return $dao->default_value
;
2156 if ($defaultValue == NULL) {
2157 $defaultValue = $dao->default_value
;
2158 $defaultHTMLType = $dao->html_type
;
2162 // some conversions are needed if either the old or new has a html type which has potential
2163 // multiple default values.
2164 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2165 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2167 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2169 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2170 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2172 $defaultValue = substr($defaultValue, 1, -1);
2173 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2174 substr($defaultValue, 1, -1)
2176 $defaultValue = $values[0];
2179 return $defaultValue;
2183 * Post process function.
2185 * @param array $params
2186 * @param int $entityID
2187 * @param string $customFieldExtends
2188 * @param bool $inline
2192 public static function postProcess(
2195 $customFieldExtends,
2198 $customData = array();
2200 foreach ($params as $key => $value) {
2201 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2203 // for autocomplete transfer hidden value instead of label
2204 if ($params[$key] && isset($params[$key . '_id'])) {
2205 $value = $params[$key . '_id'];
2208 // we need to append time with date
2209 if ($params[$key] && isset($params[$key . '_time'])) {
2210 $value .= ' ' . $params[$key . '_time'];
2213 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2216 $customFieldExtends,
2217 $customFieldInfo[1],
2229 * @param array $field
2230 * @param array $options
2234 public static function buildOption($field, &$options) {
2235 // Fixme - adding anything but options to the $options array is a bad idea
2236 // What if an option had the key 'attributes'?
2237 $options['attributes'] = array(
2238 'label' => $field['label'],
2239 'data_type' => $field['data_type'],
2240 'html_type' => $field['html_type'],
2243 $optionGroupID = NULL;
2244 if (($field['html_type'] == 'CheckBox' ||
2245 $field['html_type'] == 'Radio' ||
2246 $field['html_type'] == 'Select' ||
2247 $field['html_type'] == 'AdvMulti-Select' ||
2248 $field['html_type'] == 'Multi-Select' ||
2249 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2252 if ($field['option_group_id']) {
2253 $optionGroupID = $field['option_group_id'];
2255 elseif ($field['data_type'] != 'Boolean') {
2256 CRM_Core_Error
::fatal();
2260 // build the cache for custom values with options (label => value)
2261 if ($optionGroupID != NULL) {
2264 FROM civicrm_option_value
2265 WHERE option_group_id = $optionGroupID
2268 $dao = CRM_Core_DAO
::executeQuery($query);
2269 while ($dao->fetch()) {
2270 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2271 $num = round($dao->value
, 2);
2272 $options["$num"] = $dao->label
;
2275 $options[$dao->value
] = $dao->label
;
2279 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2284 * Get custom field ID.
2286 * @param string $fieldLabel
2287 * @param null $groupTitle
2291 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2292 $params = array(1 => array($fieldLabel, 'String'));
2294 $params[2] = array($groupTitle, 'String');
2297 FROM civicrm_custom_field f
2298 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2299 WHERE ( f.label = %1 OR f.name = %1 )
2300 AND ( g.title = %2 OR g.name = %2 )
2306 FROM civicrm_custom_field f
2307 WHERE ( f.label = %1 OR f.name = %1 )
2311 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2312 if ($dao->fetch() &&
2323 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2329 public static function getNameFromID($ids) {
2330 if (is_array($ids)) {
2331 $ids = implode(',', $ids);
2334 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2335 FROM civicrm_custom_field f
2336 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2337 WHERE f.id IN ($ids)";
2339 $dao = CRM_Core_DAO
::executeQuery($sql);
2341 while ($dao->fetch()) {
2342 $result[$dao->id
] = array(
2343 'field_name' => $dao->field_name
,
2344 'field_label' => $dao->field_label
,
2345 'group_name' => $dao->group_name
,
2346 'group_title' => $dao->group_title
,
2353 * Validate custom data.
2355 * @param array $params
2356 * Custom data submitted.
2357 * ie array( 'custom_1' => 'validate me' );
2360 * validation errors.
2362 public static function validateCustomData($params) {
2364 if (!is_array($params) ||
empty($params)) {
2368 //pick up profile fields.
2369 $profileFields = array();
2370 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2372 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2374 CRM_Core_Action
::VIEW
2378 //lets start w/ params.
2379 foreach ($params as $key => $value) {
2380 $customFieldID = self
::getKeyID($key);
2381 if (!$customFieldID) {
2385 //load the structural info for given field.
2386 $field = new CRM_Core_DAO_CustomField();
2387 $field->id
= $customFieldID;
2388 if (!$field->find(TRUE)) {
2391 $dataType = $field->data_type
;
2393 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2394 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2395 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2397 $fieldTitle = $field->label
;
2400 //no need to validate.
2401 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2405 //lets validate first for required field.
2406 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2407 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2411 //now time to take care of custom field form rules.
2412 $ruleName = $errorMsg = NULL;
2413 switch ($dataType) {
2415 $ruleName = 'integer';
2416 $errorMsg = ts('%1 must be an integer (whole number).',
2417 array(1 => $fieldTitle)
2422 $ruleName = 'money';
2423 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2424 array(1 => $fieldTitle)
2429 $ruleName = 'numeric';
2430 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2431 array(1 => $fieldTitle)
2436 $ruleName = 'wikiURL';
2437 $errorMsg = ts('%1 must be valid Website.',
2438 array(1 => $fieldTitle)
2443 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2445 $funName = "CRM_Utils_Rule::{$ruleName}";
2446 if (is_callable($funName)) {
2447 $valid = call_user_func($funName, $value);
2450 $errors[$key] = $errorMsg;
2459 * Is this field a multi record field.
2461 * @param int $customId
2465 public static function isMultiRecordField($customId) {
2466 $isMultipleWithGid = FALSE;
2467 if (!is_numeric($customId)) {
2468 $customId = self
::getKeyID($customId);
2470 if (is_numeric($customId)) {
2471 $sql = "SELECT cg.id cgId
2472 FROM civicrm_custom_group cg
2473 INNER JOIN civicrm_custom_field cf
2474 ON cg.id = cf.custom_group_id
2475 WHERE cf.id = %1 AND cg.is_multiple = 1";
2476 $params[1] = array($customId, 'Integer');
2477 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2478 if ($dao->fetch()) {
2480 $isMultipleWithGid = $dao->cgId
;
2485 return $isMultipleWithGid;
2489 * Does this field store a serialized string?
2491 * @param array $field
2495 public static function isSerialized($field) {
2496 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2497 $field = (array) $field;
2498 // 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.
2499 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2503 * Get options for field.
2505 * @param array $field
2506 * @param string|null $optionGroupName
2508 private static function getOptionsForField(&$field, $optionGroupName) {
2509 if ($optionGroupName) {
2510 $field['pseudoconstant'] = array(
2511 'optionGroupName' => $optionGroupName,
2512 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2515 elseif ($field['data_type'] == 'Boolean') {
2516 $field['pseudoconstant'] = array(
2517 'callback' => 'CRM_Core_SelectValues::boolean',
2520 elseif ($field['data_type'] == 'Country') {
2521 $field['pseudoconstant'] = array(
2522 'table' => 'civicrm_country',
2523 'keyColumn' => 'id',
2524 'labelColumn' => 'name',
2525 'nameColumn' => 'iso_code',
2528 elseif ($field['data_type'] == 'StateProvince') {
2529 $field['pseudoconstant'] = array(
2530 'table' => 'civicrm_state_province',
2531 'keyColumn' => 'id',
2532 'labelColumn' => 'name',