3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
72 * Data type => Description
75 public 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 public static function dataToHtml() {
99 if (!self
::$_dataToHtml) {
100 self
::$_dataToHtml = array(
103 'Select' => 'Select',
105 'CheckBox' => 'CheckBox',
106 'Multi-Select' => 'Multi-Select',
107 'AdvMulti-Select' => 'AdvMulti-Select',
108 'Autocomplete-Select' => 'Autocomplete-Select',
110 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
111 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
112 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
113 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
114 array('Date' => 'Select Date'),
115 array('Radio' => 'Radio'),
116 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
117 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
118 array('File' => 'File'),
119 array('Link' => 'Link'),
120 array('ContactReference' => 'Autocomplete-Select'),
123 return self
::$_dataToHtml;
127 * Takes an associative array and creates a custom field object
129 * This function is invoked from within the web form layer and also from the api layer
131 * @param array $params
132 * (reference) an assoc array of name/value pairs.
134 * @return CRM_Core_DAO_CustomField object
137 public static function create(&$params) {
138 $origParams = array_merge(array(), $params);
140 if (!isset($params['id'])) {
141 if (!isset($params['column_name'])) {
142 // if add mode & column_name not present, calculate it.
143 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
145 if (!isset($params['name'])) {
146 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
150 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
155 $columnName = $params['column_name'];
158 //as during create if field is_searchable we had created index.
159 if (!empty($params['id'])) {
160 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
163 switch (CRM_Utils_Array
::value('html_type', $params)) {
165 if (empty($params['date_format'])) {
166 $config = CRM_Core_Config
::singleton();
167 $params['date_format'] = $config->dateInputFormat
;
172 case 'AdvMulti-Select':
174 if (isset($params['default_checkbox_option'])) {
175 $tempArray = array_keys($params['default_checkbox_option']);
176 $defaultArray = array();
177 foreach ($tempArray as $k => $v) {
178 if ($params['option_value'][$v]) {
179 $defaultArray[] = $params['option_value'][$v];
183 if (!empty($defaultArray)) {
184 // also add the seperator before and after the value per new conventio (CRM-1604)
185 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
189 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
191 $params['default_value'] = $params['option_value'][$params['default_option']];
197 $transaction = new CRM_Core_Transaction();
198 // create any option group & values if required
199 if ($params['html_type'] != 'Text' &&
200 in_array($params['data_type'], array(
208 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
209 $params['custom_group_id'],
213 if ($params['option_type'] == 1 && empty($params['option_group_id'])) {
214 // first create an option group for this custom group
215 $optionGroup = new CRM_Core_DAO_OptionGroup();
216 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
217 $optionGroup->title
= $params['label'];
218 $optionGroup->is_active
= 1;
219 $optionGroup->save();
220 $params['option_group_id'] = $optionGroup->id
;
221 if (!empty($params['option_value']) && is_array($params['option_value'])) {
222 foreach ($params['option_value'] as $k => $v) {
223 if (strlen(trim($v))) {
224 $optionValue = new CRM_Core_DAO_OptionValue();
225 $optionValue->option_group_id
= $optionGroup->id
;
226 $optionValue->label
= $params['option_label'][$k];
227 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
228 switch ($params['data_type']) {
230 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
234 $optionValue->value
= intval($v);
238 $optionValue->value
= floatval($v);
242 $optionValue->value
= trim($v);
245 $optionValue->weight
= $params['option_weight'][$k];
246 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
247 $optionValue->save();
254 // check for orphan option groups
255 if (!empty($params['option_group_id'])) {
256 if (!empty($params['id'])) {
257 self
::fixOptionGroups($params['id'], $params['option_group_id']);
260 // if we dont have a default value
261 // retrive it from one of the other custom fields which use this option group
262 if (empty($params['default_value'])) {
263 //don't insert only value separator as default value, CRM-4579
264 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
268 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
272 $params['default_value'] = $defaultValue;
277 // since we need to save option group id :)
278 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
279 $params['attributes'] = 'rows=4, cols=60';
282 $customField = new CRM_Core_DAO_CustomField();
283 $customField->copyValues($params);
284 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
285 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
286 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $params, FALSE);
287 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
288 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, FALSE);
289 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
290 $customField->save();
292 // make sure all values are present in the object for further processing
293 $customField->find(TRUE);
295 $triggerRebuild = CRM_Utils_Array
::value('triggerRebuild', $params, TRUE);
296 //create/drop the index when we toggle the is_searchable flag
297 if (!empty($params['id'])) {
298 self
::createField($customField, 'modify', $indexExist, $triggerRebuild);
301 if (!isset($origParams['column_name'])) {
302 $columnName .= "_{$customField->id}";
303 $params['column_name'] = $columnName;
305 $customField->column_name
= $columnName;
306 $customField->save();
307 // make sure all values are present in the object
308 $customField->find(TRUE);
311 self
::createField($customField, 'add', $indexExist, $triggerRebuild);
314 // complete transaction
315 $transaction->commit();
317 CRM_Utils_System
::flushCache();
323 * Fetch object based on array of properties
325 * @param array $params
326 * (reference ) an assoc array of name/value pairs.
327 * @param array $defaults
328 * (reference ) an assoc array to hold the flattened values.
330 * @return CRM_Core_DAO_CustomField object
333 public static function retrieve(&$params, &$defaults) {
334 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
338 * Update the is_active flag in the db
341 * Id of the database record.
342 * @param bool $is_active
343 * Value we want to set the is_active field.
346 * DAO object on sucess, null otherwise
350 public static function setIsActive($id, $is_active) {
352 CRM_Utils_System
::flushCache();
354 //enable-disable CustomField
355 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
356 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
360 * Get the field title.
370 public static function getTitle($id) {
371 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
375 * Store and return an array of all active custom fields.
377 * @param string $customDataType
378 * Type of Custom Data; empty is a synonym for "all contact data types".
379 * @param bool $showAll
380 * If true returns all fields (includes disabled fields).
381 * @param bool $inline
382 * If true returns all inline fields (includes disabled fields).
383 * @param int $customDataSubType
384 * Custom Data sub type value.
385 * @param int $customDataSubName
386 * Custom Data sub name value.
387 * @param bool $onlyParent
388 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
389 * @param bool $onlySubType
390 * Return only custom data for subtype.
391 * @param bool $checkPermission
392 * If false, do not include permissioning clause.
395 * an array of active custom fields.
399 public static function &getFields(
400 $customDataType = 'Individual',
403 $customDataSubType = NULL,
404 $customDataSubName = NULL,
406 $onlySubType = FALSE,
407 $checkPermission = TRUE
409 if (empty($customDataType)) {
410 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
412 if ($customDataType && !is_array($customDataType)) {
414 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
415 // This is the case when getFieldsForImport() requires fields
416 // limited strictly to a subtype.
417 $customDataSubType = $customDataType;
418 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
422 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
423 // this makes the method flexible to support retrieving fields
424 // for multiple extends value.
425 $customDataType = array($customDataType);
429 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
431 if (is_array($customDataType)) {
432 $cacheKey = implode('_', $customDataType);
435 $cacheKey = $customDataType;
438 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
439 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
440 $cacheKey .= $showAll ?
'_1' : '_0';
441 $cacheKey .= $inline ?
'_1_' : '_0_';
442 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
443 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
444 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
446 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
448 // also get the permission stuff here
449 if ($checkPermission) {
450 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
455 $permissionClause = '(1)';
458 // lets md5 permission clause and take first 8 characters
459 $cacheKey .= substr(md5($permissionClause), 0, 8);
461 if (strlen($cacheKey) > 40) {
462 $cacheKey = md5($cacheKey);
465 if (!self
::$_importFields ||
466 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
468 if (!self
::$_importFields) {
469 self
::$_importFields = array();
472 // check if we can retrieve from database cache
473 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
475 if ($fields === NULL) {
476 $cfTable = self
::getTableName();
479 if (is_array($customDataType)) {
481 foreach ($customDataType as $dataType) {
482 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
483 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
484 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
487 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
489 $value = $value ?
$value . ", {$val}" : $val;
493 $extends = "AND $cgTable.extends IN ( $value ) ";
497 if (!empty($customDataType) && empty($extends)) {
498 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
499 self
::$_importFields[$cacheKey] = array();
500 return self
::$_importFields[$cacheKey];
504 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
507 $query = "SELECT $cfTable.id, $cfTable.label,
511 $cfTable.default_value,
512 $cfTable.options_per_line, $cfTable.text_length,
513 $cfTable.custom_group_id,
514 $cfTable.is_required,
515 $cgTable.extends, $cfTable.is_search_range,
516 $cgTable.extends_entity_column_value,
517 $cgTable.extends_entity_column_id,
519 $cfTable.option_group_id,
520 $cfTable.date_format,
521 $cfTable.time_format,
525 ON $cfTable.custom_group_id = $cgTable.id
529 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
533 $query .= " AND $cgTable.style = 'Inline' ";
536 //get the custom fields for specific type in
537 //combination with fields those support any type.
538 if (!empty($customDataSubType)) {
539 $subtypeClause = array();
540 foreach ($customDataSubType as $subtype) {
541 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
542 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
545 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
547 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
550 if ($customDataSubName) {
551 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
554 // also get the permission stuff here
555 if ($checkPermission) {
556 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
561 $permissionClause = '(1)';
564 $query .= " $extends AND $permissionClause
565 ORDER BY $cgTable.weight, $cgTable.title,
566 $cfTable.weight, $cfTable.label";
568 $dao = CRM_Core_DAO
::executeQuery($query);
571 while (($dao->fetch()) != NULL) {
572 $fields[$dao->id
]['label'] = $dao->label
;
573 $fields[$dao->id
]['groupTitle'] = $dao->title
;
574 $fields[$dao->id
]['data_type'] = $dao->data_type
;
575 $fields[$dao->id
]['html_type'] = $dao->html_type
;
576 $fields[$dao->id
]['default_value'] = $dao->default_value
;
577 $fields[$dao->id
]['text_length'] = $dao->text_length
;
578 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
579 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
580 $fields[$dao->id
]['extends'] = $dao->extends;
581 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
582 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
583 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
584 $fields[$dao->id
]['is_view'] = $dao->is_view
;
585 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
586 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
587 $fields[$dao->id
]['date_format'] = $dao->date_format
;
588 $fields[$dao->id
]['time_format'] = $dao->time_format
;
589 $fields[$dao->id
]['is_required'] = $dao->is_required
;
592 CRM_Core_BAO_Cache
::setItem($fields,
594 "custom importableFields $cacheKey"
597 self
::$_importFields[$cacheKey] = $fields;
600 return self
::$_importFields[$cacheKey];
604 * Return the field ids and names (with groups) for import purpose.
606 * @param int|string $contactType Contact type
607 * @param bool $showAll
608 * If true returns all fields (includes disabled fields).
609 * @param bool $onlyParent
610 * Return fields ONLY related to basic types.
611 * @param bool $search
612 * When called from search and multiple records need to be returned.
613 * @param bool $checkPermission
614 * If false, do not include permissioning clause.
616 * @param bool $withMultiple
623 public static function &getFieldsForImport(
624 $contactType = 'Individual',
628 $checkPermission = TRUE,
629 $withMultiple = FALSE
631 // Note: there are situations when we want getFieldsForImport() return fields related
632 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
633 $fields = &self
::getFields($contactType,
643 $importableFields = array();
644 foreach ($fields as $id => $values) {
645 // for now we should not allow multiple fields in profile / export etc, hence unsetting
647 (!empty($values['is_multiple']) && !$withMultiple)
652 /* generate the key for the fields array */
656 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
657 $importableFields[$key] = array(
659 'title' => CRM_Utils_Array
::value('label', $values),
660 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
662 'custom_field_id' => $id,
663 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
664 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
665 'data_type' => CRM_Utils_Array
::value('data_type', $values),
666 'html_type' => CRM_Utils_Array
::value('html_type', $values),
667 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
670 // CRM-6681, pass date and time format when html_type = Select Date
671 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
672 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
673 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
677 return $importableFields;
681 * Get the field id from an import key
687 * @return int|null The id (if exists)
690 public static function getKeyID($key, $all = FALSE) {
692 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
699 CRM_Utils_Array
::value(2, $match),
703 return $all ?
array(NULL, NULL) : NULL;
707 * Use the cache to get all values of a specific custom field
709 * @param int $fieldID
710 * The custom field ID.
712 * @return CRM_Core_DAO_CustomField $field the field object
716 public static function getFieldObject($fieldID) {
717 $field = new CRM_Core_DAO_CustomField();
719 // check if we can get the field values from the system cache
720 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
721 $cache = CRM_Utils_Cache
::singleton();
722 $fieldValues = $cache->get($cacheKey);
723 if (empty($fieldValues)) {
724 $field->id
= $fieldID;
725 if (!$field->find(TRUE)) {
726 CRM_Core_Error
::fatal();
729 $fieldValues = array();
730 CRM_Core_DAO
::storeValues($field, $fieldValues);
732 $cache->set($cacheKey, $fieldValues);
735 $field->copyValues($fieldValues);
742 * This function for building custom fields
744 * @param CRM_Core_Form $qf
745 * Form object (reference).
746 * @param string $elementName
747 * Name of the custom field.
748 * @param int $fieldId
749 * @param bool $inactiveNeeded
751 * @param bool $useRequired
752 * True if required else false.
753 * @param bool $search
754 * True if used for search else false.
755 * @param string $label
756 * Label for custom field.
760 public static function addQuickFormElement(
764 $inactiveNeeded = FALSE,
769 $field = self
::getFieldObject($fieldId);
770 $widget = $field->html_type
;
772 // Custom field HTML should indicate group+field name
773 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
774 $dataCrmCustomVal = $groupName . ':' . $field->name
;
775 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
776 $field->attributes
.= $dataCrmCustomAttr;
778 // Fixed for Issue CRM-2183
779 if ($widget == 'TextArea' && $search) {
783 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
785 // FIXME: Why are select state/country separate widget types?
786 $isSelect = (in_array($widget, array(
789 'Select State/Province',
790 'Multi-Select State/Province',
792 'Multi-Select Country',
799 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array(
800 'field' => "custom_$fieldId",
801 'context' => $search ?
'search' : 'create',
804 // Consolidate widget types to simplify the below switch statement
805 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
808 $selectAttributes = array(
809 'data-crm-custom' => $dataCrmCustomVal,
810 'class' => 'crm-select2',
812 // Search field is always multi-select
813 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
814 $selectAttributes['class'] .= ' huge';
815 $selectAttributes['multiple'] = 'multiple';
816 $selectAttributes['placeholder'] = $placeholder;
818 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
819 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
820 $selectAttributes +
= array(
821 'data-api-entity' => 'contact',
822 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
823 'data-api-field' => 'custom_' . $field->id
,
824 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
829 if (!isset($label)) {
830 $label = $field->label
;
834 * at some point in time we might want to split the below into small functions
840 if ($field->is_search_range
&& $search) {
841 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
842 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
845 $element = &$qf->add('text', $elementName, $label,
847 $useRequired && !$search
853 $attributes = $dataCrmCustomAttr;
854 if ($field->note_rows
) {
855 $attributes .= 'rows=' . $field->note_rows
;
858 $attributes .= 'rows=4';
860 if ($field->note_columns
) {
861 $attributes .= ' cols=' . $field->note_columns
;
864 $attributes .= ' cols=60';
866 if ($field->text_length
) {
867 $attributes .= ' maxlength=' . $field->text_length
;
869 $element = &$qf->add('textarea',
873 $useRequired && !$search
878 if ($field->is_search_range
&& $search) {
879 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
881 'format' => $field->date_format
,
882 'timeFormat' => $field->time_format
,
883 'startOffset' => $field->start_date_years
,
884 'endOffset' => $field->end_date_years
,
885 'data-crm-custom' => $dataCrmCustomVal,
889 $qf->addDate($elementName . '_to', ts('To'), FALSE,
891 'format' => $field->date_format
,
892 'timeFormat' => $field->time_format
,
893 'startOffset' => $field->start_date_years
,
894 'endOffset' => $field->end_date_years
,
895 'data-crm-custom' => $dataCrmCustomVal,
900 $required = $useRequired && !$search;
902 $qf->addDate($elementName, $label, $required, array(
903 'format' => $field->date_format
,
904 'timeFormat' => $field->time_format
,
905 'startOffset' => $field->start_date_years
,
906 'endOffset' => $field->end_date_years
,
907 'data-crm-custom' => $dataCrmCustomVal,
914 foreach ($options as $v => $l) {
915 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
917 $group = $qf->addGroup($choice, $elementName, $label);
918 if ($useRequired && !$search) {
919 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
922 $group->setAttribute('allowClear', TRUE);
926 // For all select elements
928 if (empty($selectAttributes['multiple'])) {
929 $options = array('' => $placeholder) +
$options;
931 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
933 // Add and/or option for fields that store multiple values
934 if ($search && self
::isSerialized($field)) {
937 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
938 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
940 $qf->addGroup($operators, $elementName . '_operator');
941 $qf->setDefaults(array($elementName . '_operator' => 'or'));
945 case 'AdvMulti-Select':
946 $include =& $qf->addElement(
953 'class' => 'advmultiselect',
954 'data-crm-custom' => $dataCrmCustomVal,
958 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
959 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
961 if ($useRequired && !$search) {
962 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
968 foreach ($options as $v => $l) {
969 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
971 $qf->addGroup($check, $elementName, $label);
972 if ($useRequired && !$search) {
973 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
978 // we should not build upload file in search mode
983 strtolower($field->html_type
),
987 $useRequired && !$search
989 $qf->addUploadElement($elementName);
992 case 'RichTextEditor':
994 'rows' => $field->note_rows
,
995 'cols' => $field->note_columns
,
996 'data-crm-custom' => $dataCrmCustomVal,
998 if ($field->text_length
) {
999 $attributes['maxlength'] = $field->text_length
;
1001 $qf->addWysiwyg($elementName, $label, $attributes, $search);
1004 case 'Autocomplete-Select':
1005 static $customUrls = array();
1006 // Fixme: why is this a string in the first place??
1007 $attributes = array();
1008 if ($field->attributes
) {
1009 foreach (explode(' ', $field->attributes
) as $at) {
1010 if (strpos($at, '=')) {
1011 list($k, $v) = explode('=', $at);
1012 $attributes[$k] = trim($v, ' "');
1016 if ($field->data_type
== 'ContactReference') {
1017 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1018 $attributes['data-api-entity'] = 'contact';
1019 $qf->add('text', $elementName, $label, $attributes,
1020 $useRequired && !$search
1023 $urlParams = "context=customfield&id={$field->id}";
1025 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1032 // FIXME: This won't work with customFieldOptions hook
1033 $attributes +
= array(
1034 'entity' => 'option_value',
1035 'placeholder' => $placeholder,
1036 'multiple' => $search,
1038 'params' => array('option_group_id' => $field->option_group_id
),
1041 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1044 $qf->assign('customUrls', $customUrls);
1048 switch ($field->data_type
) {
1050 // integers will have numeric rule applied to them.
1051 if ($field->is_search_range
&& $search) {
1052 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1053 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1055 elseif ($widget == 'Text') {
1056 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1061 if ($field->is_search_range
&& $search) {
1062 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1063 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1065 elseif ($widget == 'Text') {
1066 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1071 if ($field->is_search_range
&& $search) {
1072 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1073 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1075 elseif ($widget == 'Text') {
1076 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1081 $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
1082 $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
1083 $element->setAttribute('class', "url");
1084 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1087 if ($field->is_view
&& !$search) {
1088 $qf->freeze($elementName);
1093 * Delete the Custom Field.
1095 * @param object $field
1102 public static function deleteField($field) {
1103 CRM_Utils_System
::flushCache();
1105 // first delete the custom option group and values associated with this field
1106 if ($field->option_group_id
) {
1107 //check if option group is related to any other field, if
1108 //not delete the option group and related option values
1109 self
::checkOptionGroup($field->option_group_id
);
1112 // next drop the column from the custom value table
1113 self
::createField($field, 'delete');
1116 CRM_Core_BAO_UFField
::delUFField($field->id
);
1117 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1123 * Given a custom field value, its id and the set of options
1124 * find the display value for this field
1126 * @param mixed $value
1127 * The custom field value.
1129 * The custom field id.
1130 * @param int $options
1131 * The assoc array of option name/value pairs.
1133 * @param int $contactID
1134 * @param int $fieldID
1141 public static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1142 $option = &$options[$id];
1143 $attributes = &$option['attributes'];
1144 $html_type = $attributes['html_type'];
1145 $data_type = $attributes['data_type'];
1146 $format = CRM_Utils_Array
::value('format', $attributes);
1148 return self
::getDisplayValueCommon($value,
1163 * @param null $format
1164 * @param int $contactID
1165 * @param int $fieldID
1167 * @return array|mixed|null|string
1169 static function getDisplayValueCommon(
1181 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1182 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1183 $html_type == 'Select' ||
1184 $html_type == 'CheckBox' ||
1185 $html_type == 'AdvMulti-Select' ||
1186 $html_type == 'Multi-Select'
1189 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1192 switch ($html_type) {
1194 if ($data_type == 'Boolean') {
1195 // Do not assume that if not yes means no.
1198 $display = ts('Yes');
1200 elseif ((string) $value === '0') {
1201 $display = ts('No');
1205 $display = CRM_Utils_Array
::value($value, $option);
1209 case 'Autocomplete-Select':
1210 if ($data_type == 'ContactReference' &&
1213 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1216 $display = CRM_Utils_Array
::value($value, $option);
1221 $display = CRM_Utils_Array
::value($value, $option);
1225 case 'AdvMulti-Select':
1226 case 'Multi-Select':
1227 if (is_array($value)) {
1228 $checkedData = $value;
1231 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1232 substr($value, 1, -1)
1234 if ($html_type == 'CheckBox') {
1236 foreach ($checkedData as $v) {
1239 $checkedData = $newData;
1245 foreach ($checkedData as $key => $val) {
1246 if ($html_type == 'CheckBox') {
1249 $v[] = CRM_Utils_Array
::value($key, $option);
1254 $v[] = CRM_Utils_Array
::value($val, $option);
1258 $display = implode(', ', $v);
1263 if (is_array($value)) {
1264 foreach ($value as $key => $val) {
1265 $display[$key] = CRM_Utils_Date
::customFormat($val);
1269 // remove time element display if time is not set
1270 if (empty($option['attributes']['time_format'])) {
1271 $value = substr($value, 0, 10);
1273 $display = CRM_Utils_Date
::customFormat($value);
1277 case 'Select State/Province':
1278 if (empty($value)) {
1282 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1286 case 'Multi-Select State/Province':
1287 if (is_array($value)) {
1288 $checkedData = $value;
1291 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1292 substr($value, 1, -1)
1296 $states = CRM_Core_PseudoConstant
::stateProvince();
1298 foreach ($checkedData as $stateID) {
1302 $display .= $states[$stateID];
1306 case 'Select Country':
1307 if (empty($value)) {
1311 $display = CRM_Core_PseudoConstant
::country($value);
1315 case 'Multi-Select Country':
1316 if (is_array($value)) {
1317 $checkedData = $value;
1320 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1321 substr($value, 1, -1)
1325 $countries = CRM_Core_PseudoConstant
::country();
1327 foreach ($checkedData as $countryID) {
1331 $display .= $countries[$countryID];
1337 $url = self
::getFileURL($contactID, $fieldID, $value);
1339 $display = $url['file_url'];
1345 if (empty($value)) {
1349 $display = nl2br($value);
1354 if (empty($value)) {
1361 return $display ?
$display : $value;
1365 * Set default values for custom data used in profile
1367 * @param int $customFieldId
1369 * @param string $elementName
1370 * Custom field name.
1371 * @param array $defaults
1372 * Associated array of fields.
1373 * @param int $contactId
1377 * @param mixed $value
1378 * If passed - dont fetch value from db,.
1379 * just format the given value
1383 static function setProfileDefaults(
1391 //get the type of custom field
1392 $customField = new CRM_Core_BAO_CustomField();
1393 $customField->id
= $customFieldId;
1394 $customField->find(TRUE);
1397 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1398 $value = $customField->default_value
;
1402 if (!isset($value)) {
1403 $info = self
::getTableColumnGroup($customFieldId);
1404 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1405 $result = CRM_Core_DAO
::executeQuery($query);
1406 if ($result->fetch()) {
1407 $value = $result->value
;
1411 if ($customField->data_type
== 'Country') {
1413 $config = CRM_Core_Config
::singleton();
1414 if ($config->defaultContactCountry
) {
1415 $value = $config->defaultContactCountry();
1421 //set defaults if mode is registration
1422 if (!trim($value) &&
1424 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1426 $value = $customField->default_value
;
1429 if ($customField->data_type
== 'Money' && isset($value)) {
1430 $value = number_format($value, 2);
1432 switch ($customField->html_type
) {
1434 case 'AdvMulti-Select':
1435 case 'Multi-Select':
1436 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1437 $defaults[$elementName] = array();
1438 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1439 substr($value, 1, -1)
1441 foreach ($customOption as $val) {
1442 if (in_array($val['value'], $checkedValue)) {
1443 if ($customField->html_type
== 'CheckBox') {
1444 $defaults[$elementName][$val['value']] = 1;
1446 elseif ($customField->html_type
== 'Multi-Select' ||
1447 $customField->html_type
== 'AdvMulti-Select'
1449 $defaults[$elementName][$val['value']] = $val['value'];
1457 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1460 $customField->date_format
,
1461 $customField->time_format
1466 case 'Autocomplete-Select':
1467 if ($customField->data_type
== 'ContactReference') {
1468 if (is_numeric($value)) {
1469 $defaults[$elementName . '_id'] = $value;
1470 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1474 $defaults[$elementName] = $value;
1479 $defaults[$elementName] = $value;
1484 * @param int $contactID
1486 * @param int $fileID
1487 * @param bool $absolute
1492 * @param int $contactID
1494 * @param int $fileID
1495 * @param bool $absolute
1499 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1502 $params = array('id' => $cfID);
1503 $defaults = array();
1504 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1505 $columnName = $defaults['column_name'];
1507 //table name of custom data
1508 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1509 $defaults['custom_group_id'],
1513 //query to fetch id from civicrm_file
1514 if ($multiRecordWhereClause) {
1515 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1518 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1520 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1525 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1530 $result['file_id'] = $fileID;
1532 if ($fileType == 'image/jpeg' ||
1533 $fileType == 'image/pjpeg' ||
1534 $fileType == 'image/gif' ||
1535 $fileType == 'image/x-png' ||
1536 $fileType == 'image/png'
1538 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1543 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1544 list($imageWidth, $imageHeight) = getimagesize($path);
1545 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1546 $url = CRM_Utils_System
::url('civicrm/file',
1547 "reset=1&id=$fileID&eid=$contactID",
1548 $absolute, NULL, TRUE, TRUE
1550 $result['file_url'] = "
1551 <a href=\"$url\" class='crm-image-popup'>
1552 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1554 // for non image files
1557 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1561 $url = CRM_Utils_System
::url('civicrm/file',
1562 "reset=1&id=$fileID&eid=$contactID",
1563 $absolute, NULL, TRUE, TRUE
1565 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1573 * Format custom fields before inserting
1575 * @param int $customFieldId
1577 * @param array $customFormatted
1580 * Value of custom field.
1581 * @param string $customFieldExtend
1582 * Custom field extends.
1583 * @param int $customValueId
1584 * Custom option value id.
1585 * @param int $entityId
1586 * Entity id (contribution, membership...).
1587 * @param bool $inline
1588 * Consider inline custom groups only.
1589 * @param bool $checkPermission
1590 * If false, do not include permissioning clause.
1591 * @param bool $includeViewOnly
1592 * If true, fields marked 'View Only' are included. Required for APIv3.
1595 * formatted custom field array
1598 static function formatCustomField(
1599 $customFieldId, &$customFormatted, $value,
1600 $customFieldExtend, $customValueId = NULL,
1603 $checkPermission = TRUE,
1604 $includeViewOnly = FALSE
1606 //get the custom fields for the entity
1607 //subtype and basic type
1608 $customDataSubType = NULL;
1609 if (is_array($customFieldExtend)) {
1610 $customFieldExtend = $customFieldExtend[0];
1613 if (in_array($customFieldExtend,
1614 CRM_Contact_BAO_ContactType
::subTypes()
1616 // This is the case when getFieldsForImport() requires fields
1617 // of subtype and its parent.CRM-5143
1618 $customDataSubType = $customFieldExtend;
1619 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1622 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1632 if (!array_key_exists($customFieldId, $customFields)) {
1636 // return if field is a 'code' field
1637 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1641 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1643 if (!$customValueId &&
1644 // we always create new entites for is_multiple unless specified
1645 !$customFields[$customFieldId]['is_multiple'] &&
1651 WHERE entity_id={$entityId}";
1653 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1656 //fix checkbox, now check box always submits values
1657 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1659 // Note that only during merge this is not an array, and you can directly use value
1660 if (is_array($value)) {
1661 $selectedValues = array();
1662 foreach ($value as $selId => $val) {
1664 $selectedValues[] = $selId;
1667 if (!empty($selectedValues)) {
1668 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1670 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1679 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1680 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1683 // Note that only during merge this is not an array,
1684 // and you can directly use value, CRM-4385
1685 if (is_array($value)) {
1686 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1687 array_values($value)
1688 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1696 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1697 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1698 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1700 $customFields[$customFieldId]['data_type'] == 'String' &&
1701 !empty($customFields[$customFieldId]['text_length']) &&
1704 // lets make sure that value is less than the length, else we'll
1705 // be losing some data, CRM-7481
1706 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1707 // need to do a few things here
1709 // 1. lets find a new length
1710 $newLength = $customFields[$customFieldId]['text_length'];
1711 $minLength = strlen($value);
1712 while ($newLength < $minLength) {
1713 $newLength = $newLength * 2;
1716 // set the custom field meta data to have a length larger than value
1717 // alter the custom value table column to match this length
1718 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1723 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1724 if (!CRM_Utils_System
::isNull($value)) {
1725 $format = $customFields[$customFieldId]['date_format'];
1726 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1731 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1732 $customFields[$customFieldId]['data_type'] == 'Money'
1738 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1739 $value = CRM_Utils_Rule
::cleanMoney($value);
1743 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1744 $customFields[$customFieldId]['data_type'] == 'Country'
1754 if ($customFields[$customFieldId]['data_type'] == 'File') {
1755 if (empty($value)) {
1759 $config = CRM_Core_Config
::singleton();
1761 $fName = $value['name'];
1762 $mimeType = $value['type'];
1764 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1766 // rename this file to go into the secure directory
1767 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1768 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1771 if ($customValueId) {
1776 $params = array(1 => array($customValueId, 'Integer'));
1777 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1780 $fileDAO = new CRM_Core_DAO_File();
1783 $fileDAO->id
= $fileId;
1786 $fileDAO->uri
= $filename;
1787 $fileDAO->mime_type
= $mimeType;
1788 $fileDAO->upload_date
= date('Ymdhis');
1790 $fileId = $fileDAO->id
;
1794 if (!is_array($customFormatted)) {
1795 $customFormatted = array();
1798 if (!array_key_exists($customFieldId, $customFormatted)) {
1799 $customFormatted[$customFieldId] = array();
1803 if ($customValueId) {
1804 $index = $customValueId;
1807 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1808 $customFormatted[$customFieldId][$index] = array();
1810 $customFormatted[$customFieldId][$index] = array(
1811 'id' => $customValueId > 0 ?
$customValueId : NULL,
1813 'type' => $customFields[$customFieldId]['data_type'],
1814 'custom_field_id' => $customFieldId,
1815 'custom_group_id' => $groupID,
1816 'table_name' => $tableName,
1817 'column_name' => $columnName,
1818 'file_id' => $fileId,
1819 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1822 //we need to sort so that custom fields are created in the order of entry
1823 krsort($customFormatted[$customFieldId]);
1824 return $customFormatted;
1828 * @param array $params
1832 public static function &defaultCustomTableSchema(&$params) {
1833 // add the id and extends_id
1835 'name' => $params['name'],
1836 'is_multiple' => $params['is_multiple'],
1837 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1841 'type' => 'int unsigned',
1844 'attributes' => 'AUTO_INCREMENT',
1845 'comment' => 'Default MySQL primary key',
1848 'name' => 'entity_id',
1849 'type' => 'int unsigned',
1851 'comment' => 'Table that this extends',
1852 'fk_table_name' => $params['extends_name'],
1853 'fk_field_name' => 'id',
1854 'fk_attributes' => 'ON DELETE CASCADE',
1859 if (!$params['is_multiple']) {
1860 $table['indexes'] = array(
1863 'field_name_1' => 'entity_id',
1873 * @param bool $indexExist
1874 * @param bool $triggerRebuild
1876 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1877 $tableName = CRM_Core_DAO
::getFieldValue(
1878 'CRM_Core_DAO_CustomGroup',
1879 $field->custom_group_id
,
1884 'table_name' => $tableName,
1885 'operation' => $operation,
1886 'name' => $field->column_name
,
1887 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1891 'required' => $field->is_required
,
1892 'searchable' => $field->is_searchable
,
1895 if ($operation == 'delete') {
1896 $fkName = "{$tableName}_{$field->column_name}";
1897 if (strlen($fkName) >= 48) {
1898 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1900 $params['fkName'] = $fkName;
1902 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1903 $params['fk_table_name'] = 'civicrm_country';
1904 $params['fk_field_name'] = 'id';
1905 $params['fk_attributes'] = 'ON DELETE SET NULL';
1907 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1908 $params['type'] = 'varchar(255)';
1910 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1911 $params['fk_table_name'] = 'civicrm_state_province';
1912 $params['fk_field_name'] = 'id';
1913 $params['fk_attributes'] = 'ON DELETE SET NULL';
1915 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1916 $params['type'] = 'varchar(255)';
1918 elseif ($field->data_type
== 'File') {
1919 $params['fk_table_name'] = 'civicrm_file';
1920 $params['fk_field_name'] = 'id';
1921 $params['fk_attributes'] = 'ON DELETE SET NULL';
1923 elseif ($field->data_type
== 'ContactReference') {
1924 $params['fk_table_name'] = 'civicrm_contact';
1925 $params['fk_field_name'] = 'id';
1926 $params['fk_attributes'] = 'ON DELETE SET NULL';
1928 if (isset($field->default_value
)) {
1929 $params['default'] = "'{$field->default_value}'";
1932 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1936 * Determine whether it would be safe to move a field
1938 * @param int $fieldID
1939 * FK to civicrm_custom_field.
1940 * @param int $newGroupID
1941 * FK to civicrm_custom_group.
1946 public static function _moveFieldValidate($fieldID, $newGroupID) {
1949 $field = new CRM_Core_DAO_CustomField();
1950 $field->id
= $fieldID;
1951 if (!$field->find(TRUE)) {
1952 $errors['fieldID'] = 'Invalid ID for custom field';
1956 $oldGroup = new CRM_Core_DAO_CustomGroup();
1957 $oldGroup->id
= $field->custom_group_id
;
1958 if (!$oldGroup->find(TRUE)) {
1959 $errors['fieldID'] = 'Invalid ID for old custom group';
1963 $newGroup = new CRM_Core_DAO_CustomGroup();
1964 $newGroup->id
= $newGroupID;
1965 if (!$newGroup->find(TRUE)) {
1966 $errors['newGroupID'] = 'Invalid ID for new custom group';
1972 FROM civicrm_custom_field a
1973 INNER JOIN civicrm_custom_field b
1975 AND a.label = b.label
1976 AND b.custom_group_id = %2
1979 1 => array($field->id
, 'Integer'),
1980 2 => array($newGroup->id
, 'Integer'),
1982 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1984 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1987 $tableName = $oldGroup->table_name
;
1988 $columnName = $field->column_name
;
1993 WHERE $columnName is not null
1995 $count = CRM_Core_DAO
::singleValueQuery($query,
1996 CRM_Core_DAO
::$_nullArray
2001 FROM civicrm_custom_group
2002 WHERE id IN ( %1, %2 )
2005 1 => array($oldGroup->id
, 'Integer'),
2006 2 => array($newGroup->id
, 'Integer'),
2009 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2011 while ($dao->fetch()) {
2012 $extends[] = $dao->extends;
2014 if ($extends[0] != $extends[1]) {
2015 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
2019 return empty($errors) ?
TRUE : $errors;
2023 * Move a custom data field from one group (table) to another
2025 * @param int $fieldID
2026 * FK to civicrm_custom_field.
2027 * @param int $newGroupID
2028 * FK to civicrm_custom_group.
2032 public static function moveField($fieldID, $newGroupID) {
2033 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
2034 if (TRUE !== $validation) {
2035 CRM_Core_Error
::fatal(implode(' ', $validation));
2037 $field = new CRM_Core_DAO_CustomField();
2038 $field->id
= $fieldID;
2041 $newGroup = new CRM_Core_DAO_CustomGroup();
2042 $newGroup->id
= $newGroupID;
2043 $newGroup->find(TRUE);
2045 $oldGroup = new CRM_Core_DAO_CustomGroup();
2046 $oldGroup->id
= $field->custom_group_id
;
2047 $oldGroup->find(TRUE);
2050 $add->custom_group_id
= $newGroup->id
;
2051 self
::createField($add, 'add');
2053 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2054 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2055 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2057 CRM_Core_DAO
::executeQuery($sql);
2060 $del->custom_group_id
= $oldGroup->id
;
2061 self
::createField($del, 'delete');
2065 CRM_Utils_System
::flushCache();
2069 * Get the database table name and column name for a custom field
2071 * @param int $fieldID
2072 * The fieldID of the custom field.
2073 * @param bool $force
2074 * Force the sql to be run again (primarily used for tests).
2077 * fatal is fieldID does not exists, else array of tableName, columnName
2080 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2081 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2082 $cache = CRM_Utils_Cache
::singleton();
2083 $fieldValues = $cache->get($cacheKey);
2084 if (empty($fieldValues) ||
$force) {
2086 SELECT cg.table_name, cf.column_name, cg.id
2087 FROM civicrm_custom_group cg,
2088 civicrm_custom_field cf
2089 WHERE cf.custom_group_id = cg.id
2091 $params = array(1 => array($fieldID, 'Integer'));
2092 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2094 if (!$dao->fetch()) {
2095 CRM_Core_Error
::fatal();
2098 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2099 $cache->set($cacheKey, $fieldValues);
2101 return $fieldValues;
2105 * Get custom option groups
2107 * @param array $includeFieldIds
2108 * Ids of custom fields for which.
2109 * option groups must be included.
2111 * Currently this is required in the cases where option groups are to be included
2112 * for inactive fields : CRM-5369
2115 * @return mixed $customOptionGroup
2118 public static function &customOptionGroup($includeFieldIds = NULL) {
2119 static $customOptionGroup = NULL;
2121 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2122 if ($cacheKey == 'force') {
2123 $customOptionGroup[$cacheKey] = NULL;
2126 if (empty($customOptionGroup[$cacheKey])) {
2127 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2129 //support for single as well as array format.
2130 if (!empty($includeFieldIds)) {
2131 if (is_array($includeFieldIds)) {
2132 $includeFieldIds = implode(',', $includeFieldIds);
2134 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2138 SELECT g.id, g.title
2139 FROM civicrm_option_group g
2140 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2141 WHERE {$whereClause}";
2143 $dao = CRM_Core_DAO
::executeQuery($query);
2144 while ($dao->fetch()) {
2145 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2149 return $customOptionGroup[$cacheKey];
2155 * @param int $customFieldId
2157 * @param int $optionGroupId
2163 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2164 // check if option group belongs to any custom Field else delete
2165 // get the current option group
2166 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2170 // get the updated option group
2171 // if both are same return
2172 if ($currentOptionGroupId == $optionGroupId) {
2176 // check if option group is related to any other field
2177 self
::checkOptionGroup($currentOptionGroupId);
2181 * Check if option group is related to more than one
2184 * @param int $optionGroupId
2190 public static function checkOptionGroup($optionGroupId) {
2193 FROM civicrm_custom_field
2194 WHERE option_group_id = {$optionGroupId}";
2196 $count = CRM_Core_DAO
::singleValueQuery($query);
2199 //delete the option group
2200 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2205 * @param int $optionGroupId
2208 * @return null|string
2210 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2212 SELECT default_value, html_type
2213 FROM civicrm_custom_field
2214 WHERE option_group_id = {$optionGroupId}
2215 AND default_value IS NOT NULL
2216 ORDER BY html_type";
2218 $dao = CRM_Core_DAO
::executeQuery($query);
2219 $defaultValue = NULL;
2220 $defaultHTMLType = NULL;
2221 while ($dao->fetch()) {
2222 if ($dao->html_type
== $htmlType) {
2223 return $dao->default_value
;
2225 if ($defaultValue == NULL) {
2226 $defaultValue = $dao->default_value
;
2227 $defaultHTMLType = $dao->html_type
;
2231 // some conversions are needed if either the old or new has a html type which has potential
2232 // multiple default values.
2233 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2234 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2236 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2238 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2239 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2241 $defaultValue = substr($defaultValue, 1, -1);
2242 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2243 substr($defaultValue, 1, -1)
2245 $defaultValue = $values[0];
2248 return $defaultValue;
2252 * @param array $params
2253 * @param $customFields
2254 * @param int $entityID
2255 * @param $customFieldExtends
2256 * @param bool $inline
2260 static function postProcess(
2264 $customFieldExtends,
2267 $customData = array();
2269 foreach ($params as $key => $value) {
2270 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2272 // for autocomplete transfer hidden value instead of label
2273 if ($params[$key] && isset($params[$key . '_id'])) {
2274 $value = $params[$key . '_id'];
2277 // we need to append time with date
2278 if ($params[$key] && isset($params[$key . '_time'])) {
2279 $value .= ' ' . $params[$key . '_time'];
2282 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2285 $customFieldExtends,
2286 $customFieldInfo[1],
2301 public static function buildOption($field, &$options) {
2302 // Fixme - adding anything but options to the $options array is a bad idea
2303 // What if an option had the key 'attributes'?
2304 $options['attributes'] = array(
2305 'label' => $field['label'],
2306 'data_type' => $field['data_type'],
2307 'html_type' => $field['html_type'],
2310 $optionGroupID = NULL;
2311 if (($field['html_type'] == 'CheckBox' ||
2312 $field['html_type'] == 'Radio' ||
2313 $field['html_type'] == 'Select' ||
2314 $field['html_type'] == 'AdvMulti-Select' ||
2315 $field['html_type'] == 'Multi-Select' ||
2316 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2319 if ($field['option_group_id']) {
2320 $optionGroupID = $field['option_group_id'];
2322 elseif ($field['data_type'] != 'Boolean') {
2323 CRM_Core_Error
::fatal();
2327 // build the cache for custom values with options (label => value)
2328 if ($optionGroupID != NULL) {
2331 FROM civicrm_option_value
2332 WHERE option_group_id = $optionGroupID
2335 $dao = CRM_Core_DAO
::executeQuery($query);
2336 while ($dao->fetch()) {
2337 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2338 $num = round($dao->value
, 2);
2339 $options["$num"] = $dao->label
;
2342 $options[$dao->value
] = $dao->label
;
2346 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2351 * @param $fieldLabel
2352 * @param null $groupTitle
2356 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2357 $params = array(1 => array($fieldLabel, 'String'));
2359 $params[2] = array($groupTitle, 'String');
2362 FROM civicrm_custom_field f
2363 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2364 WHERE ( f.label = %1 OR f.name = %1 )
2365 AND ( g.title = %2 OR g.name = %2 )
2371 FROM civicrm_custom_field f
2372 WHERE ( f.label = %1 OR f.name = %1 )
2376 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2377 if ($dao->fetch() &&
2388 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2390 public static function getNameFromID($ids) {
2391 if (is_array($ids)) {
2392 $ids = implode(',', $ids);
2395 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2396 FROM civicrm_custom_field f
2397 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2398 WHERE f.id IN ($ids)";
2400 $dao = CRM_Core_DAO
::executeQuery($sql);
2402 while ($dao->fetch()) {
2403 $result[$dao->id
] = array(
2404 'field_name' => $dao->field_name
,
2405 'field_label' => $dao->field_label
,
2406 'group_name' => $dao->group_name
,
2407 'group_title' => $dao->group_title
,
2414 * Validate custom data.
2416 * @param array $params
2417 * Custom data submitted.
2418 * ie array( 'custom_1' => 'validate me' );
2421 * validation errors.
2424 public static function validateCustomData($params) {
2426 if (!is_array($params) ||
empty($params)) {
2430 //pick up profile fields.
2431 $profileFields = array();
2432 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2434 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2436 CRM_Core_Action
::VIEW
2440 //lets start w/ params.
2441 foreach ($params as $key => $value) {
2442 $customFieldID = self
::getKeyID($key);
2443 if (!$customFieldID) {
2447 //load the structural info for given field.
2448 $field = new CRM_Core_DAO_CustomField();
2449 $field->id
= $customFieldID;
2450 if (!$field->find(TRUE)) {
2453 $dataType = $field->data_type
;
2455 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2456 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2457 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2459 $fieldTitle = $field->label
;
2462 //no need to validate.
2463 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2467 //lets validate first for required field.
2468 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2469 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2473 //now time to take care of custom field form rules.
2474 $ruleName = $errorMsg = NULL;
2475 switch ($dataType) {
2477 $ruleName = 'integer';
2478 $errorMsg = ts('%1 must be an integer (whole number).',
2479 array(1 => $fieldTitle)
2484 $ruleName = 'money';
2485 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2486 array(1 => $fieldTitle)
2491 $ruleName = 'numeric';
2492 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2493 array(1 => $fieldTitle)
2498 $ruleName = 'wikiURL';
2499 $errorMsg = ts('%1 must be valid Website.',
2500 array(1 => $fieldTitle)
2505 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2507 $funName = "CRM_Utils_Rule::{$ruleName}";
2508 if (is_callable($funName)) {
2509 $valid = call_user_func($funName, $value);
2512 $errors[$key] = $errorMsg;
2521 * @param int $customId
2525 public static function isMultiRecordField($customId) {
2526 $isMultipleWithGid = FALSE;
2527 if (!is_numeric($customId)) {
2528 $customId = self
::getKeyID($customId);
2530 if (is_numeric($customId)) {
2531 $sql = "SELECT cg.id cgId
2532 FROM civicrm_custom_group cg
2533 INNER JOIN civicrm_custom_field cf
2534 ON cg.id = cf.custom_group_id
2535 WHERE cf.id = %1 AND cg.is_multiple = 1";
2536 $params[1] = array($customId, 'Integer');
2537 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2538 if ($dao->fetch()) {
2540 $isMultipleWithGid = $dao->cgId
;
2545 return $isMultipleWithGid;
2549 * Does this field store a serialized string?
2550 * @param CRM_Core_DAO_CustomField|array $field
2553 public static function isSerialized($field) {
2554 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2555 $field = (array) $field;
2556 // 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.
2557 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);