3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
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
47 public static $_dataType = NULL;
50 * Array for valid combinations of data_type & html_type
54 public static $_dataToHtml = NULL;
57 * Array to hold (formatted) fields for import
61 public static $_importFields = NULL;
64 * Build and retrieve the list of data types and descriptions.
67 * Data type => Description
69 public static function &dataType() {
70 if (!(self
::$_dataType)) {
71 self
::$_dataType = array(
72 'String' => ts('Alphanumeric'),
73 'Int' => ts('Integer'),
74 'Float' => ts('Number'),
75 'Money' => ts('Money'),
78 'Boolean' => ts('Yes or No'),
79 'StateProvince' => ts('State/Province'),
80 'Country' => ts('Country'),
83 'ContactReference' => ts('Contact Reference'),
86 return self
::$_dataType;
92 public static function dataToHtml() {
93 if (!self
::$_dataToHtml) {
94 self
::$_dataToHtml = array(
99 'CheckBox' => 'CheckBox',
100 'Multi-Select' => 'Multi-Select',
101 'AdvMulti-Select' => 'AdvMulti-Select',
102 'Autocomplete-Select' => 'Autocomplete-Select',
104 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
105 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
106 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
107 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
108 array('Date' => 'Select Date'),
109 array('Radio' => 'Radio'),
110 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
111 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
112 array('File' => 'File'),
113 array('Link' => 'Link'),
114 array('ContactReference' => 'Autocomplete-Select'),
117 return self
::$_dataToHtml;
121 * Takes an associative array and creates a custom field object.
123 * This function is invoked from within the web form layer and also from the api layer
125 * @param array $params
126 * (reference) an assoc array of name/value pairs.
128 * @return CRM_Core_DAO_CustomField
130 public static function create(&$params) {
131 $origParams = array_merge(array(), $params);
133 if (!isset($params['id'])) {
134 if (!isset($params['column_name'])) {
135 // if add mode & column_name not present, calculate it.
136 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
138 if (!isset($params['name'])) {
139 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
143 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
148 $columnName = $params['column_name'];
151 //as during create if field is_searchable we had created index.
152 if (!empty($params['id'])) {
153 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
156 switch (CRM_Utils_Array
::value('html_type', $params)) {
158 if (empty($params['date_format'])) {
159 $config = CRM_Core_Config
::singleton();
160 $params['date_format'] = $config->dateInputFormat
;
165 case 'AdvMulti-Select':
167 if (isset($params['default_checkbox_option'])) {
168 $tempArray = array_keys($params['default_checkbox_option']);
169 $defaultArray = array();
170 foreach ($tempArray as $k => $v) {
171 if ($params['option_value'][$v]) {
172 $defaultArray[] = $params['option_value'][$v];
176 if (!empty($defaultArray)) {
177 // also add the separator before and after the value per new convention (CRM-1604)
178 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
182 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
184 $params['default_value'] = $params['option_value'][$params['default_option']];
190 $transaction = new CRM_Core_Transaction();
191 // create any option group & values if required
192 if ($params['html_type'] != 'Text' &&
193 in_array($params['data_type'], array(
201 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
202 $params['custom_group_id'],
206 //CRM-16659: if option_value then create an option group for this custom field.
207 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
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 do not have a default value
255 // retrieve 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
,
266 $params['default_value'] = $defaultValue;
271 // since we need to save option group id :)
272 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
273 $params['attributes'] = 'rows=4, cols=60';
276 $customField = new CRM_Core_DAO_CustomField();
277 $customField->copyValues($params);
278 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
279 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
280 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $params, FALSE);
281 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
282 //CRM-15792 - Custom field gets disabled if is_active not set
283 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, TRUE);
284 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
285 $customField->save();
287 // make sure all values are present in the object for further processing
288 $customField->find(TRUE);
290 $triggerRebuild = CRM_Utils_Array
::value('triggerRebuild', $params, TRUE);
291 //create/drop the index when we toggle the is_searchable flag
292 if (!empty($params['id'])) {
293 self
::createField($customField, 'modify', $indexExist, $triggerRebuild);
296 if (!isset($origParams['column_name'])) {
297 $columnName .= "_{$customField->id}";
298 $params['column_name'] = $columnName;
300 $customField->column_name
= $columnName;
301 $customField->save();
302 // make sure all values are present in the object
303 $customField->find(TRUE);
306 self
::createField($customField, 'add', $indexExist, $triggerRebuild);
309 // complete transaction
310 $transaction->commit();
312 CRM_Utils_System
::flushCache();
318 * Fetch object based on array of properties.
320 * @param array $params
321 * (reference ) an assoc array of name/value pairs.
322 * @param array $defaults
323 * (reference ) an assoc array to hold the flattened values.
325 * @return CRM_Core_DAO_CustomField
327 public static function retrieve(&$params, &$defaults) {
328 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
332 * Update the is_active flag in the db.
335 * Id of the database record.
336 * @param bool $is_active
337 * Value we want to set the is_active field.
340 * DAO object on sucess, null otherwise
343 public static function setIsActive($id, $is_active) {
345 CRM_Utils_System
::flushCache();
347 //enable-disable CustomField
348 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
349 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
353 * Get the field title.
362 public static function getTitle($id) {
363 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
367 * Store and return an array of all active custom fields.
369 * @param string $customDataType
370 * Type of Custom Data; empty is a synonym for "all contact data types".
371 * @param bool $showAll
372 * If true returns all fields (includes disabled fields).
373 * @param bool $inline
374 * If true returns all inline fields (includes disabled fields).
375 * @param int $customDataSubType
376 * Custom Data sub type value.
377 * @param int $customDataSubName
378 * Custom Data sub name value.
379 * @param bool $onlyParent
380 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
381 * @param bool $onlySubType
382 * Return only custom data for subtype.
383 * @param bool $checkPermission
384 * If false, do not include permissioning clause.
387 * an array of active custom fields.
390 public static function &getFields(
391 $customDataType = 'Individual',
394 $customDataSubType = NULL,
395 $customDataSubName = NULL,
397 $onlySubType = FALSE,
398 $checkPermission = TRUE
400 if (empty($customDataType)) {
401 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
403 if ($customDataType && !is_array($customDataType)) {
405 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
406 // This is the case when getFieldsForImport() requires fields
407 // limited strictly to a subtype.
408 $customDataSubType = $customDataType;
409 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
413 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
414 // this makes the method flexible to support retrieving fields
415 // for multiple extends value.
416 $customDataType = array($customDataType);
420 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
422 if (is_array($customDataType)) {
423 $cacheKey = implode('_', $customDataType);
426 $cacheKey = $customDataType;
429 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
430 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
431 $cacheKey .= $showAll ?
'_1' : '_0';
432 $cacheKey .= $inline ?
'_1_' : '_0_';
433 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
434 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
435 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
437 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
439 // also get the permission stuff here
440 if ($checkPermission) {
441 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
446 $permissionClause = '(1)';
449 // lets md5 permission clause and take first 8 characters
450 $cacheKey .= substr(md5($permissionClause), 0, 8);
452 if (strlen($cacheKey) > 40) {
453 $cacheKey = md5($cacheKey);
456 if (!self
::$_importFields ||
457 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
459 if (!self
::$_importFields) {
460 self
::$_importFields = array();
463 // check if we can retrieve from database cache
464 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
466 if ($fields === NULL) {
467 $cfTable = self
::getTableName();
470 if (is_array($customDataType)) {
472 foreach ($customDataType as $dataType) {
473 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
474 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
475 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
478 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
480 $value = $value ?
$value . ", {$val}" : $val;
484 $extends = "AND $cgTable.extends IN ( $value ) ";
488 if (!empty($customDataType) && empty($extends)) {
489 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
490 self
::$_importFields[$cacheKey] = array();
491 return self
::$_importFields[$cacheKey];
495 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
498 $query = "SELECT $cfTable.id, $cfTable.label,
502 $cfTable.default_value,
503 $cfTable.options_per_line, $cfTable.text_length,
504 $cfTable.custom_group_id,
505 $cfTable.is_required,
506 $cgTable.extends, $cfTable.is_search_range,
507 $cgTable.extends_entity_column_value,
508 $cgTable.extends_entity_column_id,
510 $cfTable.option_group_id,
511 $cfTable.date_format,
512 $cfTable.time_format,
513 $cgTable.is_multiple,
514 og.name as option_group_name
517 ON $cfTable.custom_group_id = $cgTable.id
518 LEFT JOIN civicrm_option_group og
519 ON $cfTable.option_group_id = og.id
523 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
527 $query .= " AND $cgTable.style = 'Inline' ";
530 //get the custom fields for specific type in
531 //combination with fields those support any type.
532 if (!empty($customDataSubType)) {
533 $subtypeClause = array();
534 foreach ($customDataSubType as $subtype) {
535 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
536 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
539 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
541 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
544 if ($customDataSubName) {
545 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
548 // also get the permission stuff here
549 if ($checkPermission) {
550 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
555 $permissionClause = '(1)';
558 $query .= " $extends AND $permissionClause
559 ORDER BY $cgTable.weight, $cgTable.title,
560 $cfTable.weight, $cfTable.label";
562 $dao = CRM_Core_DAO
::executeQuery($query);
565 while (($dao->fetch()) != NULL) {
566 $fields[$dao->id
]['label'] = $dao->label
;
567 $fields[$dao->id
]['groupTitle'] = $dao->title
;
568 $fields[$dao->id
]['data_type'] = $dao->data_type
;
569 $fields[$dao->id
]['html_type'] = $dao->html_type
;
570 $fields[$dao->id
]['default_value'] = $dao->default_value
;
571 $fields[$dao->id
]['text_length'] = $dao->text_length
;
572 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
573 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
574 $fields[$dao->id
]['extends'] = $dao->extends;
575 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
576 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
577 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
578 $fields[$dao->id
]['is_view'] = $dao->is_view
;
579 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
580 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
581 $fields[$dao->id
]['date_format'] = $dao->date_format
;
582 $fields[$dao->id
]['time_format'] = $dao->time_format
;
583 $fields[$dao->id
]['is_required'] = $dao->is_required
;
584 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
587 CRM_Core_BAO_Cache
::setItem($fields,
589 "custom importableFields $cacheKey"
592 self
::$_importFields[$cacheKey] = $fields;
595 return self
::$_importFields[$cacheKey];
599 * Return the field ids and names (with groups) for import purpose.
601 * @param int|string $contactType Contact type
602 * @param bool $showAll
603 * If true returns all fields (includes disabled fields).
604 * @param bool $onlyParent
605 * Return fields ONLY related to basic types.
606 * @param bool $search
607 * When called from search and multiple records need to be returned.
608 * @param bool $checkPermission
609 * If false, do not include permissioning clause.
611 * @param bool $withMultiple
617 public static function &getFieldsForImport(
618 $contactType = 'Individual',
622 $checkPermission = TRUE,
623 $withMultiple = FALSE
625 // Note: there are situations when we want getFieldsForImport() return fields related
626 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
627 $fields = &self
::getFields($contactType,
637 $importableFields = array();
638 foreach ($fields as $id => $values) {
639 // for now we should not allow multiple fields in profile / export etc, hence unsetting
641 (!empty($values['is_multiple']) && !$withMultiple)
646 /* generate the key for the fields array */
650 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
651 $importableFields[$key] = array(
653 'title' => CRM_Utils_Array
::value('label', $values),
654 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
656 'custom_field_id' => $id,
657 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
658 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
659 'data_type' => CRM_Utils_Array
::value('data_type', $values),
660 'html_type' => CRM_Utils_Array
::value('html_type', $values),
661 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
664 // CRM-6681, pass date and time format when html_type = Select Date
665 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
666 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
667 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
671 return $importableFields;
675 * Get the field id from an import key.
684 public static function getKeyID($key, $all = FALSE) {
686 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
693 CRM_Utils_Array
::value(2, $match),
697 return $all ?
array(NULL, NULL) : NULL;
701 * Use the cache to get all values of a specific custom field.
703 * @param int $fieldID
704 * The custom field ID.
706 * @return CRM_Core_DAO_CustomField
709 public static function getFieldObject($fieldID) {
710 $field = new CRM_Core_DAO_CustomField();
712 // check if we can get the field values from the system cache
713 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
714 $cache = CRM_Utils_Cache
::singleton();
715 $fieldValues = $cache->get($cacheKey);
716 if (empty($fieldValues)) {
717 $field->id
= $fieldID;
718 if (!$field->find(TRUE)) {
719 CRM_Core_Error
::fatal();
722 $fieldValues = array();
723 CRM_Core_DAO
::storeValues($field, $fieldValues);
725 $cache->set($cacheKey, $fieldValues);
728 $field->copyValues($fieldValues);
735 * This function for building custom fields.
737 * @param CRM_Core_Form $qf
738 * Form object (reference).
739 * @param string $elementName
740 * Name of the custom field.
741 * @param int $fieldId
742 * @param bool $inactiveNeeded
744 * @param bool $useRequired
745 * True if required else false.
746 * @param bool $search
747 * True if used for search else false.
748 * @param string $label
749 * Label for custom field.
752 public static function addQuickFormElement(
756 $inactiveNeeded = FALSE,
761 $field = self
::getFieldObject($fieldId);
762 $widget = $field->html_type
;
764 // Custom field HTML should indicate group+field name
765 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
766 $dataCrmCustomVal = $groupName . ':' . $field->name
;
767 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
768 $field->attributes
.= $dataCrmCustomAttr;
770 // Fixed for Issue CRM-2183
771 if ($widget == 'TextArea' && $search) {
775 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
777 // FIXME: Why are select state/country separate widget types?
778 $isSelect = (in_array($widget, array(
781 'Select State/Province',
782 'Multi-Select State/Province',
784 'Multi-Select Country',
791 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array(
792 'field' => "custom_$fieldId",
793 'context' => $search ?
'search' : 'create',
796 // Consolidate widget types to simplify the below switch statement
797 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
800 $selectAttributes = array(
801 'data-crm-custom' => $dataCrmCustomVal,
802 'class' => 'crm-select2',
804 // Search field is always multi-select
805 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
806 $selectAttributes['class'] .= ' huge';
807 $selectAttributes['multiple'] = 'multiple';
808 $selectAttributes['placeholder'] = $placeholder;
810 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
811 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
812 $selectAttributes +
= array(
813 'data-api-entity' => 'contact',
814 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
815 'data-api-field' => 'custom_' . $field->id
,
816 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
821 if (!isset($label)) {
822 $label = $field->label
;
826 * at some point in time we might want to split the below into small functions
832 if ($field->is_search_range
&& $search) {
833 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
834 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
837 $element = &$qf->add('text', $elementName, $label,
839 $useRequired && !$search
845 $attributes = $dataCrmCustomAttr;
846 if ($field->note_rows
) {
847 $attributes .= 'rows=' . $field->note_rows
;
850 $attributes .= 'rows=4';
852 if ($field->note_columns
) {
853 $attributes .= ' cols=' . $field->note_columns
;
856 $attributes .= ' cols=60';
858 if ($field->text_length
) {
859 $attributes .= ' maxlength=' . $field->text_length
;
861 $element = &$qf->add('textarea',
865 $useRequired && !$search
870 if ($field->is_search_range
&& $search) {
871 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
873 'format' => $field->date_format
,
874 'timeFormat' => $field->time_format
,
875 'startOffset' => $field->start_date_years
,
876 'endOffset' => $field->end_date_years
,
877 'data-crm-custom' => $dataCrmCustomVal,
881 $qf->addDate($elementName . '_to', ts('To'), FALSE,
883 'format' => $field->date_format
,
884 'timeFormat' => $field->time_format
,
885 'startOffset' => $field->start_date_years
,
886 'endOffset' => $field->end_date_years
,
887 'data-crm-custom' => $dataCrmCustomVal,
892 $required = $useRequired && !$search;
894 $qf->addDate($elementName, $label, $required, array(
895 'format' => $field->date_format
,
896 'timeFormat' => $field->time_format
,
897 'startOffset' => $field->start_date_years
,
898 'endOffset' => $field->end_date_years
,
899 'data-crm-custom' => $dataCrmCustomVal,
906 foreach ($options as $v => $l) {
907 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
909 $group = $qf->addGroup($choice, $elementName, $label);
910 if ($useRequired && !$search) {
911 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
914 $group->setAttribute('allowClear', TRUE);
918 // For all select elements
920 if (empty($selectAttributes['multiple'])) {
921 $options = array('' => $placeholder) +
$options;
923 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
925 // Add and/or option for fields that store multiple values
926 if ($search && self
::isSerialized($field)) {
929 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
930 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
932 $qf->addGroup($operators, $elementName . '_operator');
933 $qf->setDefaults(array($elementName . '_operator' => 'or'));
937 case 'AdvMulti-Select':
938 $include =& $qf->addElement(
945 'class' => 'advmultiselect',
946 'data-crm-custom' => $dataCrmCustomVal,
950 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
951 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
953 if ($useRequired && !$search) {
954 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
960 foreach ($options as $v => $l) {
961 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
963 $qf->addGroup($check, $elementName, $label);
964 if ($useRequired && !$search) {
965 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
970 // we should not build upload file in search mode
975 strtolower($field->html_type
),
979 $useRequired && !$search
981 $qf->addUploadElement($elementName);
984 case 'RichTextEditor':
986 'rows' => $field->note_rows
,
987 'cols' => $field->note_columns
,
988 'data-crm-custom' => $dataCrmCustomVal,
990 if ($field->text_length
) {
991 $attributes['maxlength'] = $field->text_length
;
993 $qf->addWysiwyg($elementName, $label, $attributes, $search);
996 case 'Autocomplete-Select':
997 static $customUrls = array();
998 // Fixme: why is this a string in the first place??
999 $attributes = array();
1000 if ($field->attributes
) {
1001 foreach (explode(' ', $field->attributes
) as $at) {
1002 if (strpos($at, '=')) {
1003 list($k, $v) = explode('=', $at);
1004 $attributes[$k] = trim($v, ' "');
1008 if ($field->data_type
== 'ContactReference') {
1009 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1010 $attributes['data-api-entity'] = 'contact';
1011 $qf->add('text', $elementName, $label, $attributes,
1012 $useRequired && !$search
1015 $urlParams = "context=customfield&id={$field->id}";
1017 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1024 // FIXME: This won't work with customFieldOptions hook
1025 $attributes +
= array(
1026 'entity' => 'option_value',
1027 'placeholder' => $placeholder,
1028 'multiple' => $search,
1030 'params' => array('option_group_id' => $field->option_group_id
),
1033 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1036 $qf->assign('customUrls', $customUrls);
1040 switch ($field->data_type
) {
1042 // integers will have numeric rule applied to them.
1043 if ($field->is_search_range
&& $search) {
1044 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1045 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1047 elseif ($widget == 'Text') {
1048 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1053 if ($field->is_search_range
&& $search) {
1054 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1055 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1057 elseif ($widget == 'Text') {
1058 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1063 if ($field->is_search_range
&& $search) {
1064 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1065 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1067 elseif ($widget == 'Text') {
1068 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1073 $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
1074 $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
1075 $element->setAttribute('class', "url");
1076 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1079 if ($field->is_view
&& !$search) {
1080 $qf->freeze($elementName);
1085 * Delete the Custom Field.
1087 * @param object $field
1090 public static function deleteField($field) {
1091 CRM_Utils_System
::flushCache();
1093 // first delete the custom option group and values associated with this field
1094 if ($field->option_group_id
) {
1095 //check if option group is related to any other field, if
1096 //not delete the option group and related option values
1097 self
::checkOptionGroup($field->option_group_id
);
1100 // next drop the column from the custom value table
1101 self
::createField($field, 'delete');
1104 CRM_Core_BAO_UFField
::delUFField($field->id
);
1105 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1109 * Given a custom field value, its id and the set of options
1110 * find the display value for this field
1112 * @param mixed $value
1113 * The custom field value.
1115 * The custom field id.
1116 * @param array $options
1117 * The assoc array of option name/value pairs.
1119 * @param int $contactID
1120 * @param int $fieldID
1126 public static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1127 $option = &$options[$id];
1128 $attributes = &$option['attributes'];
1129 $html_type = $attributes['html_type'];
1130 $data_type = $attributes['data_type'];
1131 $format = CRM_Utils_Array
::value('format', $attributes);
1133 return self
::getDisplayValueCommon($value,
1148 * @param null $format
1149 * @param int $contactID
1150 * @param int $fieldID
1152 * @return array|mixed|null|string
1154 public static function getDisplayValueCommon(
1166 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1167 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1168 $html_type == 'Select' ||
1169 $html_type == 'CheckBox' ||
1170 $html_type == 'AdvMulti-Select' ||
1171 $html_type == 'Multi-Select'
1174 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1177 switch ($html_type) {
1179 if ($data_type == 'Boolean') {
1180 $option = array('No', 'Yes');
1182 if (is_array($value)) {
1184 foreach ($value as $data) {
1185 $display .= $display ?
', ' . $option[$data] : $option[$data];
1189 $display = CRM_Utils_Array
::value($value, $option);
1193 case 'Autocomplete-Select':
1194 if ($data_type == 'ContactReference' &&
1197 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1199 elseif (is_array($value)) {
1201 foreach ($value as $data) {
1202 $display .= $display ?
', ' . $option[$data] : $option[$data];
1206 $display = CRM_Utils_Array
::value($value, $option);
1211 if (is_array($value)) {
1213 foreach ($value as $data) {
1214 $display .= $display ?
', ' . $option[$data] : $option[$data];
1218 $display = CRM_Utils_Array
::value($value, $option);
1223 case 'AdvMulti-Select':
1224 case 'Multi-Select':
1225 if (is_array($value)) {
1226 $checkedData = $value;
1229 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1230 substr($value, 1, -1)
1232 if ($html_type == 'CheckBox') {
1234 foreach ($checkedData as $v) {
1235 $v = str_replace(CRM_Core_DAO
::VALUE_SEPARATOR
, '', $v);
1238 $checkedData = $newData;
1243 foreach ($checkedData as $key => $val) {
1244 $v[] = CRM_Utils_Array
::value($val, $option);
1247 $display = implode(', ', $v);
1252 if (is_array($value)) {
1253 foreach ($value as $key => $val) {
1254 $display[$key] = CRM_Utils_Date
::customFormat($val);
1258 // remove time element display if time is not set
1259 if (empty($option['attributes']['time_format'])) {
1260 $value = substr($value, 0, 10);
1262 $display = CRM_Utils_Date
::customFormat($value);
1266 case 'Select State/Province':
1267 case 'Multi-Select State/Province':
1269 $option = CRM_Core_PseudoConstant
::stateProvince(FALSE, FALSE);
1270 foreach ((array) $value as $data) {
1271 $display .= $display ?
', ' . $option[$data] : $option[$data];
1275 case 'Select Country':
1276 case 'Multi-Select Country':
1277 $countries = CRM_Core_PseudoConstant
::country(FALSE, FALSE);
1279 foreach ((array) $value as $countryID) {
1280 $display .= $display ?
', ' . $countries[$countryID] : $countries[$countryID];
1285 // In the context of displaying a profile, show file/image
1286 if ($contactID && $value) {
1287 $url = self
::getFileURL($contactID, $fieldID, $value);
1289 $display = $url['file_url'];
1292 // In other contexts show a paperclip icon
1294 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1295 $display = $icons[$value];
1300 if (empty($value)) {
1304 $display = is_array($value) ?
nl2br(implode(', ', $value)) : nl2br($value);
1310 if (empty($value)) {
1314 $display = is_array($value) ?
implode(', ', $value) : $value;
1317 return $display ?
$display : $value;
1321 * Set default values for custom data used in profile.
1323 * @param int $customFieldId
1325 * @param string $elementName
1326 * Custom field name.
1327 * @param array $defaults
1328 * Associated array of fields.
1329 * @param int $contactId
1333 * @param mixed $value
1334 * If passed - dont fetch value from db,.
1335 * just format the given value
1338 public static function setProfileDefaults(
1346 //get the type of custom field
1347 $customField = new CRM_Core_BAO_CustomField();
1348 $customField->id
= $customFieldId;
1349 $customField->find(TRUE);
1352 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1353 $value = $customField->default_value
;
1357 if (!isset($value)) {
1358 $info = self
::getTableColumnGroup($customFieldId);
1359 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1360 $result = CRM_Core_DAO
::executeQuery($query);
1361 if ($result->fetch()) {
1362 $value = $result->value
;
1366 if ($customField->data_type
== 'Country') {
1368 $config = CRM_Core_Config
::singleton();
1369 if ($config->defaultContactCountry
) {
1370 $value = $config->defaultContactCountry();
1376 //set defaults if mode is registration
1377 if (!trim($value) &&
1379 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1381 $value = $customField->default_value
;
1384 if ($customField->data_type
== 'Money' && isset($value)) {
1385 $value = number_format($value, 2);
1387 switch ($customField->html_type
) {
1389 case 'AdvMulti-Select':
1390 case 'Multi-Select':
1391 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1392 $defaults[$elementName] = array();
1393 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1394 substr($value, 1, -1)
1396 foreach ($customOption as $val) {
1397 if (in_array($val['value'], $checkedValue)) {
1398 if ($customField->html_type
== 'CheckBox') {
1399 $defaults[$elementName][$val['value']] = 1;
1401 elseif ($customField->html_type
== 'Multi-Select' ||
1402 $customField->html_type
== 'AdvMulti-Select'
1404 $defaults[$elementName][$val['value']] = $val['value'];
1412 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1415 $customField->date_format
,
1416 $customField->time_format
1421 case 'Autocomplete-Select':
1422 if ($customField->data_type
== 'ContactReference') {
1423 if (is_numeric($value)) {
1424 $defaults[$elementName . '_id'] = $value;
1425 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1429 $defaults[$elementName] = $value;
1434 $defaults[$elementName] = $value;
1439 * @param int $contactID
1441 * @param int $fileID
1442 * @param bool $absolute
1447 * @param int $contactID
1449 * @param int $fileID
1450 * @param bool $absolute
1454 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1457 $params = array('id' => $cfID);
1458 $defaults = array();
1459 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1460 $columnName = $defaults['column_name'];
1462 //table name of custom data
1463 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1464 $defaults['custom_group_id'],
1468 //query to fetch id from civicrm_file
1469 if ($multiRecordWhereClause) {
1470 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1473 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1475 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1480 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1485 $result['file_id'] = $fileID;
1487 if ($fileType == 'image/jpeg' ||
1488 $fileType == 'image/pjpeg' ||
1489 $fileType == 'image/gif' ||
1490 $fileType == 'image/x-png' ||
1491 $fileType == 'image/png'
1493 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1498 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1499 list($imageWidth, $imageHeight) = getimagesize($path);
1500 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1501 $url = CRM_Utils_System
::url('civicrm/file',
1502 "reset=1&id=$fileID&eid=$contactID",
1503 $absolute, NULL, TRUE, TRUE
1505 $result['file_url'] = "
1506 <a href=\"$url\" class='crm-image-popup'>
1507 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1509 // for non image files
1512 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1516 $url = CRM_Utils_System
::url('civicrm/file',
1517 "reset=1&id=$fileID&eid=$contactID",
1518 $absolute, NULL, TRUE, TRUE
1520 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1528 * Format custom fields before inserting.
1530 * @param int $customFieldId
1532 * @param array $customFormatted
1535 * Value of custom field.
1536 * @param string $customFieldExtend
1537 * Custom field extends.
1538 * @param int $customValueId
1539 * Custom option value id.
1540 * @param int $entityId
1541 * Entity id (contribution, membership...).
1542 * @param bool $inline
1543 * Consider inline custom groups only.
1544 * @param bool $checkPermission
1545 * If false, do not include permissioning clause.
1546 * @param bool $includeViewOnly
1547 * If true, fields marked 'View Only' are included. Required for APIv3.
1549 * @return array|NULL
1550 * formatted custom field array
1552 public static function formatCustomField(
1553 $customFieldId, &$customFormatted, $value,
1554 $customFieldExtend, $customValueId = NULL,
1557 $checkPermission = TRUE,
1558 $includeViewOnly = FALSE
1560 //get the custom fields for the entity
1561 //subtype and basic type
1562 $customDataSubType = NULL;
1563 if ($customFieldExtend) {
1564 // This is the case when getFieldsForImport() requires fields
1565 // of subtype and its parent.CRM-5143
1566 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1567 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1568 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1569 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1570 if (is_array($customFieldExtend)) {
1571 $customFieldExtend = array_unique(array_values($customFieldExtend));
1576 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1586 if (!array_key_exists($customFieldId, $customFields)) {
1590 // return if field is a 'code' field
1591 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1595 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1597 if (!$customValueId &&
1598 // we always create new entites for is_multiple unless specified
1599 !$customFields[$customFieldId]['is_multiple'] &&
1605 WHERE entity_id={$entityId}";
1607 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1610 //fix checkbox, now check box always submits values
1611 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1613 // Note that only during merge this is not an array, and you can directly use value
1614 if (is_array($value)) {
1615 $selectedValues = array();
1616 foreach ($value as $selId => $val) {
1618 $selectedValues[] = $selId;
1621 if (!empty($selectedValues)) {
1622 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1624 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1633 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1634 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1637 // Note that only during merge this is not an array,
1638 // and you can directly use value, CRM-4385
1639 if (is_array($value)) {
1640 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1641 array_values($value)
1642 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1650 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1651 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1652 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1654 $customFields[$customFieldId]['data_type'] == 'String' &&
1655 !empty($customFields[$customFieldId]['text_length']) &&
1658 // lets make sure that value is less than the length, else we'll
1659 // be losing some data, CRM-7481
1660 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1661 // need to do a few things here
1663 // 1. lets find a new length
1664 $newLength = $customFields[$customFieldId]['text_length'];
1665 $minLength = strlen($value);
1666 while ($newLength < $minLength) {
1667 $newLength = $newLength * 2;
1670 // set the custom field meta data to have a length larger than value
1671 // alter the custom value table column to match this length
1672 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1677 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1678 if (!CRM_Utils_System
::isNull($value)) {
1679 $format = $customFields[$customFieldId]['date_format'];
1680 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1685 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1686 $customFields[$customFieldId]['data_type'] == 'Money'
1692 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1693 $value = CRM_Utils_Rule
::cleanMoney($value);
1697 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1698 $customFields[$customFieldId]['data_type'] == 'Country'
1708 if ($customFields[$customFieldId]['data_type'] == 'File') {
1709 if (empty($value)) {
1713 $config = CRM_Core_Config
::singleton();
1715 $fName = $value['name'];
1716 $mimeType = $value['type'];
1718 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1720 // rename this file to go into the secure directory
1721 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1722 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1725 if ($customValueId) {
1730 $params = array(1 => array($customValueId, 'Integer'));
1731 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1734 $fileDAO = new CRM_Core_DAO_File();
1737 $fileDAO->id
= $fileId;
1740 $fileDAO->uri
= $filename;
1741 $fileDAO->mime_type
= $mimeType;
1742 $fileDAO->upload_date
= date('Ymdhis');
1744 $fileId = $fileDAO->id
;
1748 if (!is_array($customFormatted)) {
1749 $customFormatted = array();
1752 if (!array_key_exists($customFieldId, $customFormatted)) {
1753 $customFormatted[$customFieldId] = array();
1757 if ($customValueId) {
1758 $index = $customValueId;
1761 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1762 $customFormatted[$customFieldId][$index] = array();
1764 $customFormatted[$customFieldId][$index] = array(
1765 'id' => $customValueId > 0 ?
$customValueId : NULL,
1767 'type' => $customFields[$customFieldId]['data_type'],
1768 'custom_field_id' => $customFieldId,
1769 'custom_group_id' => $groupID,
1770 'table_name' => $tableName,
1771 'column_name' => $columnName,
1772 'file_id' => $fileId,
1773 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1776 //we need to sort so that custom fields are created in the order of entry
1777 krsort($customFormatted[$customFieldId]);
1778 return $customFormatted;
1782 * @param array $params
1786 public static function &defaultCustomTableSchema(&$params) {
1787 // add the id and extends_id
1789 'name' => $params['name'],
1790 'is_multiple' => $params['is_multiple'],
1791 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1795 'type' => 'int unsigned',
1798 'attributes' => 'AUTO_INCREMENT',
1799 'comment' => 'Default MySQL primary key',
1802 'name' => 'entity_id',
1803 'type' => 'int unsigned',
1805 'comment' => 'Table that this extends',
1806 'fk_table_name' => $params['extends_name'],
1807 'fk_field_name' => 'id',
1808 'fk_attributes' => 'ON DELETE CASCADE',
1813 if (!$params['is_multiple']) {
1814 $table['indexes'] = array(
1817 'field_name_1' => 'entity_id',
1827 * @param bool $indexExist
1828 * @param bool $triggerRebuild
1830 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1831 $tableName = CRM_Core_DAO
::getFieldValue(
1832 'CRM_Core_DAO_CustomGroup',
1833 $field->custom_group_id
,
1838 'table_name' => $tableName,
1839 'operation' => $operation,
1840 'name' => $field->column_name
,
1841 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1845 'required' => $field->is_required
,
1846 'searchable' => $field->is_searchable
,
1849 if ($operation == 'delete') {
1850 $fkName = "{$tableName}_{$field->column_name}";
1851 if (strlen($fkName) >= 48) {
1852 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1854 $params['fkName'] = $fkName;
1856 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1857 $params['fk_table_name'] = 'civicrm_country';
1858 $params['fk_field_name'] = 'id';
1859 $params['fk_attributes'] = 'ON DELETE SET NULL';
1861 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1862 $params['type'] = 'varchar(255)';
1864 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1865 $params['fk_table_name'] = 'civicrm_state_province';
1866 $params['fk_field_name'] = 'id';
1867 $params['fk_attributes'] = 'ON DELETE SET NULL';
1869 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1870 $params['type'] = 'varchar(255)';
1872 elseif ($field->data_type
== 'File') {
1873 $params['fk_table_name'] = 'civicrm_file';
1874 $params['fk_field_name'] = 'id';
1875 $params['fk_attributes'] = 'ON DELETE SET NULL';
1877 elseif ($field->data_type
== 'ContactReference') {
1878 $params['fk_table_name'] = 'civicrm_contact';
1879 $params['fk_field_name'] = 'id';
1880 $params['fk_attributes'] = 'ON DELETE SET NULL';
1882 if (isset($field->default_value
)) {
1883 $params['default'] = "'{$field->default_value}'";
1886 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1890 * Determine whether it would be safe to move a field.
1892 * @param int $fieldID
1893 * FK to civicrm_custom_field.
1894 * @param int $newGroupID
1895 * FK to civicrm_custom_group.
1898 * array(string) or TRUE
1900 public static function _moveFieldValidate($fieldID, $newGroupID) {
1903 $field = new CRM_Core_DAO_CustomField();
1904 $field->id
= $fieldID;
1905 if (!$field->find(TRUE)) {
1906 $errors['fieldID'] = 'Invalid ID for custom field';
1910 $oldGroup = new CRM_Core_DAO_CustomGroup();
1911 $oldGroup->id
= $field->custom_group_id
;
1912 if (!$oldGroup->find(TRUE)) {
1913 $errors['fieldID'] = 'Invalid ID for old custom group';
1917 $newGroup = new CRM_Core_DAO_CustomGroup();
1918 $newGroup->id
= $newGroupID;
1919 if (!$newGroup->find(TRUE)) {
1920 $errors['newGroupID'] = 'Invalid ID for new custom group';
1926 FROM civicrm_custom_field a
1927 INNER JOIN civicrm_custom_field b
1929 AND a.label = b.label
1930 AND b.custom_group_id = %2
1933 1 => array($field->id
, 'Integer'),
1934 2 => array($newGroup->id
, 'Integer'),
1936 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1938 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1941 $tableName = $oldGroup->table_name
;
1942 $columnName = $field->column_name
;
1947 WHERE $columnName is not null
1949 $count = CRM_Core_DAO
::singleValueQuery($query,
1950 CRM_Core_DAO
::$_nullArray
1955 FROM civicrm_custom_group
1956 WHERE id IN ( %1, %2 )
1959 1 => array($oldGroup->id
, 'Integer'),
1960 2 => array($newGroup->id
, 'Integer'),
1963 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1965 while ($dao->fetch()) {
1966 $extends[] = $dao->extends;
1968 if ($extends[0] != $extends[1]) {
1969 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1973 return empty($errors) ?
TRUE : $errors;
1977 * Move a custom data field from one group (table) to another
1979 * @param int $fieldID
1980 * FK to civicrm_custom_field.
1981 * @param int $newGroupID
1982 * FK to civicrm_custom_group.
1986 public static function moveField($fieldID, $newGroupID) {
1987 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1988 if (TRUE !== $validation) {
1989 CRM_Core_Error
::fatal(implode(' ', $validation));
1991 $field = new CRM_Core_DAO_CustomField();
1992 $field->id
= $fieldID;
1995 $newGroup = new CRM_Core_DAO_CustomGroup();
1996 $newGroup->id
= $newGroupID;
1997 $newGroup->find(TRUE);
1999 $oldGroup = new CRM_Core_DAO_CustomGroup();
2000 $oldGroup->id
= $field->custom_group_id
;
2001 $oldGroup->find(TRUE);
2004 $add->custom_group_id
= $newGroup->id
;
2005 self
::createField($add, 'add');
2007 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2008 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2009 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2011 CRM_Core_DAO
::executeQuery($sql);
2014 $del->custom_group_id
= $oldGroup->id
;
2015 self
::createField($del, 'delete');
2019 CRM_Utils_System
::flushCache();
2023 * Get the database table name and column name for a custom field.
2025 * @param int $fieldID
2026 * The fieldID of the custom field.
2027 * @param bool $force
2028 * Force the sql to be run again (primarily used for tests).
2031 * fatal is fieldID does not exists, else array of tableName, columnName
2033 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2034 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2035 $cache = CRM_Utils_Cache
::singleton();
2036 $fieldValues = $cache->get($cacheKey);
2037 if (empty($fieldValues) ||
$force) {
2039 SELECT cg.table_name, cf.column_name, cg.id
2040 FROM civicrm_custom_group cg,
2041 civicrm_custom_field cf
2042 WHERE cf.custom_group_id = cg.id
2044 $params = array(1 => array($fieldID, 'Integer'));
2045 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2047 if (!$dao->fetch()) {
2048 CRM_Core_Error
::fatal();
2051 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2052 $cache->set($cacheKey, $fieldValues);
2054 return $fieldValues;
2058 * Get custom option groups.
2060 * @param array $includeFieldIds
2061 * Ids of custom fields for which.
2062 * option groups must be included.
2064 * Currently this is required in the cases where option groups are to be included
2065 * for inactive fields : CRM-5369
2070 public static function &customOptionGroup($includeFieldIds = NULL) {
2071 static $customOptionGroup = NULL;
2073 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2074 if ($cacheKey == 'force') {
2075 $customOptionGroup[$cacheKey] = NULL;
2078 if (empty($customOptionGroup[$cacheKey])) {
2079 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2081 //support for single as well as array format.
2082 if (!empty($includeFieldIds)) {
2083 if (is_array($includeFieldIds)) {
2084 $includeFieldIds = implode(',', $includeFieldIds);
2086 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2090 SELECT g.id, g.title
2091 FROM civicrm_option_group g
2092 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2093 WHERE {$whereClause}";
2095 $dao = CRM_Core_DAO
::executeQuery($query);
2096 while ($dao->fetch()) {
2097 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2101 return $customOptionGroup[$cacheKey];
2105 * Fix orphan groups.
2107 * @param int $customFieldId
2109 * @param int $optionGroupId
2114 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2115 // check if option group belongs to any custom Field else delete
2116 // get the current option group
2117 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2121 // get the updated option group
2122 // if both are same return
2123 if ($currentOptionGroupId == $optionGroupId) {
2127 // check if option group is related to any other field
2128 self
::checkOptionGroup($currentOptionGroupId);
2132 * Check if option group is related to more than one
2135 * @param int $optionGroupId
2140 public static function checkOptionGroup($optionGroupId) {
2143 FROM civicrm_custom_field
2144 WHERE option_group_id = {$optionGroupId}";
2146 $count = CRM_Core_DAO
::singleValueQuery($query);
2149 //delete the option group
2150 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2155 * @param int $optionGroupId
2158 * @return null|string
2160 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2162 SELECT default_value, html_type
2163 FROM civicrm_custom_field
2164 WHERE option_group_id = {$optionGroupId}
2165 AND default_value IS NOT NULL
2166 ORDER BY html_type";
2168 $dao = CRM_Core_DAO
::executeQuery($query);
2169 $defaultValue = NULL;
2170 $defaultHTMLType = NULL;
2171 while ($dao->fetch()) {
2172 if ($dao->html_type
== $htmlType) {
2173 return $dao->default_value
;
2175 if ($defaultValue == NULL) {
2176 $defaultValue = $dao->default_value
;
2177 $defaultHTMLType = $dao->html_type
;
2181 // some conversions are needed if either the old or new has a html type which has potential
2182 // multiple default values.
2183 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2184 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2186 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2188 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2189 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2191 $defaultValue = substr($defaultValue, 1, -1);
2192 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2193 substr($defaultValue, 1, -1)
2195 $defaultValue = $values[0];
2198 return $defaultValue;
2202 * @param array $params
2203 * @param $customFields
2204 * @param int $entityID
2205 * @param $customFieldExtends
2206 * @param bool $inline
2210 public static function postProcess(
2214 $customFieldExtends,
2217 $customData = array();
2219 foreach ($params as $key => $value) {
2220 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2222 // for autocomplete transfer hidden value instead of label
2223 if ($params[$key] && isset($params[$key . '_id'])) {
2224 $value = $params[$key . '_id'];
2227 // we need to append time with date
2228 if ($params[$key] && isset($params[$key . '_time'])) {
2229 $value .= ' ' . $params[$key . '_time'];
2232 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2235 $customFieldExtends,
2236 $customFieldInfo[1],
2251 public static function buildOption($field, &$options) {
2252 // Fixme - adding anything but options to the $options array is a bad idea
2253 // What if an option had the key 'attributes'?
2254 $options['attributes'] = array(
2255 'label' => $field['label'],
2256 'data_type' => $field['data_type'],
2257 'html_type' => $field['html_type'],
2260 $optionGroupID = NULL;
2261 if (($field['html_type'] == 'CheckBox' ||
2262 $field['html_type'] == 'Radio' ||
2263 $field['html_type'] == 'Select' ||
2264 $field['html_type'] == 'AdvMulti-Select' ||
2265 $field['html_type'] == 'Multi-Select' ||
2266 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2269 if ($field['option_group_id']) {
2270 $optionGroupID = $field['option_group_id'];
2272 elseif ($field['data_type'] != 'Boolean') {
2273 CRM_Core_Error
::fatal();
2277 // build the cache for custom values with options (label => value)
2278 if ($optionGroupID != NULL) {
2281 FROM civicrm_option_value
2282 WHERE option_group_id = $optionGroupID
2285 $dao = CRM_Core_DAO
::executeQuery($query);
2286 while ($dao->fetch()) {
2287 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2288 $num = round($dao->value
, 2);
2289 $options["$num"] = $dao->label
;
2292 $options[$dao->value
] = $dao->label
;
2296 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2301 * @param $fieldLabel
2302 * @param null $groupTitle
2306 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2307 $params = array(1 => array($fieldLabel, 'String'));
2309 $params[2] = array($groupTitle, 'String');
2312 FROM civicrm_custom_field f
2313 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2314 WHERE ( f.label = %1 OR f.name = %1 )
2315 AND ( g.title = %2 OR g.name = %2 )
2321 FROM civicrm_custom_field f
2322 WHERE ( f.label = %1 OR f.name = %1 )
2326 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2327 if ($dao->fetch() &&
2338 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2344 public static function getNameFromID($ids) {
2345 if (is_array($ids)) {
2346 $ids = implode(',', $ids);
2349 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2350 FROM civicrm_custom_field f
2351 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2352 WHERE f.id IN ($ids)";
2354 $dao = CRM_Core_DAO
::executeQuery($sql);
2356 while ($dao->fetch()) {
2357 $result[$dao->id
] = array(
2358 'field_name' => $dao->field_name
,
2359 'field_label' => $dao->field_label
,
2360 'group_name' => $dao->group_name
,
2361 'group_title' => $dao->group_title
,
2368 * Validate custom data.
2370 * @param array $params
2371 * Custom data submitted.
2372 * ie array( 'custom_1' => 'validate me' );
2375 * validation errors.
2377 public static function validateCustomData($params) {
2379 if (!is_array($params) ||
empty($params)) {
2383 //pick up profile fields.
2384 $profileFields = array();
2385 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2387 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2389 CRM_Core_Action
::VIEW
2393 //lets start w/ params.
2394 foreach ($params as $key => $value) {
2395 $customFieldID = self
::getKeyID($key);
2396 if (!$customFieldID) {
2400 //load the structural info for given field.
2401 $field = new CRM_Core_DAO_CustomField();
2402 $field->id
= $customFieldID;
2403 if (!$field->find(TRUE)) {
2406 $dataType = $field->data_type
;
2408 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2409 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2410 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2412 $fieldTitle = $field->label
;
2415 //no need to validate.
2416 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2420 //lets validate first for required field.
2421 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2422 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2426 //now time to take care of custom field form rules.
2427 $ruleName = $errorMsg = NULL;
2428 switch ($dataType) {
2430 $ruleName = 'integer';
2431 $errorMsg = ts('%1 must be an integer (whole number).',
2432 array(1 => $fieldTitle)
2437 $ruleName = 'money';
2438 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2439 array(1 => $fieldTitle)
2444 $ruleName = 'numeric';
2445 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2446 array(1 => $fieldTitle)
2451 $ruleName = 'wikiURL';
2452 $errorMsg = ts('%1 must be valid Website.',
2453 array(1 => $fieldTitle)
2458 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2460 $funName = "CRM_Utils_Rule::{$ruleName}";
2461 if (is_callable($funName)) {
2462 $valid = call_user_func($funName, $value);
2465 $errors[$key] = $errorMsg;
2474 * @param int $customId
2478 public static function isMultiRecordField($customId) {
2479 $isMultipleWithGid = FALSE;
2480 if (!is_numeric($customId)) {
2481 $customId = self
::getKeyID($customId);
2483 if (is_numeric($customId)) {
2484 $sql = "SELECT cg.id cgId
2485 FROM civicrm_custom_group cg
2486 INNER JOIN civicrm_custom_field cf
2487 ON cg.id = cf.custom_group_id
2488 WHERE cf.id = %1 AND cg.is_multiple = 1";
2489 $params[1] = array($customId, 'Integer');
2490 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2491 if ($dao->fetch()) {
2493 $isMultipleWithGid = $dao->cgId
;
2498 return $isMultipleWithGid;
2502 * Does this field store a serialized string?
2503 * @param CRM_Core_DAO_CustomField|array $field
2506 public static function isSerialized($field) {
2507 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2508 $field = (array) $field;
2509 // 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.
2510 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2514 * @param array $field
2515 * @param string|null $optionGroupName
2517 private static function getOptionsForField(&$field, $optionGroupName) {
2518 if ($optionGroupName) {
2519 $field['pseudoconstant'] = array(
2520 'optionGroupName' => $optionGroupName,
2521 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2524 elseif ($field['data_type'] == 'Boolean') {
2525 $field['pseudoconstant'] = array(
2526 'callback' => 'CRM_Core_SelectValues::boolean',
2529 elseif ($field['data_type'] == 'Country') {
2530 $field['pseudoconstant'] = array(
2531 'table' => 'civicrm_country',
2532 'keyColumn' => 'id',
2533 'labelColumn' => 'name',
2534 'nameColumn' => 'iso_code',
2537 elseif ($field['data_type'] == 'StateProvince') {
2538 $field['pseudoconstant'] = array(
2539 'table' => 'civicrm_state_province',
2540 'keyColumn' => 'id',
2541 'labelColumn' => 'name',