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.
371 public static function getTitle($id) {
372 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
376 * Store and return an array of all active custom fields.
378 * @param string $customDataType
379 * Type of Custom Data; empty is a synonym for "all contact data types".
380 * @param bool $showAll
381 * If true returns all fields (includes disabled fields).
382 * @param bool $inline
383 * If true returns all inline fields (includes disabled fields).
384 * @param int $customDataSubType
385 * Custom Data sub type value.
386 * @param int $customDataSubName
387 * Custom Data sub name value.
388 * @param bool $onlyParent
389 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
390 * @param bool $onlySubType
391 * Return only custom data for subtype.
392 * @param bool $checkPermission
393 * If false, do not include permissioning clause.
396 * an array of active custom fields.
400 public static function &getFields(
401 $customDataType = 'Individual',
404 $customDataSubType = NULL,
405 $customDataSubName = NULL,
407 $onlySubType = FALSE,
408 $checkPermission = TRUE
410 if (empty($customDataType)) {
411 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
413 if ($customDataType && !is_array($customDataType)) {
415 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
416 // This is the case when getFieldsForImport() requires fields
417 // limited strictly to a subtype.
418 $customDataSubType = $customDataType;
419 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
423 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
424 // this makes the method flexible to support retrieving fields
425 // for multiple extends value.
426 $customDataType = array($customDataType);
430 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
432 if (is_array($customDataType)) {
433 $cacheKey = implode('_', $customDataType);
436 $cacheKey = $customDataType;
439 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
440 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
441 $cacheKey .= $showAll ?
'_1' : '_0';
442 $cacheKey .= $inline ?
'_1_' : '_0_';
443 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
444 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
445 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
447 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
449 // also get the permission stuff here
450 if ($checkPermission) {
451 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
456 $permissionClause = '(1)';
459 // lets md5 permission clause and take first 8 characters
460 $cacheKey .= substr(md5($permissionClause), 0, 8);
462 if (strlen($cacheKey) > 40) {
463 $cacheKey = md5($cacheKey);
466 if (!self
::$_importFields ||
467 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
469 if (!self
::$_importFields) {
470 self
::$_importFields = array();
473 // check if we can retrieve from database cache
474 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
476 if ($fields === NULL) {
477 $cfTable = self
::getTableName();
480 if (is_array($customDataType)) {
482 foreach ($customDataType as $dataType) {
483 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
484 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
485 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
488 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
490 $value = $value ?
$value . ", {$val}" : $val;
494 $extends = "AND $cgTable.extends IN ( $value ) ";
498 if (!empty($customDataType) && empty($extends)) {
499 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
500 self
::$_importFields[$cacheKey] = array();
501 return self
::$_importFields[$cacheKey];
505 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
508 $query = "SELECT $cfTable.id, $cfTable.label,
512 $cfTable.default_value,
513 $cfTable.options_per_line, $cfTable.text_length,
514 $cfTable.custom_group_id,
515 $cfTable.is_required,
516 $cgTable.extends, $cfTable.is_search_range,
517 $cgTable.extends_entity_column_value,
518 $cgTable.extends_entity_column_id,
520 $cfTable.option_group_id,
521 $cfTable.date_format,
522 $cfTable.time_format,
526 ON $cfTable.custom_group_id = $cgTable.id
530 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
534 $query .= " AND $cgTable.style = 'Inline' ";
537 //get the custom fields for specific type in
538 //combination with fields those support any type.
539 if (!empty($customDataSubType)) {
540 $subtypeClause = array();
541 foreach ($customDataSubType as $subtype) {
542 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
543 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
546 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
548 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
551 if ($customDataSubName) {
552 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
555 // also get the permission stuff here
556 if ($checkPermission) {
557 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
562 $permissionClause = '(1)';
565 $query .= " $extends AND $permissionClause
566 ORDER BY $cgTable.weight, $cgTable.title,
567 $cfTable.weight, $cfTable.label";
569 $dao = CRM_Core_DAO
::executeQuery($query);
572 while (($dao->fetch()) != NULL) {
573 $fields[$dao->id
]['label'] = $dao->label
;
574 $fields[$dao->id
]['groupTitle'] = $dao->title
;
575 $fields[$dao->id
]['data_type'] = $dao->data_type
;
576 $fields[$dao->id
]['html_type'] = $dao->html_type
;
577 $fields[$dao->id
]['default_value'] = $dao->default_value
;
578 $fields[$dao->id
]['text_length'] = $dao->text_length
;
579 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
580 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
581 $fields[$dao->id
]['extends'] = $dao->extends;
582 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
583 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
584 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
585 $fields[$dao->id
]['is_view'] = $dao->is_view
;
586 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
587 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
588 $fields[$dao->id
]['date_format'] = $dao->date_format
;
589 $fields[$dao->id
]['time_format'] = $dao->time_format
;
590 $fields[$dao->id
]['is_required'] = $dao->is_required
;
593 CRM_Core_BAO_Cache
::setItem($fields,
595 "custom importableFields $cacheKey"
598 self
::$_importFields[$cacheKey] = $fields;
601 return self
::$_importFields[$cacheKey];
605 * Return the field ids and names (with groups) for import purpose.
607 * @param int|string $contactType Contact type
608 * @param bool $showAll
609 * If true returns all fields (includes disabled fields).
610 * @param bool $onlyParent
611 * Return fields ONLY related to basic types.
612 * @param bool $search
613 * When called from search and multiple records need to be returned.
614 * @param bool $checkPermission
615 * If false, do not include permissioning clause.
617 * @param bool $withMultiple
624 public static function &getFieldsForImport(
625 $contactType = 'Individual',
629 $checkPermission = TRUE,
630 $withMultiple = FALSE
632 // Note: there are situations when we want getFieldsForImport() return fields related
633 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
634 $fields = &self
::getFields($contactType,
644 $importableFields = array();
645 foreach ($fields as $id => $values) {
646 // for now we should not allow multiple fields in profile / export etc, hence unsetting
648 (!empty($values['is_multiple']) && !$withMultiple)
653 /* generate the key for the fields array */
657 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
658 $importableFields[$key] = array(
660 'title' => CRM_Utils_Array
::value('label', $values),
661 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
663 'custom_field_id' => $id,
664 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
665 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
666 'data_type' => CRM_Utils_Array
::value('data_type', $values),
667 'html_type' => CRM_Utils_Array
::value('html_type', $values),
668 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
671 // CRM-6681, pass date and time format when html_type = Select Date
672 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
673 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
674 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
678 return $importableFields;
682 * Get the field id from an import key
688 * @return int|null The id (if exists)
691 public static function getKeyID($key, $all = FALSE) {
693 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
700 CRM_Utils_Array
::value(2, $match),
704 return $all ?
array(NULL, NULL) : NULL;
708 * Use the cache to get all values of a specific custom field
710 * @param int $fieldID
711 * The custom field ID.
713 * @return CRM_Core_DAO_CustomField $field the field object
717 public static function getFieldObject($fieldID) {
718 $field = new CRM_Core_DAO_CustomField();
720 // check if we can get the field values from the system cache
721 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
722 $cache = CRM_Utils_Cache
::singleton();
723 $fieldValues = $cache->get($cacheKey);
724 if (empty($fieldValues)) {
725 $field->id
= $fieldID;
726 if (!$field->find(TRUE)) {
727 CRM_Core_Error
::fatal();
730 $fieldValues = array();
731 CRM_Core_DAO
::storeValues($field, $fieldValues);
733 $cache->set($cacheKey, $fieldValues);
736 $field->copyValues($fieldValues);
743 * This function for building custom fields
745 * @param CRM_Core_Form $qf
746 * Form object (reference).
747 * @param string $elementName
748 * Name of the custom field.
749 * @param int $fieldId
750 * @param bool $inactiveNeeded
752 * @param bool $useRequired
753 * True if required else false.
754 * @param bool $search
755 * True if used for search else false.
756 * @param string $label
757 * Label for custom field.
761 public static function addQuickFormElement(
765 $inactiveNeeded = FALSE,
770 $field = self
::getFieldObject($fieldId);
771 $widget = $field->html_type
;
773 // Custom field HTML should indicate group+field name
774 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
775 $dataCrmCustomVal = $groupName . ':' . $field->name
;
776 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
777 $field->attributes
.= $dataCrmCustomAttr;
779 // Fixed for Issue CRM-2183
780 if ($widget == 'TextArea' && $search) {
784 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
786 // FIXME: Why are select state/country separate widget types?
787 $isSelect = (in_array($widget, array(
790 'Select State/Province',
791 'Multi-Select State/Province',
793 'Multi-Select Country',
800 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array(
801 'field' => "custom_$fieldId",
802 'context' => $search ?
'search' : 'create',
805 // Consolidate widget types to simplify the below switch statement
806 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
809 $selectAttributes = array(
810 'data-crm-custom' => $dataCrmCustomVal,
811 'class' => 'crm-select2',
813 // Search field is always multi-select
814 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
815 $selectAttributes['class'] .= ' huge';
816 $selectAttributes['multiple'] = 'multiple';
817 $selectAttributes['placeholder'] = $placeholder;
819 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
820 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
821 $selectAttributes +
= array(
822 'data-api-entity' => 'contact',
823 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
824 'data-api-field' => 'custom_' . $field->id
,
825 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
830 if (!isset($label)) {
831 $label = $field->label
;
835 * at some point in time we might want to split the below into small functions
841 if ($field->is_search_range
&& $search) {
842 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
843 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
846 $element = &$qf->add('text', $elementName, $label,
848 $useRequired && !$search
854 $attributes = $dataCrmCustomAttr;
855 if ($field->note_rows
) {
856 $attributes .= 'rows=' . $field->note_rows
;
859 $attributes .= 'rows=4';
861 if ($field->note_columns
) {
862 $attributes .= ' cols=' . $field->note_columns
;
865 $attributes .= ' cols=60';
867 if ($field->text_length
) {
868 $attributes .= ' maxlength=' . $field->text_length
;
870 $element = &$qf->add('textarea',
874 $useRequired && !$search
879 if ($field->is_search_range
&& $search) {
880 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
882 'format' => $field->date_format
,
883 'timeFormat' => $field->time_format
,
884 'startOffset' => $field->start_date_years
,
885 'endOffset' => $field->end_date_years
,
886 'data-crm-custom' => $dataCrmCustomVal,
890 $qf->addDate($elementName . '_to', ts('To'), FALSE,
892 'format' => $field->date_format
,
893 'timeFormat' => $field->time_format
,
894 'startOffset' => $field->start_date_years
,
895 'endOffset' => $field->end_date_years
,
896 'data-crm-custom' => $dataCrmCustomVal,
901 $required = $useRequired && !$search;
903 $qf->addDate($elementName, $label, $required, array(
904 'format' => $field->date_format
,
905 'timeFormat' => $field->time_format
,
906 'startOffset' => $field->start_date_years
,
907 'endOffset' => $field->end_date_years
,
908 'data-crm-custom' => $dataCrmCustomVal,
915 foreach ($options as $v => $l) {
916 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
918 $group = $qf->addGroup($choice, $elementName, $label);
919 if ($useRequired && !$search) {
920 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
923 $group->setAttribute('allowClear', TRUE);
927 // For all select elements
929 if (empty($selectAttributes['multiple'])) {
930 $options = array('' => $placeholder) +
$options;
932 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
934 // Add and/or option for fields that store multiple values
935 if ($search && self
::isSerialized($field)) {
938 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
939 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
941 $qf->addGroup($operators, $elementName . '_operator');
942 $qf->setDefaults(array($elementName . '_operator' => 'or'));
946 case 'AdvMulti-Select':
947 $include =& $qf->addElement(
954 'class' => 'advmultiselect',
955 'data-crm-custom' => $dataCrmCustomVal,
959 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
960 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
962 if ($useRequired && !$search) {
963 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
969 foreach ($options as $v => $l) {
970 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
972 $qf->addGroup($check, $elementName, $label);
973 if ($useRequired && !$search) {
974 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
979 // we should not build upload file in search mode
984 strtolower($field->html_type
),
988 $useRequired && !$search
990 $qf->addUploadElement($elementName);
993 case 'RichTextEditor':
995 'rows' => $field->note_rows
,
996 'cols' => $field->note_columns
,
997 'data-crm-custom' => $dataCrmCustomVal,
999 if ($field->text_length
) {
1000 $attributes['maxlength'] = $field->text_length
;
1002 $qf->addWysiwyg($elementName, $label, $attributes, $search);
1005 case 'Autocomplete-Select':
1006 static $customUrls = array();
1007 // Fixme: why is this a string in the first place??
1008 $attributes = array();
1009 if ($field->attributes
) {
1010 foreach (explode(' ', $field->attributes
) as $at) {
1011 if (strpos($at, '=')) {
1012 list($k, $v) = explode('=', $at);
1013 $attributes[$k] = trim($v, ' "');
1017 if ($field->data_type
== 'ContactReference') {
1018 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1019 $attributes['data-api-entity'] = 'contact';
1020 $qf->add('text', $elementName, $label, $attributes,
1021 $useRequired && !$search
1024 $urlParams = "context=customfield&id={$field->id}";
1026 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1033 // FIXME: This won't work with customFieldOptions hook
1034 $attributes +
= array(
1035 'entity' => 'option_value',
1036 'placeholder' => $placeholder,
1037 'multiple' => $search,
1039 'params' => array('option_group_id' => $field->option_group_id
),
1042 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1045 $qf->assign('customUrls', $customUrls);
1049 switch ($field->data_type
) {
1051 // integers will have numeric rule applied to them.
1052 if ($field->is_search_range
&& $search) {
1053 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1054 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1056 elseif ($widget == 'Text') {
1057 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1062 if ($field->is_search_range
&& $search) {
1063 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1064 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1066 elseif ($widget == 'Text') {
1067 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1072 if ($field->is_search_range
&& $search) {
1073 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1074 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1076 elseif ($widget == 'Text') {
1077 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1082 $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
1083 $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
1084 $element->setAttribute('class', "url");
1085 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1088 if ($field->is_view
&& !$search) {
1089 $qf->freeze($elementName);
1094 * Delete the Custom Field.
1096 * @param object $field
1104 public static function deleteField($field) {
1105 CRM_Utils_System
::flushCache();
1107 // first delete the custom option group and values associated with this field
1108 if ($field->option_group_id
) {
1109 //check if option group is related to any other field, if
1110 //not delete the option group and related option values
1111 self
::checkOptionGroup($field->option_group_id
);
1114 // next drop the column from the custom value table
1115 self
::createField($field, 'delete');
1118 CRM_Core_BAO_UFField
::delUFField($field->id
);
1119 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1125 * Given a custom field value, its id and the set of options
1126 * find the display value for this field
1128 * @param mixed $value
1129 * The custom field value.
1131 * The custom field id.
1132 * @param int $options
1133 * The assoc array of option name/value pairs.
1135 * @param int $contactID
1136 * @param int $fieldID
1143 public static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1144 $option = &$options[$id];
1145 $attributes = &$option['attributes'];
1146 $html_type = $attributes['html_type'];
1147 $data_type = $attributes['data_type'];
1148 $format = CRM_Utils_Array
::value('format', $attributes);
1150 return self
::getDisplayValueCommon($value,
1165 * @param null $format
1166 * @param int $contactID
1167 * @param int $fieldID
1169 * @return array|mixed|null|string
1171 static function getDisplayValueCommon(
1183 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1184 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1185 $html_type == 'Select' ||
1186 $html_type == 'CheckBox' ||
1187 $html_type == 'AdvMulti-Select' ||
1188 $html_type == 'Multi-Select'
1191 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1194 switch ($html_type) {
1196 if ($data_type == 'Boolean') {
1197 // Do not assume that if not yes means no.
1200 $display = ts('Yes');
1202 elseif ((string) $value === '0') {
1203 $display = ts('No');
1207 $display = CRM_Utils_Array
::value($value, $option);
1211 case 'Autocomplete-Select':
1212 if ($data_type == 'ContactReference' &&
1215 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1218 $display = CRM_Utils_Array
::value($value, $option);
1223 $display = CRM_Utils_Array
::value($value, $option);
1227 case 'AdvMulti-Select':
1228 case 'Multi-Select':
1229 if (is_array($value)) {
1230 $checkedData = $value;
1233 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1234 substr($value, 1, -1)
1236 if ($html_type == 'CheckBox') {
1238 foreach ($checkedData as $v) {
1241 $checkedData = $newData;
1247 foreach ($checkedData as $key => $val) {
1248 if ($html_type == 'CheckBox') {
1251 $v[] = CRM_Utils_Array
::value($key, $option);
1256 $v[] = CRM_Utils_Array
::value($val, $option);
1260 $display = implode(', ', $v);
1265 if (is_array($value)) {
1266 foreach ($value as $key => $val) {
1267 $display[$key] = CRM_Utils_Date
::customFormat($val);
1271 // remove time element display if time is not set
1272 if (empty($option['attributes']['time_format'])) {
1273 $value = substr($value, 0, 10);
1275 $display = CRM_Utils_Date
::customFormat($value);
1279 case 'Select State/Province':
1280 if (empty($value)) {
1284 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1288 case 'Multi-Select State/Province':
1289 if (is_array($value)) {
1290 $checkedData = $value;
1293 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1294 substr($value, 1, -1)
1298 $states = CRM_Core_PseudoConstant
::stateProvince();
1300 foreach ($checkedData as $stateID) {
1304 $display .= $states[$stateID];
1308 case 'Select Country':
1309 if (empty($value)) {
1313 $display = CRM_Core_PseudoConstant
::country($value);
1317 case 'Multi-Select Country':
1318 if (is_array($value)) {
1319 $checkedData = $value;
1322 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1323 substr($value, 1, -1)
1327 $countries = CRM_Core_PseudoConstant
::country();
1329 foreach ($checkedData as $countryID) {
1333 $display .= $countries[$countryID];
1339 $url = self
::getFileURL($contactID, $fieldID, $value);
1341 $display = $url['file_url'];
1347 if (empty($value)) {
1351 $display = nl2br($value);
1356 if (empty($value)) {
1363 return $display ?
$display : $value;
1367 * Set default values for custom data used in profile
1369 * @param int $customFieldId
1371 * @param string $elementName
1372 * Custom field name.
1373 * @param array $defaults
1374 * Associated array of fields.
1375 * @param int $contactId
1379 * @param mixed $value
1380 * If passed - dont fetch value from db,.
1381 * just format the given value
1385 static function setProfileDefaults(
1393 //get the type of custom field
1394 $customField = new CRM_Core_BAO_CustomField();
1395 $customField->id
= $customFieldId;
1396 $customField->find(TRUE);
1399 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1400 $value = $customField->default_value
;
1404 if (!isset($value)) {
1405 $info = self
::getTableColumnGroup($customFieldId);
1406 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1407 $result = CRM_Core_DAO
::executeQuery($query);
1408 if ($result->fetch()) {
1409 $value = $result->value
;
1413 if ($customField->data_type
== 'Country') {
1415 $config = CRM_Core_Config
::singleton();
1416 if ($config->defaultContactCountry
) {
1417 $value = $config->defaultContactCountry();
1423 //set defaults if mode is registration
1424 if (!trim($value) &&
1426 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1428 $value = $customField->default_value
;
1431 if ($customField->data_type
== 'Money' && isset($value)) {
1432 $value = number_format($value, 2);
1434 switch ($customField->html_type
) {
1436 case 'AdvMulti-Select':
1437 case 'Multi-Select':
1438 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1439 $defaults[$elementName] = array();
1440 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1441 substr($value, 1, -1)
1443 foreach ($customOption as $val) {
1444 if (in_array($val['value'], $checkedValue)) {
1445 if ($customField->html_type
== 'CheckBox') {
1446 $defaults[$elementName][$val['value']] = 1;
1448 elseif ($customField->html_type
== 'Multi-Select' ||
1449 $customField->html_type
== 'AdvMulti-Select'
1451 $defaults[$elementName][$val['value']] = $val['value'];
1459 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1462 $customField->date_format
,
1463 $customField->time_format
1468 case 'Autocomplete-Select':
1469 if ($customField->data_type
== 'ContactReference') {
1470 if (is_numeric($value)) {
1471 $defaults[$elementName . '_id'] = $value;
1472 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1476 $defaults[$elementName] = $value;
1481 $defaults[$elementName] = $value;
1486 * @param int $contactID
1488 * @param int $fileID
1489 * @param bool $absolute
1494 * @param int $contactID
1496 * @param int $fileID
1497 * @param bool $absolute
1501 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1504 $params = array('id' => $cfID);
1505 $defaults = array();
1506 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1507 $columnName = $defaults['column_name'];
1509 //table name of custom data
1510 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1511 $defaults['custom_group_id'],
1515 //query to fetch id from civicrm_file
1516 if ($multiRecordWhereClause) {
1517 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1520 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1522 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1527 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1532 $result['file_id'] = $fileID;
1534 if ($fileType == 'image/jpeg' ||
1535 $fileType == 'image/pjpeg' ||
1536 $fileType == 'image/gif' ||
1537 $fileType == 'image/x-png' ||
1538 $fileType == 'image/png'
1540 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1545 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1546 list($imageWidth, $imageHeight) = getimagesize($path);
1547 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1548 $url = CRM_Utils_System
::url('civicrm/file',
1549 "reset=1&id=$fileID&eid=$contactID",
1550 $absolute, NULL, TRUE, TRUE
1552 $result['file_url'] = "
1553 <a href=\"$url\" class='crm-image-popup'>
1554 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1556 // for non image files
1559 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1563 $url = CRM_Utils_System
::url('civicrm/file',
1564 "reset=1&id=$fileID&eid=$contactID",
1565 $absolute, NULL, TRUE, TRUE
1567 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1575 * Format custom fields before inserting
1577 * @param int $customFieldId
1579 * @param array $customFormatted
1582 * Value of custom field.
1583 * @param string $customFieldExtend
1584 * Custom field extends.
1585 * @param int $customValueId
1586 * Custom option value id.
1587 * @param int $entityId
1588 * Entity id (contribution, membership...).
1589 * @param bool $inline
1590 * Consider inline custom groups only.
1591 * @param bool $checkPermission
1592 * If false, do not include permissioning clause.
1593 * @param bool $includeViewOnly
1594 * If true, fields marked 'View Only' are included. Required for APIv3.
1597 * formatted custom field array
1600 static function formatCustomField(
1601 $customFieldId, &$customFormatted, $value,
1602 $customFieldExtend, $customValueId = NULL,
1605 $checkPermission = TRUE,
1606 $includeViewOnly = FALSE
1608 //get the custom fields for the entity
1609 //subtype and basic type
1610 $customDataSubType = NULL;
1611 if (is_array($customFieldExtend)) {
1612 $customFieldExtend = $customFieldExtend[0];
1615 if (in_array($customFieldExtend,
1616 CRM_Contact_BAO_ContactType
::subTypes()
1618 // This is the case when getFieldsForImport() requires fields
1619 // of subtype and its parent.CRM-5143
1620 $customDataSubType = $customFieldExtend;
1621 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1624 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1634 if (!array_key_exists($customFieldId, $customFields)) {
1638 // return if field is a 'code' field
1639 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1643 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1645 if (!$customValueId &&
1646 // we always create new entites for is_multiple unless specified
1647 !$customFields[$customFieldId]['is_multiple'] &&
1653 WHERE entity_id={$entityId}";
1655 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1658 //fix checkbox, now check box always submits values
1659 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1661 // Note that only during merge this is not an array, and you can directly use value
1662 if (is_array($value)) {
1663 $selectedValues = array();
1664 foreach ($value as $selId => $val) {
1666 $selectedValues[] = $selId;
1669 if (!empty($selectedValues)) {
1670 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1672 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1681 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1682 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1685 // Note that only during merge this is not an array,
1686 // and you can directly use value, CRM-4385
1687 if (is_array($value)) {
1688 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1689 array_values($value)
1690 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1698 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1699 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1700 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1702 $customFields[$customFieldId]['data_type'] == 'String' &&
1703 !empty($customFields[$customFieldId]['text_length']) &&
1706 // lets make sure that value is less than the length, else we'll
1707 // be losing some data, CRM-7481
1708 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1709 // need to do a few things here
1711 // 1. lets find a new length
1712 $newLength = $customFields[$customFieldId]['text_length'];
1713 $minLength = strlen($value);
1714 while ($newLength < $minLength) {
1715 $newLength = $newLength * 2;
1718 // set the custom field meta data to have a length larger than value
1719 // alter the custom value table column to match this length
1720 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1725 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1726 if (!CRM_Utils_System
::isNull($value)) {
1727 $format = $customFields[$customFieldId]['date_format'];
1728 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1733 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1734 $customFields[$customFieldId]['data_type'] == 'Money'
1740 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1741 $value = CRM_Utils_Rule
::cleanMoney($value);
1745 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1746 $customFields[$customFieldId]['data_type'] == 'Country'
1756 if ($customFields[$customFieldId]['data_type'] == 'File') {
1757 if (empty($value)) {
1761 $config = CRM_Core_Config
::singleton();
1763 $fName = $value['name'];
1764 $mimeType = $value['type'];
1766 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1768 // rename this file to go into the secure directory
1769 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1770 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1773 if ($customValueId) {
1778 $params = array(1 => array($customValueId, 'Integer'));
1779 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1782 $fileDAO = new CRM_Core_DAO_File();
1785 $fileDAO->id
= $fileId;
1788 $fileDAO->uri
= $filename;
1789 $fileDAO->mime_type
= $mimeType;
1790 $fileDAO->upload_date
= date('Ymdhis');
1792 $fileId = $fileDAO->id
;
1796 if (!is_array($customFormatted)) {
1797 $customFormatted = array();
1800 if (!array_key_exists($customFieldId, $customFormatted)) {
1801 $customFormatted[$customFieldId] = array();
1805 if ($customValueId) {
1806 $index = $customValueId;
1809 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1810 $customFormatted[$customFieldId][$index] = array();
1812 $customFormatted[$customFieldId][$index] = array(
1813 'id' => $customValueId > 0 ?
$customValueId : NULL,
1815 'type' => $customFields[$customFieldId]['data_type'],
1816 'custom_field_id' => $customFieldId,
1817 'custom_group_id' => $groupID,
1818 'table_name' => $tableName,
1819 'column_name' => $columnName,
1820 'file_id' => $fileId,
1821 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1824 //we need to sort so that custom fields are created in the order of entry
1825 krsort($customFormatted[$customFieldId]);
1826 return $customFormatted;
1830 * @param array $params
1834 public static function &defaultCustomTableSchema(&$params) {
1835 // add the id and extends_id
1837 'name' => $params['name'],
1838 'is_multiple' => $params['is_multiple'],
1839 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1843 'type' => 'int unsigned',
1846 'attributes' => 'AUTO_INCREMENT',
1847 'comment' => 'Default MySQL primary key',
1850 'name' => 'entity_id',
1851 'type' => 'int unsigned',
1853 'comment' => 'Table that this extends',
1854 'fk_table_name' => $params['extends_name'],
1855 'fk_field_name' => 'id',
1856 'fk_attributes' => 'ON DELETE CASCADE',
1861 if (!$params['is_multiple']) {
1862 $table['indexes'] = array(
1865 'field_name_1' => 'entity_id',
1875 * @param bool $indexExist
1876 * @param bool $triggerRebuild
1878 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1879 $tableName = CRM_Core_DAO
::getFieldValue(
1880 'CRM_Core_DAO_CustomGroup',
1881 $field->custom_group_id
,
1886 'table_name' => $tableName,
1887 'operation' => $operation,
1888 'name' => $field->column_name
,
1889 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1893 'required' => $field->is_required
,
1894 'searchable' => $field->is_searchable
,
1897 if ($operation == 'delete') {
1898 $fkName = "{$tableName}_{$field->column_name}";
1899 if (strlen($fkName) >= 48) {
1900 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1902 $params['fkName'] = $fkName;
1904 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1905 $params['fk_table_name'] = 'civicrm_country';
1906 $params['fk_field_name'] = 'id';
1907 $params['fk_attributes'] = 'ON DELETE SET NULL';
1909 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1910 $params['type'] = 'varchar(255)';
1912 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1913 $params['fk_table_name'] = 'civicrm_state_province';
1914 $params['fk_field_name'] = 'id';
1915 $params['fk_attributes'] = 'ON DELETE SET NULL';
1917 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1918 $params['type'] = 'varchar(255)';
1920 elseif ($field->data_type
== 'File') {
1921 $params['fk_table_name'] = 'civicrm_file';
1922 $params['fk_field_name'] = 'id';
1923 $params['fk_attributes'] = 'ON DELETE SET NULL';
1925 elseif ($field->data_type
== 'ContactReference') {
1926 $params['fk_table_name'] = 'civicrm_contact';
1927 $params['fk_field_name'] = 'id';
1928 $params['fk_attributes'] = 'ON DELETE SET NULL';
1930 if (isset($field->default_value
)) {
1931 $params['default'] = "'{$field->default_value}'";
1934 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1938 * Determine whether it would be safe to move a field
1940 * @param int $fieldID
1941 * FK to civicrm_custom_field.
1942 * @param int $newGroupID
1943 * FK to civicrm_custom_group.
1948 public static function _moveFieldValidate($fieldID, $newGroupID) {
1951 $field = new CRM_Core_DAO_CustomField();
1952 $field->id
= $fieldID;
1953 if (!$field->find(TRUE)) {
1954 $errors['fieldID'] = 'Invalid ID for custom field';
1958 $oldGroup = new CRM_Core_DAO_CustomGroup();
1959 $oldGroup->id
= $field->custom_group_id
;
1960 if (!$oldGroup->find(TRUE)) {
1961 $errors['fieldID'] = 'Invalid ID for old custom group';
1965 $newGroup = new CRM_Core_DAO_CustomGroup();
1966 $newGroup->id
= $newGroupID;
1967 if (!$newGroup->find(TRUE)) {
1968 $errors['newGroupID'] = 'Invalid ID for new custom group';
1974 FROM civicrm_custom_field a
1975 INNER JOIN civicrm_custom_field b
1977 AND a.label = b.label
1978 AND b.custom_group_id = %2
1981 1 => array($field->id
, 'Integer'),
1982 2 => array($newGroup->id
, 'Integer'),
1984 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1986 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1989 $tableName = $oldGroup->table_name
;
1990 $columnName = $field->column_name
;
1995 WHERE $columnName is not null
1997 $count = CRM_Core_DAO
::singleValueQuery($query,
1998 CRM_Core_DAO
::$_nullArray
2003 FROM civicrm_custom_group
2004 WHERE id IN ( %1, %2 )
2007 1 => array($oldGroup->id
, 'Integer'),
2008 2 => array($newGroup->id
, 'Integer'),
2011 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2013 while ($dao->fetch()) {
2014 $extends[] = $dao->extends;
2016 if ($extends[0] != $extends[1]) {
2017 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
2021 return empty($errors) ?
TRUE : $errors;
2025 * Move a custom data field from one group (table) to another
2027 * @param int $fieldID
2028 * FK to civicrm_custom_field.
2029 * @param int $newGroupID
2030 * FK to civicrm_custom_group.
2034 public static function moveField($fieldID, $newGroupID) {
2035 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
2036 if (TRUE !== $validation) {
2037 CRM_Core_Error
::fatal(implode(' ', $validation));
2039 $field = new CRM_Core_DAO_CustomField();
2040 $field->id
= $fieldID;
2043 $newGroup = new CRM_Core_DAO_CustomGroup();
2044 $newGroup->id
= $newGroupID;
2045 $newGroup->find(TRUE);
2047 $oldGroup = new CRM_Core_DAO_CustomGroup();
2048 $oldGroup->id
= $field->custom_group_id
;
2049 $oldGroup->find(TRUE);
2052 $add->custom_group_id
= $newGroup->id
;
2053 self
::createField($add, 'add');
2055 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2056 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2057 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2059 CRM_Core_DAO
::executeQuery($sql);
2062 $del->custom_group_id
= $oldGroup->id
;
2063 self
::createField($del, 'delete');
2067 CRM_Utils_System
::flushCache();
2071 * Get the database table name and column name for a custom field
2073 * @param int $fieldID
2074 * The fieldID of the custom field.
2075 * @param bool $force
2076 * Force the sql to be run again (primarily used for tests).
2079 * fatal is fieldID does not exists, else array of tableName, columnName
2082 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2083 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2084 $cache = CRM_Utils_Cache
::singleton();
2085 $fieldValues = $cache->get($cacheKey);
2086 if (empty($fieldValues) ||
$force) {
2088 SELECT cg.table_name, cf.column_name, cg.id
2089 FROM civicrm_custom_group cg,
2090 civicrm_custom_field cf
2091 WHERE cf.custom_group_id = cg.id
2093 $params = array(1 => array($fieldID, 'Integer'));
2094 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2096 if (!$dao->fetch()) {
2097 CRM_Core_Error
::fatal();
2100 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2101 $cache->set($cacheKey, $fieldValues);
2103 return $fieldValues;
2107 * Get custom option groups
2109 * @param array $includeFieldIds
2110 * Ids of custom fields for which.
2111 * option groups must be included.
2113 * Currently this is required in the cases where option groups are to be included
2114 * for inactive fields : CRM-5369
2117 * @return mixed $customOptionGroup
2120 public static function &customOptionGroup($includeFieldIds = NULL) {
2121 static $customOptionGroup = NULL;
2123 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2124 if ($cacheKey == 'force') {
2125 $customOptionGroup[$cacheKey] = NULL;
2128 if (empty($customOptionGroup[$cacheKey])) {
2129 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2131 //support for single as well as array format.
2132 if (!empty($includeFieldIds)) {
2133 if (is_array($includeFieldIds)) {
2134 $includeFieldIds = implode(',', $includeFieldIds);
2136 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2140 SELECT g.id, g.title
2141 FROM civicrm_option_group g
2142 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2143 WHERE {$whereClause}";
2145 $dao = CRM_Core_DAO
::executeQuery($query);
2146 while ($dao->fetch()) {
2147 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2151 return $customOptionGroup[$cacheKey];
2157 * @param int $customFieldId
2159 * @param int $optionGroupId
2165 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2166 // check if option group belongs to any custom Field else delete
2167 // get the current option group
2168 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2172 // get the updated option group
2173 // if both are same return
2174 if ($currentOptionGroupId == $optionGroupId) {
2178 // check if option group is related to any other field
2179 self
::checkOptionGroup($currentOptionGroupId);
2183 * Check if option group is related to more than one
2186 * @param int $optionGroupId
2192 public static function checkOptionGroup($optionGroupId) {
2195 FROM civicrm_custom_field
2196 WHERE option_group_id = {$optionGroupId}";
2198 $count = CRM_Core_DAO
::singleValueQuery($query);
2201 //delete the option group
2202 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2207 * @param int $optionGroupId
2210 * @return null|string
2212 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2214 SELECT default_value, html_type
2215 FROM civicrm_custom_field
2216 WHERE option_group_id = {$optionGroupId}
2217 AND default_value IS NOT NULL
2218 ORDER BY html_type";
2220 $dao = CRM_Core_DAO
::executeQuery($query);
2221 $defaultValue = NULL;
2222 $defaultHTMLType = NULL;
2223 while ($dao->fetch()) {
2224 if ($dao->html_type
== $htmlType) {
2225 return $dao->default_value
;
2227 if ($defaultValue == NULL) {
2228 $defaultValue = $dao->default_value
;
2229 $defaultHTMLType = $dao->html_type
;
2233 // some conversions are needed if either the old or new has a html type which has potential
2234 // multiple default values.
2235 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2236 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2238 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2240 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2241 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2243 $defaultValue = substr($defaultValue, 1, -1);
2244 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2245 substr($defaultValue, 1, -1)
2247 $defaultValue = $values[0];
2250 return $defaultValue;
2254 * @param array $params
2255 * @param $customFields
2256 * @param int $entityID
2257 * @param $customFieldExtends
2258 * @param bool $inline
2262 static function postProcess(
2266 $customFieldExtends,
2269 $customData = array();
2271 foreach ($params as $key => $value) {
2272 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2274 // for autocomplete transfer hidden value instead of label
2275 if ($params[$key] && isset($params[$key . '_id'])) {
2276 $value = $params[$key . '_id'];
2279 // we need to append time with date
2280 if ($params[$key] && isset($params[$key . '_time'])) {
2281 $value .= ' ' . $params[$key . '_time'];
2284 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2287 $customFieldExtends,
2288 $customFieldInfo[1],
2303 public static function buildOption($field, &$options) {
2304 // Fixme - adding anything but options to the $options array is a bad idea
2305 // What if an option had the key 'attributes'?
2306 $options['attributes'] = array(
2307 'label' => $field['label'],
2308 'data_type' => $field['data_type'],
2309 'html_type' => $field['html_type'],
2312 $optionGroupID = NULL;
2313 if (($field['html_type'] == 'CheckBox' ||
2314 $field['html_type'] == 'Radio' ||
2315 $field['html_type'] == 'Select' ||
2316 $field['html_type'] == 'AdvMulti-Select' ||
2317 $field['html_type'] == 'Multi-Select' ||
2318 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2321 if ($field['option_group_id']) {
2322 $optionGroupID = $field['option_group_id'];
2324 elseif ($field['data_type'] != 'Boolean') {
2325 CRM_Core_Error
::fatal();
2329 // build the cache for custom values with options (label => value)
2330 if ($optionGroupID != NULL) {
2333 FROM civicrm_option_value
2334 WHERE option_group_id = $optionGroupID
2337 $dao = CRM_Core_DAO
::executeQuery($query);
2338 while ($dao->fetch()) {
2339 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2340 $num = round($dao->value
, 2);
2341 $options["$num"] = $dao->label
;
2344 $options[$dao->value
] = $dao->label
;
2348 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2353 * @param $fieldLabel
2354 * @param null $groupTitle
2358 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2359 $params = array(1 => array($fieldLabel, 'String'));
2361 $params[2] = array($groupTitle, 'String');
2364 FROM civicrm_custom_field f
2365 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2366 WHERE ( f.label = %1 OR f.name = %1 )
2367 AND ( g.title = %2 OR g.name = %2 )
2373 FROM civicrm_custom_field f
2374 WHERE ( f.label = %1 OR f.name = %1 )
2378 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2379 if ($dao->fetch() &&
2390 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2393 public static function getNameFromID($ids) {
2394 if (is_array($ids)) {
2395 $ids = implode(',', $ids);
2398 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2399 FROM civicrm_custom_field f
2400 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2401 WHERE f.id IN ($ids)";
2403 $dao = CRM_Core_DAO
::executeQuery($sql);
2405 while ($dao->fetch()) {
2406 $result[$dao->id
] = array(
2407 'field_name' => $dao->field_name
,
2408 'field_label' => $dao->field_label
,
2409 'group_name' => $dao->group_name
,
2410 'group_title' => $dao->group_title
,
2417 * Validate custom data.
2419 * @param array $params
2420 * Custom data submitted.
2421 * ie array( 'custom_1' => 'validate me' );
2424 * validation errors.
2427 public static function validateCustomData($params) {
2429 if (!is_array($params) ||
empty($params)) {
2433 //pick up profile fields.
2434 $profileFields = array();
2435 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2437 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2439 CRM_Core_Action
::VIEW
2443 //lets start w/ params.
2444 foreach ($params as $key => $value) {
2445 $customFieldID = self
::getKeyID($key);
2446 if (!$customFieldID) {
2450 //load the structural info for given field.
2451 $field = new CRM_Core_DAO_CustomField();
2452 $field->id
= $customFieldID;
2453 if (!$field->find(TRUE)) {
2456 $dataType = $field->data_type
;
2458 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2459 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2460 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2462 $fieldTitle = $field->label
;
2465 //no need to validate.
2466 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2470 //lets validate first for required field.
2471 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2472 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2476 //now time to take care of custom field form rules.
2477 $ruleName = $errorMsg = NULL;
2478 switch ($dataType) {
2480 $ruleName = 'integer';
2481 $errorMsg = ts('%1 must be an integer (whole number).',
2482 array(1 => $fieldTitle)
2487 $ruleName = 'money';
2488 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2489 array(1 => $fieldTitle)
2494 $ruleName = 'numeric';
2495 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2496 array(1 => $fieldTitle)
2501 $ruleName = 'wikiURL';
2502 $errorMsg = ts('%1 must be valid Website.',
2503 array(1 => $fieldTitle)
2508 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2510 $funName = "CRM_Utils_Rule::{$ruleName}";
2511 if (is_callable($funName)) {
2512 $valid = call_user_func($funName, $value);
2515 $errors[$key] = $errorMsg;
2524 * @param int $customId
2528 public static function isMultiRecordField($customId) {
2529 $isMultipleWithGid = FALSE;
2530 if (!is_numeric($customId)) {
2531 $customId = self
::getKeyID($customId);
2533 if (is_numeric($customId)) {
2534 $sql = "SELECT cg.id cgId
2535 FROM civicrm_custom_group cg
2536 INNER JOIN civicrm_custom_field cf
2537 ON cg.id = cf.custom_group_id
2538 WHERE cf.id = %1 AND cg.is_multiple = 1";
2539 $params[1] = array($customId, 'Integer');
2540 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2541 if ($dao->fetch()) {
2543 $isMultipleWithGid = $dao->cgId
;
2548 return $isMultipleWithGid;
2552 * Does this field store a serialized string?
2553 * @param CRM_Core_DAO_CustomField|array $field
2556 public static function isSerialized($field) {
2557 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2558 $field = (array) $field;
2559 // 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.
2560 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);