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) {
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 * Takes a bunch of params that are needed to match certain criteria and
317 * retrieves the relevant objects. Typically the valid params are only
318 * contact_id. We'll tweak this function to be more full featured over a period
319 * of time. This is the inverse function of create. It also stores all the retrieved
320 * values in the default array
322 * @param array $params (reference ) an assoc array of name/value pairs
323 * @param array $defaults (reference ) an assoc array to hold the flattened values
325 * @return object CRM_Core_DAO_CustomField object
329 static function retrieve(&$params, &$defaults) {
330 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
334 * update the is_active flag in the db
336 * @param int $id Id of the database record
337 * @param boolean $is_active Value we want to set the is_active field
339 * @return Object DAO object on sucess, null otherwise
344 static function setIsActive($id, $is_active) {
346 CRM_Utils_System
::flushCache();
348 //enable-disable CustomField
349 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
350 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
354 * Get the field title.
356 * @param int $id id of field.
358 * @return string name
364 public static function getTitle($id) {
365 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
369 * Store and return an array of all active custom fields.
371 * @param string $customDataType type of Custom Data; empty is a synonym for "all contact data types"
372 * @param boolean $showAll If true returns all fields (includes disabled fields)
373 * @param boolean $inline If true returns all inline fields (includes disabled fields)
374 * @param int $customDataSubType Custom Data sub type value
375 * @param int $customDataSubName Custom Data sub name value
376 * @param boolean $onlyParent return only top level custom data, for eg, only Participant and ignore subname and subtype
377 * @param boolean $onlySubType return only custom data for subtype
378 * @param boolean $checkPermission if false, do not include permissioning clause
380 * @return array $fields - an array of active custom fields.
385 public static function &getFields($customDataType = 'Individual',
388 $customDataSubType = NULL,
389 $customDataSubName = NULL,
391 $onlySubType = FALSE,
392 $checkPermission = TRUE
394 if (empty($customDataType)) {
395 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
397 if ($customDataType && !is_array($customDataType)) {
399 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
400 // This is the case when getFieldsForImport() requires fields
401 // limited strictly to a subtype.
402 $customDataSubType = $customDataType;
403 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
407 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
408 // this makes the method flexible to support retrieving fields
409 // for multiple extends value.
410 $customDataType = array($customDataType);
414 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
416 if (is_array($customDataType)) {
417 $cacheKey = implode('_', $customDataType);
420 $cacheKey = $customDataType;
423 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
424 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
425 $cacheKey .= $showAll ?
'_1' : '_0';
426 $cacheKey .= $inline ?
'_1_' : '_0_';
427 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
428 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
429 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
431 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
433 // also get the permission stuff here
434 if ($checkPermission) {
435 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
440 $permissionClause = '(1)';
443 // lets md5 permission clause and take first 8 characters
444 $cacheKey .= substr(md5($permissionClause), 0, 8);
446 if (strlen($cacheKey) > 40) {
447 $cacheKey = md5($cacheKey);
450 if (!self
::$_importFields ||
451 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
453 if (!self
::$_importFields) {
454 self
::$_importFields = array();
457 // check if we can retrieve from database cache
458 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
460 if ($fields === NULL) {
461 $cfTable = self
::getTableName();
464 if (is_array($customDataType)) {
466 foreach ($customDataType as $dataType) {
467 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
468 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
469 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
472 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
474 $value = $value ?
$value . ", {$val}" : $val;
478 $extends = "AND $cgTable.extends IN ( $value ) ";
482 if (!empty($customDataType) && empty($extends)) {
483 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
484 self
::$_importFields[$cacheKey] = array();
485 return self
::$_importFields[$cacheKey];
489 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
492 $query = "SELECT $cfTable.id, $cfTable.label,
496 $cfTable.default_value,
497 $cfTable.options_per_line, $cfTable.text_length,
498 $cfTable.custom_group_id,
499 $cfTable.is_required,
500 $cgTable.extends, $cfTable.is_search_range,
501 $cgTable.extends_entity_column_value,
502 $cgTable.extends_entity_column_id,
504 $cfTable.option_group_id,
505 $cfTable.date_format,
506 $cfTable.time_format,
510 ON $cfTable.custom_group_id = $cgTable.id
514 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
518 $query .= " AND $cgTable.style = 'Inline' ";
521 //get the custom fields for specific type in
522 //combination with fields those support any type.
523 if (!empty($customDataSubType)) {
524 $subtypeClause = array();
525 foreach ($customDataSubType as $subtype) {
526 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
527 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
530 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
532 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
535 if ($customDataSubName) {
536 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
539 // also get the permission stuff here
540 if ($checkPermission) {
541 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
546 $permissionClause = '(1)';
549 $query .= " $extends AND $permissionClause
550 ORDER BY $cgTable.weight, $cgTable.title,
551 $cfTable.weight, $cfTable.label";
553 $dao = CRM_Core_DAO
::executeQuery($query);
556 while (($dao->fetch()) != NULL) {
557 $fields[$dao->id
]['label'] = $dao->label
;
558 $fields[$dao->id
]['groupTitle'] = $dao->title
;
559 $fields[$dao->id
]['data_type'] = $dao->data_type
;
560 $fields[$dao->id
]['html_type'] = $dao->html_type
;
561 $fields[$dao->id
]['default_value'] = $dao->default_value
;
562 $fields[$dao->id
]['text_length'] = $dao->text_length
;
563 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
564 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
565 $fields[$dao->id
]['extends'] = $dao->extends;
566 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
567 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
568 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
569 $fields[$dao->id
]['is_view'] = $dao->is_view
;
570 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
571 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
572 $fields[$dao->id
]['date_format'] = $dao->date_format
;
573 $fields[$dao->id
]['time_format'] = $dao->time_format
;
574 $fields[$dao->id
]['is_required'] = $dao->is_required
;
577 CRM_Core_BAO_Cache
::setItem($fields,
579 "custom importableFields $cacheKey"
582 self
::$_importFields[$cacheKey] = $fields;
585 return self
::$_importFields[$cacheKey];
589 * Return the field ids and names (with groups) for import purpose.
591 * @param int|string $contactType Contact type
592 * @param boolean $showAll If true returns all fields (includes disabled fields)
593 * @param boolean $onlyParent return fields ONLY related to basic types
594 * @param boolean $search when called from search and multiple records need to be returned
595 * @param boolean $checkPermission if false, do not include permissioning clause
597 * @param bool $withMultiple
599 * @return array $fields -
604 public static function &getFieldsForImport($contactType = 'Individual',
608 $checkPermission = TRUE,
609 $withMultiple = FALSE
611 // Note: there are situations when we want getFieldsForImport() return fields related
612 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
613 $fields = &self
::getFields($contactType,
623 $importableFields = array();
624 foreach ($fields as $id => $values) {
625 // for now we should not allow multiple fields in profile / export etc, hence unsetting
627 (!empty($values['is_multiple']) && !$withMultiple)
632 /* generate the key for the fields array */
636 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
637 $importableFields[$key] = array(
639 'title' => CRM_Utils_Array
::value('label', $values),
640 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
642 'custom_field_id' => $id,
643 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
644 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
645 'data_type' => CRM_Utils_Array
::value('data_type', $values),
646 'html_type' => CRM_Utils_Array
::value('html_type', $values),
647 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
650 // CRM-6681, pass date and time format when html_type = Select Date
651 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
652 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
653 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
657 return $importableFields;
661 * Get the field id from an import key
663 * @param string $key The key to parse
666 * @return int|null The id (if exists)
670 public static function getKeyID($key, $all = FALSE) {
672 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
679 CRM_Utils_Array
::value(2, $match),
683 return $all ?
array(NULL, NULL) : NULL;
687 * Use the cache to get all values of a specific custom field
689 * @param int $fieldID the custom field ID
691 * @return CRM_Core_DAO_CustomField $field the field object
695 static function getFieldObject($fieldID) {
696 $field = new CRM_Core_DAO_CustomField();
698 // check if we can get the field values from the system cache
699 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
700 $cache = CRM_Utils_Cache
::singleton();
701 $fieldValues = $cache->get($cacheKey);
702 if (empty($fieldValues)) {
703 $field->id
= $fieldID;
704 if (!$field->find(TRUE)) {
705 CRM_Core_Error
::fatal();
708 $fieldValues = array();
709 CRM_Core_DAO
::storeValues($field, $fieldValues);
711 $cache->set($cacheKey, $fieldValues);
714 $field->copyValues($fieldValues);
721 * This function for building custom fields
723 * @param CRM_Core_Form $qf form object (reference)
724 * @param string $elementName name of the custom field
726 * @param boolean $inactiveNeeded -deprecated
727 * @param bool $useRequired
728 * @param boolean $search true if used for search else false
729 * @param string $label label for custom field
731 * @internal param bool $userRequired true if required else false
735 public static function addQuickFormElement(&$qf,
738 $inactiveNeeded = FALSE,
743 $field = self
::getFieldObject($fieldId);
744 $widget = $field->html_type
;
746 // Custom field HTML should indicate group+field name
747 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
748 $dataCrmCustomVal = $groupName.':'.$field->name
;
749 $dataCrmCustomAttr = 'data-crm-custom="'.$dataCrmCustomVal.'"';
750 $field->attributes
.= $dataCrmCustomAttr;
752 // Fixed for Issue CRM-2183
753 if ($widget == 'TextArea' && $search) {
757 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
759 // FIXME: Why are select state/country separate widget types?
760 $isSelect = (in_array($widget, array('Select', 'Multi-Select', 'Select State/Province', 'Multi-Select State/Province', 'Select Country', 'Multi-Select Country', 'AdvMulti-Select', 'CheckBox', 'Radio')));
763 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array('field' => "custom_$fieldId", 'context' => $search ?
'search' : 'create'), array()));
765 // Consolidate widget types to simplify the below switch statement
766 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
769 $selectAttributes = array(
770 'data-crm-custom' => $dataCrmCustomVal,
771 'class' => 'crm-select2',
773 // Search field is always multi-select
774 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
775 $selectAttributes['class'] .= ' huge';
776 $selectAttributes['multiple'] = 'multiple';
777 $selectAttributes['placeholder'] = $placeholder;
779 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
780 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
781 $selectAttributes +
= array(
782 'data-api-entity' => 'contact', // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
783 'data-api-field' => 'custom_' . $field->id
,
784 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
789 if (!isset($label)) {
790 $label = $field->label
;
794 * at some point in time we might want to split the below into small functions
800 if ($field->is_search_range
&& $search) {
801 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
802 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
805 $element = &$qf->add('text', $elementName, $label,
807 $useRequired && !$search
813 $attributes = $dataCrmCustomAttr;
814 if ($field->note_rows
) {
815 $attributes .= 'rows=' . $field->note_rows
;
818 $attributes .= 'rows=4';
820 if ($field->note_columns
) {
821 $attributes .= ' cols=' . $field->note_columns
;
824 $attributes .= ' cols=60';
826 if ($field->text_length
) {
827 $attributes .= ' maxlength=' . $field->text_length
;
829 $element = &$qf->add('textarea',
833 $useRequired && !$search
838 if ($field->is_search_range
&& $search) {
839 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
841 'format' => $field->date_format
,
842 'timeFormat' => $field->time_format
,
843 'startOffset' => $field->start_date_years
,
844 'endOffset' => $field->end_date_years
,
845 'data-crm-custom' => $dataCrmCustomVal,
849 $qf->addDate($elementName . '_to', ts('To'), FALSE,
851 'format' => $field->date_format
,
852 'timeFormat' => $field->time_format
,
853 'startOffset' => $field->start_date_years
,
854 'endOffset' => $field->end_date_years
,
855 'data-crm-custom' => $dataCrmCustomVal,
860 $required = $useRequired && !$search;
862 $qf->addDate($elementName, $label, $required, array(
863 'format' => $field->date_format
,
864 'timeFormat' => $field->time_format
,
865 'startOffset' => $field->start_date_years
,
866 'endOffset' => $field->end_date_years
,
867 'data-crm-custom' => $dataCrmCustomVal,
874 foreach ($options as $v => $l) {
875 $choice[] = $qf->createElement('radio', NULL, '', $l, (string)$v, $field->attributes
);
877 $group = $qf->addGroup($choice, $elementName, $label);
878 if ($useRequired && !$search) {
879 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
882 $group->setAttribute('allowClear', TRUE);
886 // For all select elements
888 if (empty($selectAttributes['multiple'])) {
889 $options = array('' => $placeholder) +
$options;
891 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
893 // Add and/or option for fields that store multiple values
894 if ($search && self
::isSerialized($field)) {
897 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
898 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
900 $qf->addGroup($operators, $elementName . '_operator');
901 $qf->setDefaults(array($elementName . '_operator' => 'or'));
905 case 'AdvMulti-Select':
906 $include =& $qf->addElement(
913 'class' => 'advmultiselect',
914 'data-crm-custom' => $dataCrmCustomVal,
918 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
919 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
921 if ($useRequired && !$search) {
922 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
928 foreach ($options as $v => $l) {
929 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
931 $qf->addGroup($check, $elementName, $label);
932 if ($useRequired && !$search) {
933 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
938 // we should not build upload file in search mode
943 strtolower($field->html_type
),
947 $useRequired && !$search
949 $qf->addUploadElement($elementName);
952 case 'RichTextEditor':
953 $attributes = array('rows' => $field->note_rows
, 'cols' => $field->note_columns
, 'data-crm-custom' => $dataCrmCustomVal);
954 if ($field->text_length
) {
955 $attributes['maxlength'] = $field->text_length
;
957 $qf->addWysiwyg($elementName, $label, $attributes, $search);
960 case 'Autocomplete-Select':
961 static $customUrls = array();
962 // Fixme: why is this a string in the first place??
963 $attributes = array();
964 if ($field->attributes
) {
965 foreach(explode(' ', $field->attributes
) as $at) {
966 if (strpos($at, '=')) {
967 list($k, $v) = explode('=', $at);
968 $attributes[$k] = trim($v, ' "');
972 if ($field->data_type
== 'ContactReference') {
973 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
974 $attributes['data-api-entity'] = 'contact';
975 $qf->add('text', $elementName, $label, $attributes,
976 $useRequired && !$search
979 $urlParams = "context=customfield&id={$field->id}";
981 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
988 // FIXME: This won't work with customFieldOptions hook
989 $attributes +
= array(
990 'entity' => 'option_value',
991 'placeholder' => $placeholder,
992 'multiple' => $search,
994 'params' => array('option_group_id' => $field->option_group_id
),
997 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1000 $qf->assign('customUrls', $customUrls);
1004 switch ($field->data_type
) {
1006 // integers will have numeric rule applied to them.
1007 if ($field->is_search_range
&& $search) {
1008 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1009 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1011 elseif ($widget == 'Text') {
1012 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1017 if ($field->is_search_range
&& $search) {
1018 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1019 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1021 elseif ($widget == 'Text') {
1022 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1027 if ($field->is_search_range
&& $search) {
1028 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1029 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1031 elseif ($widget == 'Text') {
1032 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1037 $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
1038 $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
1039 $element->setAttribute('class', "url");
1040 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1043 if ($field->is_view
&& !$search) {
1044 $qf->freeze($elementName);
1049 * Delete the Custom Field.
1051 * @param object $field - the field object
1059 public static function deleteField($field) {
1060 CRM_Utils_System
::flushCache();
1062 // first delete the custom option group and values associated with this field
1063 if ($field->option_group_id
) {
1064 //check if option group is related to any other field, if
1065 //not delete the option group and related option values
1066 self
::checkOptionGroup($field->option_group_id
);
1069 // next drop the column from the custom value table
1070 self
::createField($field, 'delete');
1073 CRM_Core_BAO_UFField
::delUFField($field->id
);
1074 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1080 * Given a custom field value, its id and the set of options
1081 * find the display value for this field
1083 * @param mixed $value the custom field value
1084 * @param int $id the custom field id
1085 * @param int $options the assoc array of option name/value pairs
1087 * @param null $contactID
1088 * @param null $fieldID
1090 * @return string the display value
1095 static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1096 $option = &$options[$id];
1097 $attributes = &$option['attributes'];
1098 $html_type = $attributes['html_type'];
1099 $data_type = $attributes['data_type'];
1100 $format = CRM_Utils_Array
::value('format', $attributes);
1102 return self
::getDisplayValueCommon($value,
1117 * @param null $format
1118 * @param null $contactID
1119 * @param null $fieldID
1121 * @return array|mixed|null|string
1123 static function getDisplayValueCommon($value,
1134 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1135 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1136 $html_type == 'Select' ||
1137 $html_type == 'CheckBox' ||
1138 $html_type == 'AdvMulti-Select' ||
1139 $html_type == 'Multi-Select'
1142 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1145 switch ($html_type) {
1147 if ($data_type == 'Boolean') {
1148 // Do not assume that if not yes means no.
1151 $display = ts('Yes');
1153 elseif ((string)$value === '0') {
1154 $display = ts('No');
1158 $display = CRM_Utils_Array
::value($value, $option);
1162 case 'Autocomplete-Select':
1163 if ($data_type == 'ContactReference' &&
1166 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1169 $display = CRM_Utils_Array
::value($value, $option);
1174 $display = CRM_Utils_Array
::value($value, $option);
1178 case 'AdvMulti-Select':
1179 case 'Multi-Select':
1180 if (is_array($value)) {
1181 $checkedData = $value;
1184 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1185 substr($value, 1, -1)
1187 if ($html_type == 'CheckBox') {
1189 foreach ($checkedData as $v) {
1192 $checkedData = $newData;
1198 foreach ($checkedData as $key => $val) {
1199 if ($html_type == 'CheckBox') {
1202 $v[] = CRM_Utils_Array
::value($key, $option);
1207 $v[] = CRM_Utils_Array
::value($val, $option);
1211 $display = implode(', ', $v);
1216 if (is_array($value)) {
1217 foreach ($value as $key => $val) {
1218 $display[$key] = CRM_Utils_Date
::customFormat($val);
1222 // remove time element display if time is not set
1223 if (empty($option['attributes']['time_format'])) {
1224 $value = substr($value, 0, 10);
1226 $display = CRM_Utils_Date
::customFormat($value);
1230 case 'Select State/Province':
1231 if (empty($value)) {
1235 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1239 case 'Multi-Select State/Province':
1240 if (is_array($value)) {
1241 $checkedData = $value;
1244 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1245 substr($value, 1, -1)
1249 $states = CRM_Core_PseudoConstant
::stateProvince();
1251 foreach ($checkedData as $stateID) {
1255 $display .= $states[$stateID];
1259 case 'Select Country':
1260 if (empty($value)) {
1264 $display = CRM_Core_PseudoConstant
::country($value);
1268 case 'Multi-Select Country':
1269 if (is_array($value)) {
1270 $checkedData = $value;
1273 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1274 substr($value, 1, -1)
1278 $countries = CRM_Core_PseudoConstant
::country();
1280 foreach ($checkedData as $countryID) {
1284 $display .= $countries[$countryID];
1289 // In the context of displaying a profile, show file/image
1290 if ($contactID && $value) {
1291 $url = self
::getFileURL($contactID, $fieldID, $value);
1293 $display = $url['file_url'];
1296 // In other contexts show a paperclip icon
1298 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1299 $display = $icons[$value];
1304 if (empty($value)) {
1308 $display = nl2br($value);
1313 if (empty($value)) {
1320 return $display ?
$display : $value;
1324 * Function to set default values for custom data used in profile
1326 * @params int $customFieldId custom field id
1327 * @params string $elementName custom field name
1328 * @params array $defaults associated array of fields
1329 * @params int $contactId contact id
1330 * @param $customFieldId
1331 * @param $elementName
1333 * @param null $contactId
1334 * @param int $mode profile mode
1335 * @param mixed $value if passed - dont fetch value from db,
1336 * just format the given value
1341 static function setProfileDefaults($customFieldId,
1348 //get the type of custom field
1349 $customField = new CRM_Core_BAO_CustomField();
1350 $customField->id
= $customFieldId;
1351 $customField->find(TRUE);
1354 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1355 $value = $customField->default_value
;
1359 if (!isset($value)) {
1360 $info = self
::getTableColumnGroup($customFieldId);
1361 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1362 $result = CRM_Core_DAO
::executeQuery($query);
1363 if ($result->fetch()) {
1364 $value = $result->value
;
1368 if ($customField->data_type
== 'Country') {
1370 $config = CRM_Core_Config
::singleton();
1371 if ($config->defaultContactCountry
) {
1372 $value = $config->defaultContactCountry();
1378 //set defaults if mode is registration
1379 if (!trim($value) &&
1381 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1383 $value = $customField->default_value
;
1386 if ($customField->data_type
== 'Money' && isset($value)) {
1387 $value = number_format($value, 2);
1389 switch ($customField->html_type
) {
1391 case 'AdvMulti-Select':
1392 case 'Multi-Select':
1393 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1394 $defaults[$elementName] = array();
1395 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1396 substr($value, 1, -1)
1398 foreach ($customOption as $val) {
1399 if (in_array($val['value'], $checkedValue)) {
1400 if ($customField->html_type
== 'CheckBox') {
1401 $defaults[$elementName][$val['value']] = 1;
1403 elseif ($customField->html_type
== 'Multi-Select' ||
1404 $customField->html_type
== 'AdvMulti-Select'
1406 $defaults[$elementName][$val['value']] = $val['value'];
1414 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1417 $customField->date_format
,
1418 $customField->time_format
1423 case 'Autocomplete-Select':
1424 if ($customField->data_type
== 'ContactReference') {
1425 if (is_numeric($value)) {
1426 $defaults[$elementName . '_id'] = $value;
1427 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1431 $defaults[$elementName] = $value;
1436 $defaults[$elementName] = $value;
1443 * @param null $fileID
1444 * @param bool $absolute
1451 * @param null $fileID
1452 * @param bool $absolute
1456 static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1459 $params = array('id' => $cfID);
1460 $defaults = array();
1461 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1462 $columnName = $defaults['column_name'];
1464 //table name of custom data
1465 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1466 $defaults['custom_group_id'],
1470 //query to fetch id from civicrm_file
1471 if ($multiRecordWhereClause) {
1472 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1475 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1477 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1482 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1487 $result['file_id'] = $fileID;
1489 if ($fileType == 'image/jpeg' ||
1490 $fileType == 'image/pjpeg' ||
1491 $fileType == 'image/gif' ||
1492 $fileType == 'image/x-png' ||
1493 $fileType == 'image/png'
1495 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1500 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1501 list($imageWidth, $imageHeight) = getimagesize($path);
1502 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1503 $url = CRM_Utils_System
::url('civicrm/file',
1504 "reset=1&id=$fileID&eid=$contactID",
1505 $absolute, NULL, TRUE, TRUE
1507 $result['file_url'] = "
1508 <a href=\"$url\" class='crm-image-popup'>
1509 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1511 // for non image files
1514 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1518 $url = CRM_Utils_System
::url('civicrm/file',
1519 "reset=1&id=$fileID&eid=$contactID",
1520 $absolute, NULL, TRUE, TRUE
1522 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1530 * Format custom fields before inserting
1532 * @param int $customFieldId custom field id
1533 * @param array $customFormatted formatted array
1534 * @param mix $value value of custom field
1535 * @param string $customFieldExtend custom field extends
1536 * @param int $customValueId custom option value id
1537 * @param int $entityId entity id (contribution, membership...)
1538 * @param boolean $inline consider inline custom groups only
1539 * @param boolean $checkPermission if false, do not include permissioning clause
1540 * @param boolean $includeViewOnly if true, fields marked 'View Only' are included. Required for APIv3.
1542 * @return array $customFormatted formatted custom field array
1545 static function formatCustomField($customFieldId, &$customFormatted, $value,
1546 $customFieldExtend, $customValueId = NULL,
1549 $checkPermission = TRUE,
1550 $includeViewOnly = false
1552 //get the custom fields for the entity
1553 //subtype and basic type
1554 $customDataSubType = NULL;
1555 if (is_array($customFieldExtend)) {
1556 $customFieldExtend = $customFieldExtend[0];
1559 if (in_array($customFieldExtend,
1560 CRM_Contact_BAO_ContactType
::subTypes()
1562 // This is the case when getFieldsForImport() requires fields
1563 // of subtype and its parent.CRM-5143
1564 $customDataSubType = $customFieldExtend;
1565 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1568 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1578 if (!array_key_exists($customFieldId, $customFields)) {
1582 // return if field is a 'code' field
1583 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1587 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1589 if (!$customValueId &&
1590 // we always create new entites for is_multiple unless specified
1591 !$customFields[$customFieldId]['is_multiple'] &&
1597 WHERE entity_id={$entityId}";
1599 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1602 //fix checkbox, now check box always submits values
1603 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1605 // Note that only during merge this is not an array, and you can directly use value
1606 if (is_array($value)) {
1607 $selectedValues = array();
1608 foreach ($value as $selId => $val) {
1610 $selectedValues[] = $selId;
1613 if (!empty($selectedValues)) {
1614 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1616 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1625 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1626 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1629 // Note that only during merge this is not an array,
1630 // and you can directly use value, CRM-4385
1631 if (is_array($value)) {
1632 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1633 array_values($value)
1634 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1642 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1643 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1644 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1646 $customFields[$customFieldId]['data_type'] == 'String' &&
1647 !empty($customFields[$customFieldId]['text_length']) &&
1650 // lets make sure that value is less than the length, else we'll
1651 // be losing some data, CRM-7481
1652 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1653 // need to do a few things here
1655 // 1. lets find a new length
1656 $newLength = $customFields[$customFieldId]['text_length'];
1657 $minLength = strlen($value);
1658 while ($newLength < $minLength) {
1659 $newLength = $newLength * 2;
1662 // set the custom field meta data to have a length larger than value
1663 // alter the custom value table column to match this length
1664 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1669 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1670 if (!CRM_Utils_System
::isNull($value)) {
1671 $format = $customFields[$customFieldId]['date_format'];
1672 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1677 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1678 $customFields[$customFieldId]['data_type'] == 'Money'
1684 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1685 $value = CRM_Utils_Rule
::cleanMoney($value);
1689 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1690 $customFields[$customFieldId]['data_type'] == 'Country'
1700 if ($customFields[$customFieldId]['data_type'] == 'File') {
1701 if (empty($value)) {
1705 $config = CRM_Core_Config
::singleton();
1707 $fName = $value['name'];
1708 $mimeType = $value['type'];
1710 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1712 // rename this file to go into the secure directory
1713 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1714 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1717 if ($customValueId) {
1722 $params = array(1 => array($customValueId, 'Integer'));
1723 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1726 $fileDAO = new CRM_Core_DAO_File();
1729 $fileDAO->id
= $fileId;
1732 $fileDAO->uri
= $filename;
1733 $fileDAO->mime_type
= $mimeType;
1734 $fileDAO->upload_date
= date('Ymdhis');
1736 $fileId = $fileDAO->id
;
1740 if (!is_array($customFormatted)) {
1741 $customFormatted = array();
1744 if (!array_key_exists($customFieldId, $customFormatted)) {
1745 $customFormatted[$customFieldId] = array();
1749 if ($customValueId) {
1750 $index = $customValueId;
1753 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1754 $customFormatted[$customFieldId][$index] = array();
1756 $customFormatted[$customFieldId][$index] = array(
1757 'id' => $customValueId > 0 ?
$customValueId : NULL,
1759 'type' => $customFields[$customFieldId]['data_type'],
1760 'custom_field_id' => $customFieldId,
1761 'custom_group_id' => $groupID,
1762 'table_name' => $tableName,
1763 'column_name' => $columnName,
1764 'file_id' => $fileId,
1765 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1768 //we need to sort so that custom fields are created in the order of entry
1769 krsort($customFormatted[$customFieldId]);
1770 return $customFormatted;
1778 static function &defaultCustomTableSchema(&$params) {
1779 // add the id and extends_id
1781 'name' => $params['name'],
1782 'is_multiple' => $params['is_multiple'],
1783 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1787 'type' => 'int unsigned',
1790 'attributes' => 'AUTO_INCREMENT',
1791 'comment' => 'Default MySQL primary key',
1794 'name' => 'entity_id',
1795 'type' => 'int unsigned',
1797 'comment' => 'Table that this extends',
1798 'fk_table_name' => $params['extends_name'],
1799 'fk_field_name' => 'id',
1800 'fk_attributes' => 'ON DELETE CASCADE',
1805 if (!$params['is_multiple']) {
1806 $table['indexes'] = array(
1809 'field_name_1' => 'entity_id',
1819 * @param bool $indexExist
1820 * @param bool $triggerRebuild
1822 static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1823 $tableName = CRM_Core_DAO
::getFieldValue(
1824 'CRM_Core_DAO_CustomGroup',
1825 $field->custom_group_id
,
1830 'table_name' => $tableName,
1831 'operation' => $operation,
1832 'name' => $field->column_name
,
1833 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1837 'required' => $field->is_required
,
1838 'searchable' => $field->is_searchable
,
1841 if ($operation == 'delete') {
1842 $fkName = "{$tableName}_{$field->column_name}";
1843 if (strlen($fkName) >= 48) {
1844 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1846 $params['fkName'] = $fkName;
1848 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1849 $params['fk_table_name'] = 'civicrm_country';
1850 $params['fk_field_name'] = 'id';
1851 $params['fk_attributes'] = 'ON DELETE SET NULL';
1853 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1854 $params['type'] = 'varchar(255)';
1856 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1857 $params['fk_table_name'] = 'civicrm_state_province';
1858 $params['fk_field_name'] = 'id';
1859 $params['fk_attributes'] = 'ON DELETE SET NULL';
1861 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1862 $params['type'] = 'varchar(255)';
1864 elseif ($field->data_type
== 'File') {
1865 $params['fk_table_name'] = 'civicrm_file';
1866 $params['fk_field_name'] = 'id';
1867 $params['fk_attributes'] = 'ON DELETE SET NULL';
1869 elseif ($field->data_type
== 'ContactReference') {
1870 $params['fk_table_name'] = 'civicrm_contact';
1871 $params['fk_field_name'] = 'id';
1872 $params['fk_attributes'] = 'ON DELETE SET NULL';
1874 if ($field->default_value
) {
1875 $params['default'] = "'{$field->default_value}'";
1878 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1882 * Determine whether it would be safe to move a field
1884 * @param int $fieldID FK to civicrm_custom_field
1885 * @param int $newGroupID FK to civicrm_custom_group
1890 static function _moveFieldValidate($fieldID, $newGroupID) {
1893 $field = new CRM_Core_DAO_CustomField();
1894 $field->id
= $fieldID;
1895 if (!$field->find(TRUE)) {
1896 $errors['fieldID'] = 'Invalid ID for custom field';
1900 $oldGroup = new CRM_Core_DAO_CustomGroup();
1901 $oldGroup->id
= $field->custom_group_id
;
1902 if (!$oldGroup->find(TRUE)) {
1903 $errors['fieldID'] = 'Invalid ID for old custom group';
1907 $newGroup = new CRM_Core_DAO_CustomGroup();
1908 $newGroup->id
= $newGroupID;
1909 if (!$newGroup->find(TRUE)) {
1910 $errors['newGroupID'] = 'Invalid ID for new custom group';
1916 FROM civicrm_custom_field a
1917 INNER JOIN civicrm_custom_field b
1919 AND a.label = b.label
1920 AND b.custom_group_id = %2
1923 1 => array($field->id
, 'Integer'),
1924 2 => array($newGroup->id
, 'Integer'),
1926 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1928 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1931 $tableName = $oldGroup->table_name
;
1932 $columnName = $field->column_name
;
1937 WHERE $columnName is not null
1939 $count = CRM_Core_DAO
::singleValueQuery($query,
1940 CRM_Core_DAO
::$_nullArray
1945 FROM civicrm_custom_group
1946 WHERE id IN ( %1, %2 )
1948 $params = array(1 => array($oldGroup->id
, 'Integer'),
1949 2 => array($newGroup->id
, 'Integer'),
1952 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1954 while ($dao->fetch()) {
1955 $extends[] = $dao->extends;
1957 if ($extends[0] != $extends[1]) {
1958 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1962 return empty($errors) ?
TRUE : $errors;
1966 * Move a custom data field from one group (table) to another
1968 * @param int $fieldID FK to civicrm_custom_field
1969 * @param int $newGroupID FK to civicrm_custom_group
1973 static function moveField($fieldID, $newGroupID) {
1974 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1975 if (TRUE !== $validation) {
1976 CRM_Core_Error
::fatal(implode(' ', $validation));
1978 $field = new CRM_Core_DAO_CustomField();
1979 $field->id
= $fieldID;
1982 $newGroup = new CRM_Core_DAO_CustomGroup();
1983 $newGroup->id
= $newGroupID;
1984 $newGroup->find(TRUE);
1986 $oldGroup = new CRM_Core_DAO_CustomGroup();
1987 $oldGroup->id
= $field->custom_group_id
;
1988 $oldGroup->find(TRUE);
1991 $add->custom_group_id
= $newGroup->id
;
1992 self
::createField($add, 'add');
1994 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1995 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1996 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1998 CRM_Core_DAO
::executeQuery($sql);
2001 $del->custom_group_id
= $oldGroup->id
;
2002 self
::createField($del, 'delete');
2006 CRM_Utils_System
::flushCache();
2010 * Get the database table name and column name for a custom field
2012 * @param int $fieldID - the fieldID of the custom field
2013 * @param boolean $force - force the sql to be run again (primarily used for tests)
2015 * @return array - fatal is fieldID does not exists, else array of tableName, columnName
2019 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 * Function to get custom option groups
2046 * @params array $includeFieldIds ids of custom fields for which
2047 * 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 * @param null $includeFieldIds
2056 * @return mixed $customOptionGroup@static
2058 public static function &customOptionGroup($includeFieldIds = NULL) {
2059 static $customOptionGroup = NULL;
2061 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2062 if ($cacheKey == 'force') {
2063 $customOptionGroup[$cacheKey] = NULL;
2066 if (empty($customOptionGroup[$cacheKey])) {
2067 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2069 //support for single as well as array format.
2070 if (!empty($includeFieldIds)) {
2071 if (is_array($includeFieldIds)) {
2072 $includeFieldIds = implode(',', $includeFieldIds);
2074 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2078 SELECT g.id, g.title
2079 FROM civicrm_option_group g
2080 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2081 WHERE {$whereClause}";
2083 $dao = CRM_Core_DAO
::executeQuery($query);
2084 while ($dao->fetch()) {
2085 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2089 return $customOptionGroup[$cacheKey];
2093 * Function to fix orphan groups
2095 * @params int $customFieldId custom field id
2096 * @params int $optionGroupId option group id
2100 * @param $customFieldId
2101 * @param $optionGroupId
2106 static function fixOptionGroups($customFieldId, $optionGroupId) {
2107 // check if option group belongs to any custom Field else delete
2108 // get the current option group
2109 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2113 // get the updated option group
2114 // if both are same return
2115 if ($currentOptionGroupId == $optionGroupId) {
2119 // check if option group is related to any other field
2120 self
::checkOptionGroup($currentOptionGroupId);
2124 * Function to check if option group is related to more than one
2127 * @params int $optionGroupId option group id
2129 * @param $optionGroupId
2134 static function checkOptionGroup($optionGroupId) {
2137 FROM civicrm_custom_field
2138 WHERE option_group_id = {$optionGroupId}";
2140 $count = CRM_Core_DAO
::singleValueQuery($query);
2143 //delete the option group
2144 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2149 * @param $optionGroupId
2152 * @return null|string
2154 static function getOptionGroupDefault($optionGroupId, $htmlType) {
2156 SELECT default_value, html_type
2157 FROM civicrm_custom_field
2158 WHERE option_group_id = {$optionGroupId}
2159 AND default_value IS NOT NULL
2160 ORDER BY html_type";
2162 $dao = CRM_Core_DAO
::executeQuery($query);
2163 $defaultValue = NULL;
2164 $defaultHTMLType = NULL;
2165 while ($dao->fetch()) {
2166 if ($dao->html_type
== $htmlType) {
2167 return $dao->default_value
;
2169 if ($defaultValue == NULL) {
2170 $defaultValue = $dao->default_value
;
2171 $defaultHTMLType = $dao->html_type
;
2175 // some conversions are needed if either the old or new has a html type which has potential
2176 // multiple default values.
2177 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2178 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2180 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2182 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2183 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2185 $defaultValue = substr($defaultValue, 1, -1);
2186 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2187 substr($defaultValue, 1, -1)
2189 $defaultValue = $values[0];
2192 return $defaultValue;
2197 * @param $customFields
2199 * @param $customFieldExtends
2200 * @param bool $inline
2204 static function postProcess(&$params,
2207 $customFieldExtends,
2210 $customData = array();
2212 foreach ($params as $key => $value) {
2213 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2215 // for autocomplete transfer hidden value instead of label
2216 if ($params[$key] && isset($params[$key . '_id'])) {
2217 $value = $params[$key . '_id'];
2220 // we need to append time with date
2221 if ($params[$key] && isset($params[$key . '_time'])) {
2222 $value .= ' ' . $params[$key . '_time'];
2225 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2228 $customFieldExtends,
2229 $customFieldInfo[1],
2244 static function buildOption($field, &$options) {
2245 // Fixme - adding anything but options to the $options array is a bad idea
2246 // What if an option had the key 'attributes'?
2247 $options['attributes'] = array(
2248 'label' => $field['label'],
2249 'data_type' => $field['data_type'],
2250 'html_type' => $field['html_type'],
2253 $optionGroupID = NULL;
2254 if (($field['html_type'] == 'CheckBox' ||
2255 $field['html_type'] == 'Radio' ||
2256 $field['html_type'] == 'Select' ||
2257 $field['html_type'] == 'AdvMulti-Select' ||
2258 $field['html_type'] == 'Multi-Select' ||
2259 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2261 if ($field['option_group_id']) {
2262 $optionGroupID = $field['option_group_id'];
2264 elseif ($field['data_type'] != 'Boolean') {
2265 CRM_Core_Error
::fatal();
2269 // build the cache for custom values with options (label => value)
2270 if ($optionGroupID != NULL) {
2273 FROM civicrm_option_value
2274 WHERE option_group_id = $optionGroupID
2277 $dao = CRM_Core_DAO
::executeQuery($query);
2278 while ($dao->fetch()) {
2279 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2280 $num = round($dao->value
, 2);
2281 $options["$num"] = $dao->label
;
2284 $options[$dao->value
] = $dao->label
;
2288 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2293 * @param $fieldLabel
2294 * @param null $groupTitle
2298 static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2299 $params = array(1 => array($fieldLabel, 'String'));
2301 $params[2] = array($groupTitle, 'String');
2304 FROM civicrm_custom_field f
2305 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2306 WHERE ( f.label = %1 OR f.name = %1 )
2307 AND ( g.title = %2 OR g.name = %2 )
2313 FROM civicrm_custom_field f
2314 WHERE ( f.label = %1 OR f.name = %1 )
2318 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2319 if ($dao->fetch() &&
2330 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2333 static function getNameFromID($ids) {
2334 if (is_array($ids)) {
2335 $ids = implode(',', $ids);
2338 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2339 FROM civicrm_custom_field f
2340 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2341 WHERE f.id IN ($ids)";
2344 $dao = CRM_Core_DAO
::executeQuery($sql);
2346 while ($dao->fetch()) {
2347 $result[$dao->id
] = array(
2348 'field_name' => $dao->field_name
,
2349 'field_label' => $dao->field_label
,
2350 'group_name' => $dao->group_name
,
2351 'group_title' => $dao->group_title
,
2358 * Validate custom data.
2360 * @param array $params custom data submitted.
2361 * ie array( 'custom_1' => 'validate me' );
2363 * @return array $errors validation errors.
2366 static function validateCustomData($params) {
2368 if (!is_array($params) ||
empty($params)) {
2373 //pick up profile fields.
2374 $profileFields = array();
2375 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2377 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2379 CRM_Core_Action
::VIEW
2383 //lets start w/ params.
2384 foreach ($params as $key => $value) {
2385 $customFieldID = self
::getKeyID($key);
2386 if (!$customFieldID) {
2390 //load the structural info for given field.
2391 $field = new CRM_Core_DAO_CustomField();
2392 $field->id
= $customFieldID;
2393 if (!$field->find(TRUE)) {
2396 $dataType = $field->data_type
;
2398 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2399 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2400 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2402 $fieldTitle = $field->label
;
2405 //no need to validate.
2406 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2410 //lets validate first for required field.
2411 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2412 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2416 //now time to take care of custom field form rules.
2417 $ruleName = $errorMsg = NULL;
2418 switch ($dataType) {
2420 $ruleName = 'integer';
2421 $errorMsg = ts('%1 must be an integer (whole number).',
2422 array(1 => $fieldTitle)
2427 $ruleName = 'money';
2428 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2429 array(1 => $fieldTitle)
2434 $ruleName = 'numeric';
2435 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2436 array(1 => $fieldTitle)
2441 $ruleName = 'wikiURL';
2442 $errorMsg = ts('%1 must be valid Website.',
2443 array(1 => $fieldTitle)
2448 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2450 $funName = "CRM_Utils_Rule::{$ruleName}";
2451 if (is_callable($funName)) {
2452 $valid = call_user_func($funName, $value);
2455 $errors[$key] = $errorMsg;
2468 static function isMultiRecordField($customId) {
2469 $isMultipleWithGid = FALSE;
2470 if (!is_numeric($customId)) {
2471 $customId = self
::getKeyID($customId);
2473 if (is_numeric($customId)) {
2474 $sql = "SELECT cg.id cgId
2475 FROM civicrm_custom_group cg
2476 INNER JOIN civicrm_custom_field cf
2477 ON cg.id = cf.custom_group_id
2478 WHERE cf.id = %1 AND cg.is_multiple = 1";
2479 $params[1] = array($customId, 'Integer');
2480 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2481 if ($dao->fetch()) {
2483 $isMultipleWithGid = $dao->cgId
;
2488 return $isMultipleWithGid;
2492 * Does this field store a serialized string?
2493 * @param CRM_Core_DAO_CustomField|array $field
2496 static function isSerialized($field) {
2497 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2498 $field = (array) $field;
2499 // FIXME: Currently the only way to know if data is serialized is by looking at the html_type. It would be cleaner to decouple this.
2500 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);