3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * Business objects for managing custom data fields.
40 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
43 * Array for valid combinations of data_type & descriptions
48 public static $_dataType = NULL;
51 * Array for valid combinations of data_type & html_type
56 public static $_dataToHtml = NULL;
59 * Array to hold (formatted) fields for import
64 public static $_importFields = NULL;
67 * Build and retrieve the list of data types and descriptions
71 * @return array Data type => Description
75 static function &dataType() {
76 if (!(self
::$_dataType)) {
77 self
::$_dataType = array(
78 'String' => ts('Alphanumeric'),
79 'Int' => ts('Integer'),
80 'Float' => ts('Number'),
81 'Money' => ts('Money'),
84 'Boolean' => ts('Yes or No'),
85 'StateProvince' => ts('State/Province'),
86 'Country' => ts('Country'),
89 'ContactReference' => ts('Contact Reference'),
92 return self
::$_dataType;
98 static function dataToHtml() {
99 if (!self
::$_dataToHtml) {
100 self
::$_dataToHtml = array(
102 'Text' => 'Text', 'Select' => 'Select',
103 'Radio' => 'Radio', 'CheckBox' => 'CheckBox',
104 'Multi-Select' => 'Multi-Select',
105 'AdvMulti-Select' => 'AdvMulti-Select',
106 'Autocomplete-Select' => 'Autocomplete-Select',
108 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
109 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
110 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
111 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
112 array('Date' => 'Select Date'),
113 array('Radio' => 'Radio'),
114 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
115 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
116 array('File' => 'File'),
117 array('Link' => 'Link'),
118 array('ContactReference' => 'Autocomplete-Select'),
121 return self
::$_dataToHtml;
125 * Takes an associative array and creates a custom field object
127 * This function is invoked from within the web form layer and also from the api layer
129 * @param array $params (reference) an assoc array of name/value pairs
131 * @return CRM_Core_DAO_CustomField object
135 static function create(&$params) {
136 $origParams = array_merge(array(), $params);
138 if (!isset($params['id'])) {
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
;
169 case 'AdvMulti-Select':
171 if (isset($params['default_checkbox_option'])) {
172 $tempArray = array_keys($params['default_checkbox_option']);
173 $defaultArray = array();
174 foreach ($tempArray as $k => $v) {
175 if ($params['option_value'][$v]) {
176 $defaultArray[] = $params['option_value'][$v];
180 if (!empty($defaultArray)) {
181 // also add the seperator before and after the value per new conventio (CRM-1604)
182 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
186 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
188 $params['default_value'] = $params['option_value'][$params['default_option']];
194 $transaction = new CRM_Core_Transaction();
195 // create any option group & values if required
196 if ($params['html_type'] != 'Text' &&
197 in_array($params['data_type'], array(
198 'String', 'Int', 'Float', 'Money'))
201 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
202 $params['custom_group_id'],
207 if ($params['option_type'] == 1 && empty($params['option_group_id'])) {
208 // first create an option group for this custom group
209 $optionGroup = new CRM_Core_DAO_OptionGroup();
210 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
211 $optionGroup->title
= $params['label'];
212 $optionGroup->is_active
= 1;
213 $optionGroup->save();
214 $params['option_group_id'] = $optionGroup->id
;
215 if(!empty($params['option_value']) && is_array($params['option_value'])){
216 foreach ($params['option_value'] as $k => $v) {
217 if (strlen(trim($v))) {
218 $optionValue = new CRM_Core_DAO_OptionValue();
219 $optionValue->option_group_id
= $optionGroup->id
;
220 $optionValue->label
= $params['option_label'][$k];
221 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
222 switch ($params['data_type']) {
224 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
228 $optionValue->value
= intval($v);
232 $optionValue->value
= floatval($v);
236 $optionValue->value
= trim($v);
239 $optionValue->weight
= $params['option_weight'][$k];
240 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
241 $optionValue->save();
248 // check for orphan option groups
249 if (!empty($params['option_group_id'])) {
250 if (!empty($params['id'])) {
251 self
::fixOptionGroups($params['id'], $params['option_group_id']);
254 // if we dont have a default value
255 // retrive it from one of the other custom fields which use this option group
256 if (empty($params['default_value'])) {
257 //don't insert only value separator as default value, CRM-4579
258 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
262 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
265 $params['default_value'] = $defaultValue;
270 // since we need to save option group id :)
271 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
272 $params['attributes'] = 'rows=4, cols=60';
275 $customField = new CRM_Core_DAO_CustomField();
276 $customField->copyValues($params);
277 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
278 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
279 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $params, FALSE);
280 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
281 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, FALSE);
282 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
283 $customField->save();
285 // make sure all values are present in the object for further processing
286 $customField->find(TRUE);
288 $triggerRebuild = CRM_Utils_Array
::value('triggerRebuild', $params, TRUE);
289 //create/drop the index when we toggle the is_searchable flag
290 if (!empty($params['id'])) {
291 self
::createField($customField, 'modify', $indexExist, $triggerRebuild);
294 if (!isset($origParams['column_name'])) {
295 $columnName .= "_{$customField->id}";
296 $params['column_name'] = $columnName;
298 $customField->column_name
= $columnName;
299 $customField->save();
300 // make sure all values are present in the object
301 $customField->find(TRUE);
304 self
::createField($customField, 'add', $indexExist, $triggerRebuild);
307 // complete transaction
308 $transaction->commit();
310 CRM_Utils_System
::flushCache();
316 * Fetch object based on array of properties
318 * @param array $params (reference ) an assoc array of name/value pairs
319 * @param array $defaults (reference ) an assoc array to hold the flattened values
321 * @return CRM_Core_DAO_CustomField object
325 static function retrieve(&$params, &$defaults) {
326 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
330 * Update the is_active flag in the db
332 * @param int $id Id of the database record
333 * @param boolean $is_active Value we want to set the is_active field
335 * @return Object DAO object on sucess, null otherwise
340 static function setIsActive($id, $is_active) {
342 CRM_Utils_System
::flushCache();
344 //enable-disable CustomField
345 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
346 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
350 * Get the field title.
352 * @param int $id id of field.
354 * @return string name
360 public static function getTitle($id) {
361 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
365 * Store and return an array of all active custom fields.
367 * @param string $customDataType type of Custom Data; empty is a synonym for "all contact data types"
368 * @param boolean $showAll If true returns all fields (includes disabled fields)
369 * @param boolean $inline If true returns all inline fields (includes disabled fields)
370 * @param int $customDataSubType Custom Data sub type value
371 * @param int $customDataSubName Custom Data sub name value
372 * @param boolean $onlyParent return only top level custom data, for eg, only Participant and ignore subname and subtype
373 * @param boolean $onlySubType return only custom data for subtype
374 * @param boolean $checkPermission if false, do not include permissioning clause
376 * @return array $fields - an array of active custom fields.
381 public static function &getFields($customDataType = 'Individual',
384 $customDataSubType = NULL,
385 $customDataSubName = NULL,
387 $onlySubType = FALSE,
388 $checkPermission = TRUE
390 if (empty($customDataType)) {
391 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
393 if ($customDataType && !is_array($customDataType)) {
395 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
396 // This is the case when getFieldsForImport() requires fields
397 // limited strictly to a subtype.
398 $customDataSubType = $customDataType;
399 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
403 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
404 // this makes the method flexible to support retrieving fields
405 // for multiple extends value.
406 $customDataType = array($customDataType);
410 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
412 if (is_array($customDataType)) {
413 $cacheKey = implode('_', $customDataType);
416 $cacheKey = $customDataType;
419 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
420 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
421 $cacheKey .= $showAll ?
'_1' : '_0';
422 $cacheKey .= $inline ?
'_1_' : '_0_';
423 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
424 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
425 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
427 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
429 // also get the permission stuff here
430 if ($checkPermission) {
431 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
436 $permissionClause = '(1)';
439 // lets md5 permission clause and take first 8 characters
440 $cacheKey .= substr(md5($permissionClause), 0, 8);
442 if (strlen($cacheKey) > 40) {
443 $cacheKey = md5($cacheKey);
446 if (!self
::$_importFields ||
447 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
449 if (!self
::$_importFields) {
450 self
::$_importFields = array();
453 // check if we can retrieve from database cache
454 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
456 if ($fields === NULL) {
457 $cfTable = self
::getTableName();
460 if (is_array($customDataType)) {
462 foreach ($customDataType as $dataType) {
463 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
464 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
465 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
468 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
470 $value = $value ?
$value . ", {$val}" : $val;
474 $extends = "AND $cgTable.extends IN ( $value ) ";
478 if (!empty($customDataType) && empty($extends)) {
479 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
480 self
::$_importFields[$cacheKey] = array();
481 return self
::$_importFields[$cacheKey];
485 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
488 $query = "SELECT $cfTable.id, $cfTable.label,
492 $cfTable.default_value,
493 $cfTable.options_per_line, $cfTable.text_length,
494 $cfTable.custom_group_id,
495 $cfTable.is_required,
496 $cgTable.extends, $cfTable.is_search_range,
497 $cgTable.extends_entity_column_value,
498 $cgTable.extends_entity_column_id,
500 $cfTable.option_group_id,
501 $cfTable.date_format,
502 $cfTable.time_format,
506 ON $cfTable.custom_group_id = $cgTable.id
510 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
514 $query .= " AND $cgTable.style = 'Inline' ";
517 //get the custom fields for specific type in
518 //combination with fields those support any type.
519 if (!empty($customDataSubType)) {
520 $subtypeClause = array();
521 foreach ($customDataSubType as $subtype) {
522 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
523 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
526 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
528 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
531 if ($customDataSubName) {
532 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
535 // also get the permission stuff here
536 if ($checkPermission) {
537 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
542 $permissionClause = '(1)';
545 $query .= " $extends AND $permissionClause
546 ORDER BY $cgTable.weight, $cgTable.title,
547 $cfTable.weight, $cfTable.label";
549 $dao = CRM_Core_DAO
::executeQuery($query);
552 while (($dao->fetch()) != NULL) {
553 $fields[$dao->id
]['label'] = $dao->label
;
554 $fields[$dao->id
]['groupTitle'] = $dao->title
;
555 $fields[$dao->id
]['data_type'] = $dao->data_type
;
556 $fields[$dao->id
]['html_type'] = $dao->html_type
;
557 $fields[$dao->id
]['default_value'] = $dao->default_value
;
558 $fields[$dao->id
]['text_length'] = $dao->text_length
;
559 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
560 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
561 $fields[$dao->id
]['extends'] = $dao->extends;
562 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
563 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
564 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
565 $fields[$dao->id
]['is_view'] = $dao->is_view
;
566 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
567 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
568 $fields[$dao->id
]['date_format'] = $dao->date_format
;
569 $fields[$dao->id
]['time_format'] = $dao->time_format
;
570 $fields[$dao->id
]['is_required'] = $dao->is_required
;
573 CRM_Core_BAO_Cache
::setItem($fields,
575 "custom importableFields $cacheKey"
578 self
::$_importFields[$cacheKey] = $fields;
581 return self
::$_importFields[$cacheKey];
585 * Return the field ids and names (with groups) for import purpose.
587 * @param int|string $contactType Contact type
588 * @param boolean $showAll If true returns all fields (includes disabled fields)
589 * @param boolean $onlyParent return fields ONLY related to basic types
590 * @param boolean $search when called from search and multiple records need to be returned
591 * @param boolean $checkPermission if false, do not include permissioning clause
593 * @param bool $withMultiple
595 * @return array $fields -
600 public static function &getFieldsForImport($contactType = 'Individual',
604 $checkPermission = TRUE,
605 $withMultiple = FALSE
607 // Note: there are situations when we want getFieldsForImport() return fields related
608 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
609 $fields = &self
::getFields($contactType,
619 $importableFields = array();
620 foreach ($fields as $id => $values) {
621 // for now we should not allow multiple fields in profile / export etc, hence unsetting
623 (!empty($values['is_multiple']) && !$withMultiple)
628 /* generate the key for the fields array */
632 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
633 $importableFields[$key] = array(
635 'title' => CRM_Utils_Array
::value('label', $values),
636 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
638 'custom_field_id' => $id,
639 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
640 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
641 'data_type' => CRM_Utils_Array
::value('data_type', $values),
642 'html_type' => CRM_Utils_Array
::value('html_type', $values),
643 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
646 // CRM-6681, pass date and time format when html_type = Select Date
647 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
648 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
649 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
653 return $importableFields;
657 * Get the field id from an import key
659 * @param string $key The key to parse
662 * @return int|null The id (if exists)
666 public static function getKeyID($key, $all = FALSE) {
668 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
675 CRM_Utils_Array
::value(2, $match),
679 return $all ?
array(NULL, NULL) : NULL;
683 * Use the cache to get all values of a specific custom field
685 * @param int $fieldID the custom field ID
687 * @return CRM_Core_DAO_CustomField $field the field object
691 static function getFieldObject($fieldID) {
692 $field = new CRM_Core_DAO_CustomField();
694 // check if we can get the field values from the system cache
695 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
696 $cache = CRM_Utils_Cache
::singleton();
697 $fieldValues = $cache->get($cacheKey);
698 if (empty($fieldValues)) {
699 $field->id
= $fieldID;
700 if (!$field->find(TRUE)) {
701 CRM_Core_Error
::fatal();
704 $fieldValues = array();
705 CRM_Core_DAO
::storeValues($field, $fieldValues);
707 $cache->set($cacheKey, $fieldValues);
710 $field->copyValues($fieldValues);
717 * This function for building custom fields
719 * @param CRM_Core_Form $qf form object (reference)
720 * @param string $elementName name of the custom field
721 * @param int $fieldId
722 * @param boolean $inactiveNeeded -deprecated
723 * @param bool $useRequired true if required else false
724 * @param boolean $search true if used for search else false
725 * @param string $label label for custom field
730 public static function addQuickFormElement(&$qf,
733 $inactiveNeeded = FALSE,
738 $field = self
::getFieldObject($fieldId);
739 $widget = $field->html_type
;
741 // Custom field HTML should indicate group+field name
742 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
743 $dataCrmCustomVal = $groupName.':'.$field->name
;
744 $dataCrmCustomAttr = 'data-crm-custom="'.$dataCrmCustomVal.'"';
745 $field->attributes
.= $dataCrmCustomAttr;
747 // Fixed for Issue CRM-2183
748 if ($widget == 'TextArea' && $search) {
752 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
754 // FIXME: Why are select state/country separate widget types?
755 $isSelect = (in_array($widget, array('Select', 'Multi-Select', 'Select State/Province', 'Multi-Select State/Province', 'Select Country', 'Multi-Select Country', 'AdvMulti-Select', 'CheckBox', 'Radio')));
758 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array('field' => "custom_$fieldId", 'context' => $search ?
'search' : 'create'), array()));
760 // Consolidate widget types to simplify the below switch statement
761 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
764 $selectAttributes = array(
765 'data-crm-custom' => $dataCrmCustomVal,
766 'class' => 'crm-select2',
768 // Search field is always multi-select
769 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
770 $selectAttributes['class'] .= ' huge';
771 $selectAttributes['multiple'] = 'multiple';
772 $selectAttributes['placeholder'] = $placeholder;
774 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
775 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
776 $selectAttributes +
= array(
777 'data-api-entity' => 'contact', // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
778 'data-api-field' => 'custom_' . $field->id
,
779 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
784 if (!isset($label)) {
785 $label = $field->label
;
789 * at some point in time we might want to split the below into small functions
795 if ($field->is_search_range
&& $search) {
796 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
797 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
800 $element = &$qf->add('text', $elementName, $label,
802 $useRequired && !$search
808 $attributes = $dataCrmCustomAttr;
809 if ($field->note_rows
) {
810 $attributes .= 'rows=' . $field->note_rows
;
813 $attributes .= 'rows=4';
815 if ($field->note_columns
) {
816 $attributes .= ' cols=' . $field->note_columns
;
819 $attributes .= ' cols=60';
821 if ($field->text_length
) {
822 $attributes .= ' maxlength=' . $field->text_length
;
824 $element = &$qf->add('textarea',
828 $useRequired && !$search
833 if ($field->is_search_range
&& $search) {
834 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
836 'format' => $field->date_format
,
837 'timeFormat' => $field->time_format
,
838 'startOffset' => $field->start_date_years
,
839 'endOffset' => $field->end_date_years
,
840 'data-crm-custom' => $dataCrmCustomVal,
844 $qf->addDate($elementName . '_to', ts('To'), FALSE,
846 'format' => $field->date_format
,
847 'timeFormat' => $field->time_format
,
848 'startOffset' => $field->start_date_years
,
849 'endOffset' => $field->end_date_years
,
850 'data-crm-custom' => $dataCrmCustomVal,
855 $required = $useRequired && !$search;
857 $qf->addDate($elementName, $label, $required, array(
858 'format' => $field->date_format
,
859 'timeFormat' => $field->time_format
,
860 'startOffset' => $field->start_date_years
,
861 'endOffset' => $field->end_date_years
,
862 'data-crm-custom' => $dataCrmCustomVal,
869 foreach ($options as $v => $l) {
870 $choice[] = $qf->createElement('radio', NULL, '', $l, (string)$v, $field->attributes
);
872 $group = $qf->addGroup($choice, $elementName, $label);
873 if ($useRequired && !$search) {
874 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
877 $group->setAttribute('allowClear', TRUE);
881 // For all select elements
883 if (empty($selectAttributes['multiple'])) {
884 $options = array('' => $placeholder) +
$options;
886 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
888 // Add and/or option for fields that store multiple values
889 if ($search && self
::isSerialized($field)) {
892 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
893 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
895 $qf->addGroup($operators, $elementName . '_operator');
896 $qf->setDefaults(array($elementName . '_operator' => 'or'));
900 case 'AdvMulti-Select':
901 $include =& $qf->addElement(
908 'class' => 'advmultiselect',
909 'data-crm-custom' => $dataCrmCustomVal,
913 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
914 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
916 if ($useRequired && !$search) {
917 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
923 foreach ($options as $v => $l) {
924 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
926 $qf->addGroup($check, $elementName, $label);
927 if ($useRequired && !$search) {
928 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
933 // we should not build upload file in search mode
938 strtolower($field->html_type
),
942 $useRequired && !$search
944 $qf->addUploadElement($elementName);
947 case 'RichTextEditor':
948 $attributes = array('rows' => $field->note_rows
, 'cols' => $field->note_columns
, 'data-crm-custom' => $dataCrmCustomVal);
949 if ($field->text_length
) {
950 $attributes['maxlength'] = $field->text_length
;
952 $qf->addWysiwyg($elementName, $label, $attributes, $search);
955 case 'Autocomplete-Select':
956 static $customUrls = array();
957 // Fixme: why is this a string in the first place??
958 $attributes = array();
959 if ($field->attributes
) {
960 foreach(explode(' ', $field->attributes
) as $at) {
961 if (strpos($at, '=')) {
962 list($k, $v) = explode('=', $at);
963 $attributes[$k] = trim($v, ' "');
967 if ($field->data_type
== 'ContactReference') {
968 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
969 $attributes['data-api-entity'] = 'contact';
970 $qf->add('text', $elementName, $label, $attributes,
971 $useRequired && !$search
974 $urlParams = "context=customfield&id={$field->id}";
976 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
983 // FIXME: This won't work with customFieldOptions hook
984 $attributes +
= array(
985 'entity' => 'option_value',
986 'placeholder' => $placeholder,
987 'multiple' => $search,
989 'params' => array('option_group_id' => $field->option_group_id
),
992 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
995 $qf->assign('customUrls', $customUrls);
999 switch ($field->data_type
) {
1001 // integers will have numeric rule applied to them.
1002 if ($field->is_search_range
&& $search) {
1003 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1004 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1006 elseif ($widget == 'Text') {
1007 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1012 if ($field->is_search_range
&& $search) {
1013 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1014 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1016 elseif ($widget == 'Text') {
1017 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1022 if ($field->is_search_range
&& $search) {
1023 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1024 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1026 elseif ($widget == 'Text') {
1027 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1032 $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
1033 $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
1034 $element->setAttribute('class', "url");
1035 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1038 if ($field->is_view
&& !$search) {
1039 $qf->freeze($elementName);
1044 * Delete the Custom Field.
1046 * @param object $field - the field object
1054 public static function deleteField($field) {
1055 CRM_Utils_System
::flushCache();
1057 // first delete the custom option group and values associated with this field
1058 if ($field->option_group_id
) {
1059 //check if option group is related to any other field, if
1060 //not delete the option group and related option values
1061 self
::checkOptionGroup($field->option_group_id
);
1064 // next drop the column from the custom value table
1065 self
::createField($field, 'delete');
1068 CRM_Core_BAO_UFField
::delUFField($field->id
);
1069 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1075 * Given a custom field value, its id and the set of options
1076 * find the display value for this field
1078 * @param mixed $value the custom field value
1079 * @param int $id the custom field id
1080 * @param int $options the assoc array of option name/value pairs
1082 * @param int $contactID
1083 * @param int $fieldID
1085 * @return string the display value
1090 static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1091 $option = &$options[$id];
1092 $attributes = &$option['attributes'];
1093 $html_type = $attributes['html_type'];
1094 $data_type = $attributes['data_type'];
1095 $format = CRM_Utils_Array
::value('format', $attributes);
1097 return self
::getDisplayValueCommon($value,
1112 * @param null $format
1113 * @param int $contactID
1114 * @param int $fieldID
1116 * @return array|mixed|null|string
1118 static function getDisplayValueCommon($value,
1129 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1130 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1131 $html_type == 'Select' ||
1132 $html_type == 'CheckBox' ||
1133 $html_type == 'AdvMulti-Select' ||
1134 $html_type == 'Multi-Select'
1137 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1140 switch ($html_type) {
1142 if ($data_type == 'Boolean') {
1143 // Do not assume that if not yes means no.
1146 $display = ts('Yes');
1148 elseif ((string)$value === '0') {
1149 $display = ts('No');
1153 $display = CRM_Utils_Array
::value($value, $option);
1157 case 'Autocomplete-Select':
1158 if ($data_type == 'ContactReference' &&
1161 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1164 $display = CRM_Utils_Array
::value($value, $option);
1169 $display = CRM_Utils_Array
::value($value, $option);
1173 case 'AdvMulti-Select':
1174 case 'Multi-Select':
1175 if (is_array($value)) {
1176 $checkedData = $value;
1179 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1180 substr($value, 1, -1)
1182 if ($html_type == 'CheckBox') {
1184 foreach ($checkedData as $v) {
1187 $checkedData = $newData;
1193 foreach ($checkedData as $key => $val) {
1194 if ($html_type == 'CheckBox') {
1197 $v[] = CRM_Utils_Array
::value($key, $option);
1202 $v[] = CRM_Utils_Array
::value($val, $option);
1206 $display = implode(', ', $v);
1211 if (is_array($value)) {
1212 foreach ($value as $key => $val) {
1213 $display[$key] = CRM_Utils_Date
::customFormat($val);
1217 // remove time element display if time is not set
1218 if (empty($option['attributes']['time_format'])) {
1219 $value = substr($value, 0, 10);
1221 $display = CRM_Utils_Date
::customFormat($value);
1225 case 'Select State/Province':
1226 if (empty($value)) {
1230 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1234 case 'Multi-Select State/Province':
1235 if (is_array($value)) {
1236 $checkedData = $value;
1239 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1240 substr($value, 1, -1)
1244 $states = CRM_Core_PseudoConstant
::stateProvince();
1246 foreach ($checkedData as $stateID) {
1250 $display .= $states[$stateID];
1254 case 'Select Country':
1255 if (empty($value)) {
1259 $display = CRM_Core_PseudoConstant
::country($value);
1263 case 'Multi-Select Country':
1264 if (is_array($value)) {
1265 $checkedData = $value;
1268 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1269 substr($value, 1, -1)
1273 $countries = CRM_Core_PseudoConstant
::country();
1275 foreach ($checkedData as $countryID) {
1279 $display .= $countries[$countryID];
1285 $url = self
::getFileURL($contactID, $fieldID, $value);
1287 $display = $url['file_url'];
1293 if (empty($value)) {
1297 $display = nl2br($value);
1302 if (empty($value)) {
1309 return $display ?
$display : $value;
1313 * Set default values for custom data used in profile
1315 * @param int $customFieldId custom field id
1316 * @param string $elementName custom field name
1317 * @param array $defaults associated array of fields
1318 * @param int $contactId contact id
1319 * @param int $mode profile mode
1320 * @param mixed $value if passed - dont fetch value from db,
1321 * just format the given value
1326 static function setProfileDefaults($customFieldId,
1333 //get the type of custom field
1334 $customField = new CRM_Core_BAO_CustomField();
1335 $customField->id
= $customFieldId;
1336 $customField->find(TRUE);
1339 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1340 $value = $customField->default_value
;
1344 if (!isset($value)) {
1345 $info = self
::getTableColumnGroup($customFieldId);
1346 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1347 $result = CRM_Core_DAO
::executeQuery($query);
1348 if ($result->fetch()) {
1349 $value = $result->value
;
1353 if ($customField->data_type
== 'Country') {
1355 $config = CRM_Core_Config
::singleton();
1356 if ($config->defaultContactCountry
) {
1357 $value = $config->defaultContactCountry();
1363 //set defaults if mode is registration
1364 if (!trim($value) &&
1366 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1368 $value = $customField->default_value
;
1371 if ($customField->data_type
== 'Money' && isset($value)) {
1372 $value = number_format($value, 2);
1374 switch ($customField->html_type
) {
1376 case 'AdvMulti-Select':
1377 case 'Multi-Select':
1378 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1379 $defaults[$elementName] = array();
1380 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1381 substr($value, 1, -1)
1383 foreach ($customOption as $val) {
1384 if (in_array($val['value'], $checkedValue)) {
1385 if ($customField->html_type
== 'CheckBox') {
1386 $defaults[$elementName][$val['value']] = 1;
1388 elseif ($customField->html_type
== 'Multi-Select' ||
1389 $customField->html_type
== 'AdvMulti-Select'
1391 $defaults[$elementName][$val['value']] = $val['value'];
1399 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1402 $customField->date_format
,
1403 $customField->time_format
1408 case 'Autocomplete-Select':
1409 if ($customField->data_type
== 'ContactReference') {
1410 if (is_numeric($value)) {
1411 $defaults[$elementName . '_id'] = $value;
1412 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1416 $defaults[$elementName] = $value;
1421 $defaults[$elementName] = $value;
1426 * @param int $contactID
1428 * @param int $fileID
1429 * @param bool $absolute
1434 * @param int $contactID
1436 * @param int $fileID
1437 * @param bool $absolute
1441 static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1444 $params = array('id' => $cfID);
1445 $defaults = array();
1446 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1447 $columnName = $defaults['column_name'];
1449 //table name of custom data
1450 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1451 $defaults['custom_group_id'],
1455 //query to fetch id from civicrm_file
1456 if ($multiRecordWhereClause) {
1457 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1460 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1462 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1467 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1472 $result['file_id'] = $fileID;
1474 if ($fileType == 'image/jpeg' ||
1475 $fileType == 'image/pjpeg' ||
1476 $fileType == 'image/gif' ||
1477 $fileType == 'image/x-png' ||
1478 $fileType == 'image/png'
1480 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1485 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1486 list($imageWidth, $imageHeight) = getimagesize($path);
1487 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1488 $url = CRM_Utils_System
::url('civicrm/file',
1489 "reset=1&id=$fileID&eid=$contactID",
1490 $absolute, NULL, TRUE, TRUE
1492 $result['file_url'] = "
1493 <a href=\"$url\" class='crm-image-popup'>
1494 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1496 // for non image files
1499 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1503 $url = CRM_Utils_System
::url('civicrm/file',
1504 "reset=1&id=$fileID&eid=$contactID",
1505 $absolute, NULL, TRUE, TRUE
1507 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1515 * Format custom fields before inserting
1517 * @param int $customFieldId custom field id
1518 * @param array $customFormatted formatted array
1519 * @param mix $value value of custom field
1520 * @param string $customFieldExtend custom field extends
1521 * @param int $customValueId custom option value id
1522 * @param int $entityId entity id (contribution, membership...)
1523 * @param boolean $inline consider inline custom groups only
1524 * @param boolean $checkPermission if false, do not include permissioning clause
1525 * @param boolean $includeViewOnly if true, fields marked 'View Only' are included. Required for APIv3.
1527 * @return array $customFormatted formatted custom field array
1530 static function formatCustomField($customFieldId, &$customFormatted, $value,
1531 $customFieldExtend, $customValueId = NULL,
1534 $checkPermission = TRUE,
1535 $includeViewOnly = false
1537 //get the custom fields for the entity
1538 //subtype and basic type
1539 $customDataSubType = NULL;
1540 if (is_array($customFieldExtend)) {
1541 $customFieldExtend = $customFieldExtend[0];
1544 if (in_array($customFieldExtend,
1545 CRM_Contact_BAO_ContactType
::subTypes()
1547 // This is the case when getFieldsForImport() requires fields
1548 // of subtype and its parent.CRM-5143
1549 $customDataSubType = $customFieldExtend;
1550 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1553 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1563 if (!array_key_exists($customFieldId, $customFields)) {
1567 // return if field is a 'code' field
1568 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1572 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1574 if (!$customValueId &&
1575 // we always create new entites for is_multiple unless specified
1576 !$customFields[$customFieldId]['is_multiple'] &&
1582 WHERE entity_id={$entityId}";
1584 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1587 //fix checkbox, now check box always submits values
1588 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1590 // Note that only during merge this is not an array, and you can directly use value
1591 if (is_array($value)) {
1592 $selectedValues = array();
1593 foreach ($value as $selId => $val) {
1595 $selectedValues[] = $selId;
1598 if (!empty($selectedValues)) {
1599 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1601 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1610 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1611 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1614 // Note that only during merge this is not an array,
1615 // and you can directly use value, CRM-4385
1616 if (is_array($value)) {
1617 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1618 array_values($value)
1619 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1627 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1628 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1629 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1631 $customFields[$customFieldId]['data_type'] == 'String' &&
1632 !empty($customFields[$customFieldId]['text_length']) &&
1635 // lets make sure that value is less than the length, else we'll
1636 // be losing some data, CRM-7481
1637 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1638 // need to do a few things here
1640 // 1. lets find a new length
1641 $newLength = $customFields[$customFieldId]['text_length'];
1642 $minLength = strlen($value);
1643 while ($newLength < $minLength) {
1644 $newLength = $newLength * 2;
1647 // set the custom field meta data to have a length larger than value
1648 // alter the custom value table column to match this length
1649 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1654 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1655 if (!CRM_Utils_System
::isNull($value)) {
1656 $format = $customFields[$customFieldId]['date_format'];
1657 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1662 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1663 $customFields[$customFieldId]['data_type'] == 'Money'
1669 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1670 $value = CRM_Utils_Rule
::cleanMoney($value);
1674 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1675 $customFields[$customFieldId]['data_type'] == 'Country'
1685 if ($customFields[$customFieldId]['data_type'] == 'File') {
1686 if (empty($value)) {
1690 $config = CRM_Core_Config
::singleton();
1692 $fName = $value['name'];
1693 $mimeType = $value['type'];
1695 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1697 // rename this file to go into the secure directory
1698 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1699 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1702 if ($customValueId) {
1707 $params = array(1 => array($customValueId, 'Integer'));
1708 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1711 $fileDAO = new CRM_Core_DAO_File();
1714 $fileDAO->id
= $fileId;
1717 $fileDAO->uri
= $filename;
1718 $fileDAO->mime_type
= $mimeType;
1719 $fileDAO->upload_date
= date('Ymdhis');
1721 $fileId = $fileDAO->id
;
1725 if (!is_array($customFormatted)) {
1726 $customFormatted = array();
1729 if (!array_key_exists($customFieldId, $customFormatted)) {
1730 $customFormatted[$customFieldId] = array();
1734 if ($customValueId) {
1735 $index = $customValueId;
1738 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1739 $customFormatted[$customFieldId][$index] = array();
1741 $customFormatted[$customFieldId][$index] = array(
1742 'id' => $customValueId > 0 ?
$customValueId : NULL,
1744 'type' => $customFields[$customFieldId]['data_type'],
1745 'custom_field_id' => $customFieldId,
1746 'custom_group_id' => $groupID,
1747 'table_name' => $tableName,
1748 'column_name' => $columnName,
1749 'file_id' => $fileId,
1750 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1753 //we need to sort so that custom fields are created in the order of entry
1754 krsort($customFormatted[$customFieldId]);
1755 return $customFormatted;
1759 * @param array $params
1763 static function &defaultCustomTableSchema(&$params) {
1764 // add the id and extends_id
1766 'name' => $params['name'],
1767 'is_multiple' => $params['is_multiple'],
1768 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1772 'type' => 'int unsigned',
1775 'attributes' => 'AUTO_INCREMENT',
1776 'comment' => 'Default MySQL primary key',
1779 'name' => 'entity_id',
1780 'type' => 'int unsigned',
1782 'comment' => 'Table that this extends',
1783 'fk_table_name' => $params['extends_name'],
1784 'fk_field_name' => 'id',
1785 'fk_attributes' => 'ON DELETE CASCADE',
1790 if (!$params['is_multiple']) {
1791 $table['indexes'] = array(
1794 'field_name_1' => 'entity_id',
1804 * @param bool $indexExist
1805 * @param bool $triggerRebuild
1807 static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1808 $tableName = CRM_Core_DAO
::getFieldValue(
1809 'CRM_Core_DAO_CustomGroup',
1810 $field->custom_group_id
,
1815 'table_name' => $tableName,
1816 'operation' => $operation,
1817 'name' => $field->column_name
,
1818 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1822 'required' => $field->is_required
,
1823 'searchable' => $field->is_searchable
,
1826 if ($operation == 'delete') {
1827 $fkName = "{$tableName}_{$field->column_name}";
1828 if (strlen($fkName) >= 48) {
1829 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1831 $params['fkName'] = $fkName;
1833 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1834 $params['fk_table_name'] = 'civicrm_country';
1835 $params['fk_field_name'] = 'id';
1836 $params['fk_attributes'] = 'ON DELETE SET NULL';
1838 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1839 $params['type'] = 'varchar(255)';
1841 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1842 $params['fk_table_name'] = 'civicrm_state_province';
1843 $params['fk_field_name'] = 'id';
1844 $params['fk_attributes'] = 'ON DELETE SET NULL';
1846 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1847 $params['type'] = 'varchar(255)';
1849 elseif ($field->data_type
== 'File') {
1850 $params['fk_table_name'] = 'civicrm_file';
1851 $params['fk_field_name'] = 'id';
1852 $params['fk_attributes'] = 'ON DELETE SET NULL';
1854 elseif ($field->data_type
== 'ContactReference') {
1855 $params['fk_table_name'] = 'civicrm_contact';
1856 $params['fk_field_name'] = 'id';
1857 $params['fk_attributes'] = 'ON DELETE SET NULL';
1859 if (isset($field->default_value
)) {
1860 $params['default'] = "'{$field->default_value}'";
1863 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1867 * Determine whether it would be safe to move a field
1869 * @param int $fieldID FK to civicrm_custom_field
1870 * @param int $newGroupID FK to civicrm_custom_group
1875 static function _moveFieldValidate($fieldID, $newGroupID) {
1878 $field = new CRM_Core_DAO_CustomField();
1879 $field->id
= $fieldID;
1880 if (!$field->find(TRUE)) {
1881 $errors['fieldID'] = 'Invalid ID for custom field';
1885 $oldGroup = new CRM_Core_DAO_CustomGroup();
1886 $oldGroup->id
= $field->custom_group_id
;
1887 if (!$oldGroup->find(TRUE)) {
1888 $errors['fieldID'] = 'Invalid ID for old custom group';
1892 $newGroup = new CRM_Core_DAO_CustomGroup();
1893 $newGroup->id
= $newGroupID;
1894 if (!$newGroup->find(TRUE)) {
1895 $errors['newGroupID'] = 'Invalid ID for new custom group';
1901 FROM civicrm_custom_field a
1902 INNER JOIN civicrm_custom_field b
1904 AND a.label = b.label
1905 AND b.custom_group_id = %2
1908 1 => array($field->id
, 'Integer'),
1909 2 => array($newGroup->id
, 'Integer'),
1911 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1913 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1916 $tableName = $oldGroup->table_name
;
1917 $columnName = $field->column_name
;
1922 WHERE $columnName is not null
1924 $count = CRM_Core_DAO
::singleValueQuery($query,
1925 CRM_Core_DAO
::$_nullArray
1930 FROM civicrm_custom_group
1931 WHERE id IN ( %1, %2 )
1933 $params = array(1 => array($oldGroup->id
, 'Integer'),
1934 2 => array($newGroup->id
, 'Integer'),
1937 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1939 while ($dao->fetch()) {
1940 $extends[] = $dao->extends;
1942 if ($extends[0] != $extends[1]) {
1943 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1947 return empty($errors) ?
TRUE : $errors;
1951 * Move a custom data field from one group (table) to another
1953 * @param int $fieldID FK to civicrm_custom_field
1954 * @param int $newGroupID FK to civicrm_custom_group
1958 static function moveField($fieldID, $newGroupID) {
1959 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1960 if (TRUE !== $validation) {
1961 CRM_Core_Error
::fatal(implode(' ', $validation));
1963 $field = new CRM_Core_DAO_CustomField();
1964 $field->id
= $fieldID;
1967 $newGroup = new CRM_Core_DAO_CustomGroup();
1968 $newGroup->id
= $newGroupID;
1969 $newGroup->find(TRUE);
1971 $oldGroup = new CRM_Core_DAO_CustomGroup();
1972 $oldGroup->id
= $field->custom_group_id
;
1973 $oldGroup->find(TRUE);
1976 $add->custom_group_id
= $newGroup->id
;
1977 self
::createField($add, 'add');
1979 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1980 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1981 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1983 CRM_Core_DAO
::executeQuery($sql);
1986 $del->custom_group_id
= $oldGroup->id
;
1987 self
::createField($del, 'delete');
1991 CRM_Utils_System
::flushCache();
1995 * Get the database table name and column name for a custom field
1997 * @param int $fieldID - the fieldID of the custom field
1998 * @param boolean $force - force the sql to be run again (primarily used for tests)
2000 * @return array - fatal is fieldID does not exists, else array of tableName, columnName
2004 static function getTableColumnGroup($fieldID, $force = FALSE) {
2005 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2006 $cache = CRM_Utils_Cache
::singleton();
2007 $fieldValues = $cache->get($cacheKey);
2008 if (empty($fieldValues) ||
$force) {
2010 SELECT cg.table_name, cf.column_name, cg.id
2011 FROM civicrm_custom_group cg,
2012 civicrm_custom_field cf
2013 WHERE cf.custom_group_id = cg.id
2015 $params = array(1 => array($fieldID, 'Integer'));
2016 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2018 if (!$dao->fetch()) {
2019 CRM_Core_Error
::fatal();
2022 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2023 $cache->set($cacheKey, $fieldValues);
2025 return $fieldValues;
2029 * Get custom option groups
2031 * @param array $includeFieldIds ids of custom fields for which
2032 * option groups must be included.
2034 * Currently this is required in the cases where option groups are to be included
2035 * for inactive fields : CRM-5369
2039 * @return mixed $customOptionGroup@static
2041 public static function &customOptionGroup($includeFieldIds = NULL) {
2042 static $customOptionGroup = NULL;
2044 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2045 if ($cacheKey == 'force') {
2046 $customOptionGroup[$cacheKey] = NULL;
2049 if (empty($customOptionGroup[$cacheKey])) {
2050 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2052 //support for single as well as array format.
2053 if (!empty($includeFieldIds)) {
2054 if (is_array($includeFieldIds)) {
2055 $includeFieldIds = implode(',', $includeFieldIds);
2057 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2061 SELECT g.id, g.title
2062 FROM civicrm_option_group g
2063 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2064 WHERE {$whereClause}";
2066 $dao = CRM_Core_DAO
::executeQuery($query);
2067 while ($dao->fetch()) {
2068 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2072 return $customOptionGroup[$cacheKey];
2078 * @param int $customFieldId custom field id
2079 * @param int $optionGroupId option group id
2085 static function fixOptionGroups($customFieldId, $optionGroupId) {
2086 // check if option group belongs to any custom Field else delete
2087 // get the current option group
2088 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2092 // get the updated option group
2093 // if both are same return
2094 if ($currentOptionGroupId == $optionGroupId) {
2098 // check if option group is related to any other field
2099 self
::checkOptionGroup($currentOptionGroupId);
2103 * Check if option group is related to more than one
2106 * @param int $optionGroupId option group id
2111 static function checkOptionGroup($optionGroupId) {
2114 FROM civicrm_custom_field
2115 WHERE option_group_id = {$optionGroupId}";
2117 $count = CRM_Core_DAO
::singleValueQuery($query);
2120 //delete the option group
2121 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2126 * @param int $optionGroupId
2129 * @return null|string
2131 static function getOptionGroupDefault($optionGroupId, $htmlType) {
2133 SELECT default_value, html_type
2134 FROM civicrm_custom_field
2135 WHERE option_group_id = {$optionGroupId}
2136 AND default_value IS NOT NULL
2137 ORDER BY html_type";
2139 $dao = CRM_Core_DAO
::executeQuery($query);
2140 $defaultValue = NULL;
2141 $defaultHTMLType = NULL;
2142 while ($dao->fetch()) {
2143 if ($dao->html_type
== $htmlType) {
2144 return $dao->default_value
;
2146 if ($defaultValue == NULL) {
2147 $defaultValue = $dao->default_value
;
2148 $defaultHTMLType = $dao->html_type
;
2152 // some conversions are needed if either the old or new has a html type which has potential
2153 // multiple default values.
2154 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2155 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2157 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2159 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2160 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2162 $defaultValue = substr($defaultValue, 1, -1);
2163 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2164 substr($defaultValue, 1, -1)
2166 $defaultValue = $values[0];
2169 return $defaultValue;
2173 * @param array $params
2174 * @param $customFields
2175 * @param int $entityID
2176 * @param $customFieldExtends
2177 * @param bool $inline
2181 static function postProcess(&$params,
2184 $customFieldExtends,
2187 $customData = array();
2189 foreach ($params as $key => $value) {
2190 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2192 // for autocomplete transfer hidden value instead of label
2193 if ($params[$key] && isset($params[$key . '_id'])) {
2194 $value = $params[$key . '_id'];
2197 // we need to append time with date
2198 if ($params[$key] && isset($params[$key . '_time'])) {
2199 $value .= ' ' . $params[$key . '_time'];
2202 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2205 $customFieldExtends,
2206 $customFieldInfo[1],
2221 static function buildOption($field, &$options) {
2222 // Fixme - adding anything but options to the $options array is a bad idea
2223 // What if an option had the key 'attributes'?
2224 $options['attributes'] = array(
2225 'label' => $field['label'],
2226 'data_type' => $field['data_type'],
2227 'html_type' => $field['html_type'],
2230 $optionGroupID = NULL;
2231 if (($field['html_type'] == 'CheckBox' ||
2232 $field['html_type'] == 'Radio' ||
2233 $field['html_type'] == 'Select' ||
2234 $field['html_type'] == 'AdvMulti-Select' ||
2235 $field['html_type'] == 'Multi-Select' ||
2236 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2238 if ($field['option_group_id']) {
2239 $optionGroupID = $field['option_group_id'];
2241 elseif ($field['data_type'] != 'Boolean') {
2242 CRM_Core_Error
::fatal();
2246 // build the cache for custom values with options (label => value)
2247 if ($optionGroupID != NULL) {
2250 FROM civicrm_option_value
2251 WHERE option_group_id = $optionGroupID
2254 $dao = CRM_Core_DAO
::executeQuery($query);
2255 while ($dao->fetch()) {
2256 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2257 $num = round($dao->value
, 2);
2258 $options["$num"] = $dao->label
;
2261 $options[$dao->value
] = $dao->label
;
2265 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2270 * @param $fieldLabel
2271 * @param null $groupTitle
2275 static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2276 $params = array(1 => array($fieldLabel, 'String'));
2278 $params[2] = array($groupTitle, 'String');
2281 FROM civicrm_custom_field f
2282 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2283 WHERE ( f.label = %1 OR f.name = %1 )
2284 AND ( g.title = %2 OR g.name = %2 )
2290 FROM civicrm_custom_field f
2291 WHERE ( f.label = %1 OR f.name = %1 )
2295 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2296 if ($dao->fetch() &&
2307 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2310 static function getNameFromID($ids) {
2311 if (is_array($ids)) {
2312 $ids = implode(',', $ids);
2315 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2316 FROM civicrm_custom_field f
2317 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2318 WHERE f.id IN ($ids)";
2321 $dao = CRM_Core_DAO
::executeQuery($sql);
2323 while ($dao->fetch()) {
2324 $result[$dao->id
] = array(
2325 'field_name' => $dao->field_name
,
2326 'field_label' => $dao->field_label
,
2327 'group_name' => $dao->group_name
,
2328 'group_title' => $dao->group_title
,
2335 * Validate custom data.
2337 * @param array $params custom data submitted.
2338 * ie array( 'custom_1' => 'validate me' );
2340 * @return array $errors validation errors.
2343 static function validateCustomData($params) {
2345 if (!is_array($params) ||
empty($params)) {
2350 //pick up profile fields.
2351 $profileFields = array();
2352 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2354 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2356 CRM_Core_Action
::VIEW
2360 //lets start w/ params.
2361 foreach ($params as $key => $value) {
2362 $customFieldID = self
::getKeyID($key);
2363 if (!$customFieldID) {
2367 //load the structural info for given field.
2368 $field = new CRM_Core_DAO_CustomField();
2369 $field->id
= $customFieldID;
2370 if (!$field->find(TRUE)) {
2373 $dataType = $field->data_type
;
2375 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2376 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2377 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2379 $fieldTitle = $field->label
;
2382 //no need to validate.
2383 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2387 //lets validate first for required field.
2388 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2389 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2393 //now time to take care of custom field form rules.
2394 $ruleName = $errorMsg = NULL;
2395 switch ($dataType) {
2397 $ruleName = 'integer';
2398 $errorMsg = ts('%1 must be an integer (whole number).',
2399 array(1 => $fieldTitle)
2404 $ruleName = 'money';
2405 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2406 array(1 => $fieldTitle)
2411 $ruleName = 'numeric';
2412 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2413 array(1 => $fieldTitle)
2418 $ruleName = 'wikiURL';
2419 $errorMsg = ts('%1 must be valid Website.',
2420 array(1 => $fieldTitle)
2425 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2427 $funName = "CRM_Utils_Rule::{$ruleName}";
2428 if (is_callable($funName)) {
2429 $valid = call_user_func($funName, $value);
2432 $errors[$key] = $errorMsg;
2441 * @param int $customId
2445 static function isMultiRecordField($customId) {
2446 $isMultipleWithGid = FALSE;
2447 if (!is_numeric($customId)) {
2448 $customId = self
::getKeyID($customId);
2450 if (is_numeric($customId)) {
2451 $sql = "SELECT cg.id cgId
2452 FROM civicrm_custom_group cg
2453 INNER JOIN civicrm_custom_field cf
2454 ON cg.id = cf.custom_group_id
2455 WHERE cf.id = %1 AND cg.is_multiple = 1";
2456 $params[1] = array($customId, 'Integer');
2457 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2458 if ($dao->fetch()) {
2460 $isMultipleWithGid = $dao->cgId
;
2465 return $isMultipleWithGid;
2469 * Does this field store a serialized string?
2470 * @param CRM_Core_DAO_CustomField|array $field
2473 static function isSerialized($field) {
2474 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2475 $field = (array) $field;
2476 // 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.
2477 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);