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
47 public static $_dataType = NULL;
50 * Array for valid combinations of data_type & html_type
54 public static $_dataToHtml = NULL;
57 * Array to hold (formatted) fields for import
61 public static $_importFields = NULL;
64 * Build and retrieve the list of data types and descriptions
67 * Data type => Description
69 public static function &dataType() {
70 if (!(self
::$_dataType)) {
71 self
::$_dataType = array(
72 'String' => ts('Alphanumeric'),
73 'Int' => ts('Integer'),
74 'Float' => ts('Number'),
75 'Money' => ts('Money'),
78 'Boolean' => ts('Yes or No'),
79 'StateProvince' => ts('State/Province'),
80 'Country' => ts('Country'),
83 'ContactReference' => ts('Contact Reference'),
86 return self
::$_dataType;
92 public static function dataToHtml() {
93 if (!self
::$_dataToHtml) {
94 self
::$_dataToHtml = array(
99 'CheckBox' => 'CheckBox',
100 'Multi-Select' => 'Multi-Select',
101 'AdvMulti-Select' => 'AdvMulti-Select',
102 'Autocomplete-Select' => 'Autocomplete-Select',
104 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
105 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
106 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
107 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
108 array('Date' => 'Select Date'),
109 array('Radio' => 'Radio'),
110 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
111 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
112 array('File' => 'File'),
113 array('Link' => 'Link'),
114 array('ContactReference' => 'Autocomplete-Select'),
117 return self
::$_dataToHtml;
121 * Takes an associative array and creates a custom field object
123 * This function is invoked from within the web form layer and also from the api layer
125 * @param array $params
126 * (reference) an assoc array of name/value pairs.
128 * @return CRM_Core_DAO_CustomField
130 public static function create(&$params) {
131 $origParams = array_merge(array(), $params);
133 if (!isset($params['id'])) {
134 if (!isset($params['column_name'])) {
135 // if add mode & column_name not present, calculate it.
136 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
138 if (!isset($params['name'])) {
139 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
143 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
148 $columnName = $params['column_name'];
151 //as during create if field is_searchable we had created index.
152 if (!empty($params['id'])) {
153 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
156 switch (CRM_Utils_Array
::value('html_type', $params)) {
158 if (empty($params['date_format'])) {
159 $config = CRM_Core_Config
::singleton();
160 $params['date_format'] = $config->dateInputFormat
;
165 case 'AdvMulti-Select':
167 if (isset($params['default_checkbox_option'])) {
168 $tempArray = array_keys($params['default_checkbox_option']);
169 $defaultArray = array();
170 foreach ($tempArray as $k => $v) {
171 if ($params['option_value'][$v]) {
172 $defaultArray[] = $params['option_value'][$v];
176 if (!empty($defaultArray)) {
177 // also add the seperator before and after the value per new conventio (CRM-1604)
178 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
182 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
184 $params['default_value'] = $params['option_value'][$params['default_option']];
190 $transaction = new CRM_Core_Transaction();
191 // create any option group & values if required
192 if ($params['html_type'] != 'Text' &&
193 in_array($params['data_type'], array(
201 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
202 $params['custom_group_id'],
206 if ($params['option_type'] == 1 && empty($params['option_group_id'])) {
207 // first create an option group for this custom group
208 $optionGroup = new CRM_Core_DAO_OptionGroup();
209 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
210 $optionGroup->title
= $params['label'];
211 $optionGroup->is_active
= 1;
212 $optionGroup->save();
213 $params['option_group_id'] = $optionGroup->id
;
214 if (!empty($params['option_value']) && is_array($params['option_value'])) {
215 foreach ($params['option_value'] as $k => $v) {
216 if (strlen(trim($v))) {
217 $optionValue = new CRM_Core_DAO_OptionValue();
218 $optionValue->option_group_id
= $optionGroup->id
;
219 $optionValue->label
= $params['option_label'][$k];
220 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
221 switch ($params['data_type']) {
223 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
227 $optionValue->value
= intval($v);
231 $optionValue->value
= floatval($v);
235 $optionValue->value
= trim($v);
238 $optionValue->weight
= $params['option_weight'][$k];
239 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
240 $optionValue->save();
247 // check for orphan option groups
248 if (!empty($params['option_group_id'])) {
249 if (!empty($params['id'])) {
250 self
::fixOptionGroups($params['id'], $params['option_group_id']);
253 // if we dont have a default value
254 // retrive it from one of the other custom fields which use this option group
255 if (empty($params['default_value'])) {
256 //don't insert only value separator as default value, CRM-4579
257 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
261 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
265 $params['default_value'] = $defaultValue;
270 // since we need to save option group id :)
271 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
272 $params['attributes'] = 'rows=4, cols=60';
275 $customField = new CRM_Core_DAO_CustomField();
276 $customField->copyValues($params);
277 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
278 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
279 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $params, FALSE);
280 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
281 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, FALSE);
282 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
283 $customField->save();
285 // make sure all values are present in the object for further processing
286 $customField->find(TRUE);
288 $triggerRebuild = CRM_Utils_Array
::value('triggerRebuild', $params, TRUE);
289 //create/drop the index when we toggle the is_searchable flag
290 if (!empty($params['id'])) {
291 self
::createField($customField, 'modify', $indexExist, $triggerRebuild);
294 if (!isset($origParams['column_name'])) {
295 $columnName .= "_{$customField->id}";
296 $params['column_name'] = $columnName;
298 $customField->column_name
= $columnName;
299 $customField->save();
300 // make sure all values are present in the object
301 $customField->find(TRUE);
304 self
::createField($customField, 'add', $indexExist, $triggerRebuild);
307 // complete transaction
308 $transaction->commit();
310 CRM_Utils_System
::flushCache();
316 * Fetch object based on array of properties
318 * @param array $params
319 * (reference ) an assoc array of name/value pairs.
320 * @param array $defaults
321 * (reference ) an assoc array to hold the flattened values.
323 * @return CRM_Core_DAO_CustomField
325 public static function retrieve(&$params, &$defaults) {
326 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
330 * Update the is_active flag in the db
333 * Id of the database record.
334 * @param bool $is_active
335 * Value we want to set the is_active field.
338 * DAO object on sucess, null otherwise
341 public static function setIsActive($id, $is_active) {
343 CRM_Utils_System
::flushCache();
345 //enable-disable CustomField
346 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
347 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
351 * Get the field title.
360 public static function getTitle($id) {
361 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
365 * Store and return an array of all active custom fields.
367 * @param string $customDataType
368 * Type of Custom Data; empty is a synonym for "all contact data types".
369 * @param bool $showAll
370 * If true returns all fields (includes disabled fields).
371 * @param bool $inline
372 * If true returns all inline fields (includes disabled fields).
373 * @param int $customDataSubType
374 * Custom Data sub type value.
375 * @param int $customDataSubName
376 * Custom Data sub name value.
377 * @param bool $onlyParent
378 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
379 * @param bool $onlySubType
380 * Return only custom data for subtype.
381 * @param bool $checkPermission
382 * If false, do not include permissioning clause.
385 * an array of active custom fields.
388 public static function &getFields(
389 $customDataType = 'Individual',
392 $customDataSubType = NULL,
393 $customDataSubName = NULL,
395 $onlySubType = FALSE,
396 $checkPermission = TRUE
398 if (empty($customDataType)) {
399 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
401 if ($customDataType && !is_array($customDataType)) {
403 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
404 // This is the case when getFieldsForImport() requires fields
405 // limited strictly to a subtype.
406 $customDataSubType = $customDataType;
407 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
411 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
412 // this makes the method flexible to support retrieving fields
413 // for multiple extends value.
414 $customDataType = array($customDataType);
418 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
420 if (is_array($customDataType)) {
421 $cacheKey = implode('_', $customDataType);
424 $cacheKey = $customDataType;
427 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
428 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
429 $cacheKey .= $showAll ?
'_1' : '_0';
430 $cacheKey .= $inline ?
'_1_' : '_0_';
431 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
432 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
433 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
435 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
437 // also get the permission stuff here
438 if ($checkPermission) {
439 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
444 $permissionClause = '(1)';
447 // lets md5 permission clause and take first 8 characters
448 $cacheKey .= substr(md5($permissionClause), 0, 8);
450 if (strlen($cacheKey) > 40) {
451 $cacheKey = md5($cacheKey);
454 if (!self
::$_importFields ||
455 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
457 if (!self
::$_importFields) {
458 self
::$_importFields = array();
461 // check if we can retrieve from database cache
462 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
464 if ($fields === NULL) {
465 $cfTable = self
::getTableName();
468 if (is_array($customDataType)) {
470 foreach ($customDataType as $dataType) {
471 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
472 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
473 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
476 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
478 $value = $value ?
$value . ", {$val}" : $val;
482 $extends = "AND $cgTable.extends IN ( $value ) ";
486 if (!empty($customDataType) && empty($extends)) {
487 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
488 self
::$_importFields[$cacheKey] = array();
489 return self
::$_importFields[$cacheKey];
493 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
496 $query = "SELECT $cfTable.id, $cfTable.label,
500 $cfTable.default_value,
501 $cfTable.options_per_line, $cfTable.text_length,
502 $cfTable.custom_group_id,
503 $cfTable.is_required,
504 $cgTable.extends, $cfTable.is_search_range,
505 $cgTable.extends_entity_column_value,
506 $cgTable.extends_entity_column_id,
508 $cfTable.option_group_id,
509 $cfTable.date_format,
510 $cfTable.time_format,
514 ON $cfTable.custom_group_id = $cgTable.id
518 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
522 $query .= " AND $cgTable.style = 'Inline' ";
525 //get the custom fields for specific type in
526 //combination with fields those support any type.
527 if (!empty($customDataSubType)) {
528 $subtypeClause = array();
529 foreach ($customDataSubType as $subtype) {
530 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
531 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
534 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
536 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
539 if ($customDataSubName) {
540 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
543 // also get the permission stuff here
544 if ($checkPermission) {
545 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
550 $permissionClause = '(1)';
553 $query .= " $extends AND $permissionClause
554 ORDER BY $cgTable.weight, $cgTable.title,
555 $cfTable.weight, $cfTable.label";
557 $dao = CRM_Core_DAO
::executeQuery($query);
560 while (($dao->fetch()) != NULL) {
561 $fields[$dao->id
]['label'] = $dao->label
;
562 $fields[$dao->id
]['groupTitle'] = $dao->title
;
563 $fields[$dao->id
]['data_type'] = $dao->data_type
;
564 $fields[$dao->id
]['html_type'] = $dao->html_type
;
565 $fields[$dao->id
]['default_value'] = $dao->default_value
;
566 $fields[$dao->id
]['text_length'] = $dao->text_length
;
567 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
568 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
569 $fields[$dao->id
]['extends'] = $dao->extends;
570 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
571 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
572 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
573 $fields[$dao->id
]['is_view'] = $dao->is_view
;
574 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
575 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
576 $fields[$dao->id
]['date_format'] = $dao->date_format
;
577 $fields[$dao->id
]['time_format'] = $dao->time_format
;
578 $fields[$dao->id
]['is_required'] = $dao->is_required
;
581 CRM_Core_BAO_Cache
::setItem($fields,
583 "custom importableFields $cacheKey"
586 self
::$_importFields[$cacheKey] = $fields;
589 return self
::$_importFields[$cacheKey];
593 * Return the field ids and names (with groups) for import purpose.
595 * @param int|string $contactType Contact type
596 * @param bool $showAll
597 * If true returns all fields (includes disabled fields).
598 * @param bool $onlyParent
599 * Return fields ONLY related to basic types.
600 * @param bool $search
601 * When called from search and multiple records need to be returned.
602 * @param bool $checkPermission
603 * If false, do not include permissioning clause.
605 * @param bool $withMultiple
611 public static function &getFieldsForImport(
612 $contactType = 'Individual',
616 $checkPermission = TRUE,
617 $withMultiple = FALSE
619 // Note: there are situations when we want getFieldsForImport() return fields related
620 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
621 $fields = &self
::getFields($contactType,
631 $importableFields = array();
632 foreach ($fields as $id => $values) {
633 // for now we should not allow multiple fields in profile / export etc, hence unsetting
635 (!empty($values['is_multiple']) && !$withMultiple)
640 /* generate the key for the fields array */
644 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
645 $importableFields[$key] = array(
647 'title' => CRM_Utils_Array
::value('label', $values),
648 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
650 'custom_field_id' => $id,
651 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
652 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
653 'data_type' => CRM_Utils_Array
::value('data_type', $values),
654 'html_type' => CRM_Utils_Array
::value('html_type', $values),
655 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
658 // CRM-6681, pass date and time format when html_type = Select Date
659 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
660 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
661 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
665 return $importableFields;
669 * Get the field id from an import key
678 public static function getKeyID($key, $all = FALSE) {
680 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
687 CRM_Utils_Array
::value(2, $match),
691 return $all ?
array(NULL, NULL) : NULL;
695 * Use the cache to get all values of a specific custom field
697 * @param int $fieldID
698 * The custom field ID.
700 * @return CRM_Core_DAO_CustomField
703 public static function getFieldObject($fieldID) {
704 $field = new CRM_Core_DAO_CustomField();
706 // check if we can get the field values from the system cache
707 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
708 $cache = CRM_Utils_Cache
::singleton();
709 $fieldValues = $cache->get($cacheKey);
710 if (empty($fieldValues)) {
711 $field->id
= $fieldID;
712 if (!$field->find(TRUE)) {
713 CRM_Core_Error
::fatal();
716 $fieldValues = array();
717 CRM_Core_DAO
::storeValues($field, $fieldValues);
719 $cache->set($cacheKey, $fieldValues);
722 $field->copyValues($fieldValues);
729 * This function for building custom fields
731 * @param CRM_Core_Form $qf
732 * Form object (reference).
733 * @param string $elementName
734 * Name of the custom field.
735 * @param int $fieldId
736 * @param bool $inactiveNeeded
738 * @param bool $useRequired
739 * True if required else false.
740 * @param bool $search
741 * True if used for search else false.
742 * @param string $label
743 * Label for custom field.
746 public static function addQuickFormElement(
750 $inactiveNeeded = FALSE,
755 $field = self
::getFieldObject($fieldId);
756 $widget = $field->html_type
;
758 // Custom field HTML should indicate group+field name
759 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
760 $dataCrmCustomVal = $groupName . ':' . $field->name
;
761 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
762 $field->attributes
.= $dataCrmCustomAttr;
764 // Fixed for Issue CRM-2183
765 if ($widget == 'TextArea' && $search) {
769 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
771 // FIXME: Why are select state/country separate widget types?
772 $isSelect = (in_array($widget, array(
775 'Select State/Province',
776 'Multi-Select State/Province',
778 'Multi-Select Country',
785 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array(
786 'field' => "custom_$fieldId",
787 'context' => $search ?
'search' : 'create',
790 // Consolidate widget types to simplify the below switch statement
791 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
794 $selectAttributes = array(
795 'data-crm-custom' => $dataCrmCustomVal,
796 'class' => 'crm-select2',
798 // Search field is always multi-select
799 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
800 $selectAttributes['class'] .= ' huge';
801 $selectAttributes['multiple'] = 'multiple';
802 $selectAttributes['placeholder'] = $placeholder;
804 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
805 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
806 $selectAttributes +
= array(
807 'data-api-entity' => 'contact',
808 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
809 'data-api-field' => 'custom_' . $field->id
,
810 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
815 if (!isset($label)) {
816 $label = $field->label
;
820 * at some point in time we might want to split the below into small functions
826 if ($field->is_search_range
&& $search) {
827 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
828 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
831 $element = &$qf->add('text', $elementName, $label,
833 $useRequired && !$search
839 $attributes = $dataCrmCustomAttr;
840 if ($field->note_rows
) {
841 $attributes .= 'rows=' . $field->note_rows
;
844 $attributes .= 'rows=4';
846 if ($field->note_columns
) {
847 $attributes .= ' cols=' . $field->note_columns
;
850 $attributes .= ' cols=60';
852 if ($field->text_length
) {
853 $attributes .= ' maxlength=' . $field->text_length
;
855 $element = &$qf->add('textarea',
859 $useRequired && !$search
864 if ($field->is_search_range
&& $search) {
865 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
867 'format' => $field->date_format
,
868 'timeFormat' => $field->time_format
,
869 'startOffset' => $field->start_date_years
,
870 'endOffset' => $field->end_date_years
,
871 'data-crm-custom' => $dataCrmCustomVal,
875 $qf->addDate($elementName . '_to', ts('To'), FALSE,
877 'format' => $field->date_format
,
878 'timeFormat' => $field->time_format
,
879 'startOffset' => $field->start_date_years
,
880 'endOffset' => $field->end_date_years
,
881 'data-crm-custom' => $dataCrmCustomVal,
886 $required = $useRequired && !$search;
888 $qf->addDate($elementName, $label, $required, array(
889 'format' => $field->date_format
,
890 'timeFormat' => $field->time_format
,
891 'startOffset' => $field->start_date_years
,
892 'endOffset' => $field->end_date_years
,
893 'data-crm-custom' => $dataCrmCustomVal,
900 foreach ($options as $v => $l) {
901 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
903 $group = $qf->addGroup($choice, $elementName, $label);
904 if ($useRequired && !$search) {
905 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
908 $group->setAttribute('allowClear', TRUE);
912 // For all select elements
914 if (empty($selectAttributes['multiple'])) {
915 $options = array('' => $placeholder) +
$options;
917 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
919 // Add and/or option for fields that store multiple values
920 if ($search && self
::isSerialized($field)) {
923 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
924 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
926 $qf->addGroup($operators, $elementName . '_operator');
927 $qf->setDefaults(array($elementName . '_operator' => 'or'));
931 case 'AdvMulti-Select':
932 $include =& $qf->addElement(
939 'class' => 'advmultiselect',
940 'data-crm-custom' => $dataCrmCustomVal,
944 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
945 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
947 if ($useRequired && !$search) {
948 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
954 foreach ($options as $v => $l) {
955 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
957 $qf->addGroup($check, $elementName, $label);
958 if ($useRequired && !$search) {
959 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
964 // we should not build upload file in search mode
969 strtolower($field->html_type
),
973 $useRequired && !$search
975 $qf->addUploadElement($elementName);
978 case 'RichTextEditor':
980 'rows' => $field->note_rows
,
981 'cols' => $field->note_columns
,
982 'data-crm-custom' => $dataCrmCustomVal,
984 if ($field->text_length
) {
985 $attributes['maxlength'] = $field->text_length
;
987 $qf->addWysiwyg($elementName, $label, $attributes, $search);
990 case 'Autocomplete-Select':
991 static $customUrls = array();
992 // Fixme: why is this a string in the first place??
993 $attributes = array();
994 if ($field->attributes
) {
995 foreach (explode(' ', $field->attributes
) as $at) {
996 if (strpos($at, '=')) {
997 list($k, $v) = explode('=', $at);
998 $attributes[$k] = trim($v, ' "');
1002 if ($field->data_type
== 'ContactReference') {
1003 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1004 $attributes['data-api-entity'] = 'contact';
1005 $qf->add('text', $elementName, $label, $attributes,
1006 $useRequired && !$search
1009 $urlParams = "context=customfield&id={$field->id}";
1011 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1018 // FIXME: This won't work with customFieldOptions hook
1019 $attributes +
= array(
1020 'entity' => 'option_value',
1021 'placeholder' => $placeholder,
1022 'multiple' => $search,
1024 'params' => array('option_group_id' => $field->option_group_id
),
1027 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1030 $qf->assign('customUrls', $customUrls);
1034 switch ($field->data_type
) {
1036 // integers will have numeric rule applied to them.
1037 if ($field->is_search_range
&& $search) {
1038 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1039 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1041 elseif ($widget == 'Text') {
1042 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1047 if ($field->is_search_range
&& $search) {
1048 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1049 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1051 elseif ($widget == 'Text') {
1052 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1057 if ($field->is_search_range
&& $search) {
1058 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1059 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1061 elseif ($widget == 'Text') {
1062 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1067 $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
1068 $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
1069 $element->setAttribute('class', "url");
1070 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1073 if ($field->is_view
&& !$search) {
1074 $qf->freeze($elementName);
1079 * Delete the Custom Field.
1081 * @param object $field
1084 public static function deleteField($field) {
1085 CRM_Utils_System
::flushCache();
1087 // first delete the custom option group and values associated with this field
1088 if ($field->option_group_id
) {
1089 //check if option group is related to any other field, if
1090 //not delete the option group and related option values
1091 self
::checkOptionGroup($field->option_group_id
);
1094 // next drop the column from the custom value table
1095 self
::createField($field, 'delete');
1098 CRM_Core_BAO_UFField
::delUFField($field->id
);
1099 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1103 * Given a custom field value, its id and the set of options
1104 * find the display value for this field
1106 * @param mixed $value
1107 * The custom field value.
1109 * The custom field id.
1110 * @param int $options
1111 * The assoc array of option name/value pairs.
1113 * @param int $contactID
1114 * @param int $fieldID
1120 public static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1121 $option = &$options[$id];
1122 $attributes = &$option['attributes'];
1123 $html_type = $attributes['html_type'];
1124 $data_type = $attributes['data_type'];
1125 $format = CRM_Utils_Array
::value('format', $attributes);
1127 return self
::getDisplayValueCommon($value,
1142 * @param null $format
1143 * @param int $contactID
1144 * @param int $fieldID
1146 * @return array|mixed|null|string
1148 public static function getDisplayValueCommon(
1160 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1161 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1162 $html_type == 'Select' ||
1163 $html_type == 'CheckBox' ||
1164 $html_type == 'AdvMulti-Select' ||
1165 $html_type == 'Multi-Select'
1168 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1171 switch ($html_type) {
1173 if ($data_type == 'Boolean') {
1174 // Do not assume that if not yes means no.
1177 $display = ts('Yes');
1179 elseif ((string) $value === '0') {
1180 $display = ts('No');
1184 $display = CRM_Utils_Array
::value($value, $option);
1188 case 'Autocomplete-Select':
1189 if ($data_type == 'ContactReference' &&
1192 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1195 $display = CRM_Utils_Array
::value($value, $option);
1200 $display = CRM_Utils_Array
::value($value, $option);
1204 case 'AdvMulti-Select':
1205 case 'Multi-Select':
1206 if (is_array($value)) {
1207 $checkedData = $value;
1210 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1211 substr($value, 1, -1)
1213 if ($html_type == 'CheckBox') {
1215 foreach ($checkedData as $v) {
1218 $checkedData = $newData;
1224 foreach ($checkedData as $key => $val) {
1225 if ($html_type == 'CheckBox') {
1228 $v[] = CRM_Utils_Array
::value($key, $option);
1233 $v[] = CRM_Utils_Array
::value($val, $option);
1237 $display = implode(', ', $v);
1242 if (is_array($value)) {
1243 foreach ($value as $key => $val) {
1244 $display[$key] = CRM_Utils_Date
::customFormat($val);
1248 // remove time element display if time is not set
1249 if (empty($option['attributes']['time_format'])) {
1250 $value = substr($value, 0, 10);
1252 $display = CRM_Utils_Date
::customFormat($value);
1256 case 'Select State/Province':
1257 if (empty($value)) {
1261 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1265 case 'Multi-Select State/Province':
1266 if (is_array($value)) {
1267 $checkedData = $value;
1270 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1271 substr($value, 1, -1)
1275 $states = CRM_Core_PseudoConstant
::stateProvince();
1277 foreach ($checkedData as $stateID) {
1281 $display .= $states[$stateID];
1285 case 'Select Country':
1286 if (empty($value)) {
1290 $display = CRM_Core_PseudoConstant
::country($value);
1294 case 'Multi-Select Country':
1295 if (is_array($value)) {
1296 $checkedData = $value;
1299 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1300 substr($value, 1, -1)
1304 $countries = CRM_Core_PseudoConstant
::country();
1306 foreach ($checkedData as $countryID) {
1310 $display .= $countries[$countryID];
1316 $url = self
::getFileURL($contactID, $fieldID, $value);
1318 $display = $url['file_url'];
1324 if (empty($value)) {
1328 $display = nl2br($value);
1333 if (empty($value)) {
1340 return $display ?
$display : $value;
1344 * Set default values for custom data used in profile
1346 * @param int $customFieldId
1348 * @param string $elementName
1349 * Custom field name.
1350 * @param array $defaults
1351 * Associated array of fields.
1352 * @param int $contactId
1356 * @param mixed $value
1357 * If passed - dont fetch value from db,.
1358 * just format the given value
1361 public static function setProfileDefaults(
1369 //get the type of custom field
1370 $customField = new CRM_Core_BAO_CustomField();
1371 $customField->id
= $customFieldId;
1372 $customField->find(TRUE);
1375 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1376 $value = $customField->default_value
;
1380 if (!isset($value)) {
1381 $info = self
::getTableColumnGroup($customFieldId);
1382 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1383 $result = CRM_Core_DAO
::executeQuery($query);
1384 if ($result->fetch()) {
1385 $value = $result->value
;
1389 if ($customField->data_type
== 'Country') {
1391 $config = CRM_Core_Config
::singleton();
1392 if ($config->defaultContactCountry
) {
1393 $value = $config->defaultContactCountry();
1399 //set defaults if mode is registration
1400 if (!trim($value) &&
1402 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1404 $value = $customField->default_value
;
1407 if ($customField->data_type
== 'Money' && isset($value)) {
1408 $value = number_format($value, 2);
1410 switch ($customField->html_type
) {
1412 case 'AdvMulti-Select':
1413 case 'Multi-Select':
1414 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1415 $defaults[$elementName] = array();
1416 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1417 substr($value, 1, -1)
1419 foreach ($customOption as $val) {
1420 if (in_array($val['value'], $checkedValue)) {
1421 if ($customField->html_type
== 'CheckBox') {
1422 $defaults[$elementName][$val['value']] = 1;
1424 elseif ($customField->html_type
== 'Multi-Select' ||
1425 $customField->html_type
== 'AdvMulti-Select'
1427 $defaults[$elementName][$val['value']] = $val['value'];
1435 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1438 $customField->date_format
,
1439 $customField->time_format
1444 case 'Autocomplete-Select':
1445 if ($customField->data_type
== 'ContactReference') {
1446 if (is_numeric($value)) {
1447 $defaults[$elementName . '_id'] = $value;
1448 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1452 $defaults[$elementName] = $value;
1457 $defaults[$elementName] = $value;
1462 * @param int $contactID
1464 * @param int $fileID
1465 * @param bool $absolute
1470 * @param int $contactID
1472 * @param int $fileID
1473 * @param bool $absolute
1477 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1480 $params = array('id' => $cfID);
1481 $defaults = array();
1482 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1483 $columnName = $defaults['column_name'];
1485 //table name of custom data
1486 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1487 $defaults['custom_group_id'],
1491 //query to fetch id from civicrm_file
1492 if ($multiRecordWhereClause) {
1493 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1496 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1498 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1503 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1508 $result['file_id'] = $fileID;
1510 if ($fileType == 'image/jpeg' ||
1511 $fileType == 'image/pjpeg' ||
1512 $fileType == 'image/gif' ||
1513 $fileType == 'image/x-png' ||
1514 $fileType == 'image/png'
1516 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1521 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1522 list($imageWidth, $imageHeight) = getimagesize($path);
1523 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1524 $url = CRM_Utils_System
::url('civicrm/file',
1525 "reset=1&id=$fileID&eid=$contactID",
1526 $absolute, NULL, TRUE, TRUE
1528 $result['file_url'] = "
1529 <a href=\"$url\" class='crm-image-popup'>
1530 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1532 // for non image files
1535 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1539 $url = CRM_Utils_System
::url('civicrm/file',
1540 "reset=1&id=$fileID&eid=$contactID",
1541 $absolute, NULL, TRUE, TRUE
1543 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1551 * Format custom fields before inserting
1553 * @param int $customFieldId
1555 * @param array $customFormatted
1558 * Value of custom field.
1559 * @param string $customFieldExtend
1560 * Custom field extends.
1561 * @param int $customValueId
1562 * Custom option value id.
1563 * @param int $entityId
1564 * Entity id (contribution, membership...).
1565 * @param bool $inline
1566 * Consider inline custom groups only.
1567 * @param bool $checkPermission
1568 * If false, do not include permissioning clause.
1569 * @param bool $includeViewOnly
1570 * If true, fields marked 'View Only' are included. Required for APIv3.
1572 * @return array|NULL
1573 * formatted custom field array
1575 public static function formatCustomField(
1576 $customFieldId, &$customFormatted, $value,
1577 $customFieldExtend, $customValueId = NULL,
1580 $checkPermission = TRUE,
1581 $includeViewOnly = FALSE
1583 //get the custom fields for the entity
1584 //subtype and basic type
1585 $customDataSubType = NULL;
1586 if (is_array($customFieldExtend)) {
1587 $customFieldExtend = $customFieldExtend[0];
1590 if (in_array($customFieldExtend,
1591 CRM_Contact_BAO_ContactType
::subTypes()
1593 // This is the case when getFieldsForImport() requires fields
1594 // of subtype and its parent.CRM-5143
1595 $customDataSubType = $customFieldExtend;
1596 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1599 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1609 if (!array_key_exists($customFieldId, $customFields)) {
1613 // return if field is a 'code' field
1614 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1618 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1620 if (!$customValueId &&
1621 // we always create new entites for is_multiple unless specified
1622 !$customFields[$customFieldId]['is_multiple'] &&
1628 WHERE entity_id={$entityId}";
1630 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1633 //fix checkbox, now check box always submits values
1634 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1636 // Note that only during merge this is not an array, and you can directly use value
1637 if (is_array($value)) {
1638 $selectedValues = array();
1639 foreach ($value as $selId => $val) {
1641 $selectedValues[] = $selId;
1644 if (!empty($selectedValues)) {
1645 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1647 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1656 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1657 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1660 // Note that only during merge this is not an array,
1661 // and you can directly use value, CRM-4385
1662 if (is_array($value)) {
1663 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1664 array_values($value)
1665 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1673 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1674 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1675 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1677 $customFields[$customFieldId]['data_type'] == 'String' &&
1678 !empty($customFields[$customFieldId]['text_length']) &&
1681 // lets make sure that value is less than the length, else we'll
1682 // be losing some data, CRM-7481
1683 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1684 // need to do a few things here
1686 // 1. lets find a new length
1687 $newLength = $customFields[$customFieldId]['text_length'];
1688 $minLength = strlen($value);
1689 while ($newLength < $minLength) {
1690 $newLength = $newLength * 2;
1693 // set the custom field meta data to have a length larger than value
1694 // alter the custom value table column to match this length
1695 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1700 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1701 if (!CRM_Utils_System
::isNull($value)) {
1702 $format = $customFields[$customFieldId]['date_format'];
1703 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1708 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1709 $customFields[$customFieldId]['data_type'] == 'Money'
1715 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1716 $value = CRM_Utils_Rule
::cleanMoney($value);
1720 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1721 $customFields[$customFieldId]['data_type'] == 'Country'
1731 if ($customFields[$customFieldId]['data_type'] == 'File') {
1732 if (empty($value)) {
1736 $config = CRM_Core_Config
::singleton();
1738 $fName = $value['name'];
1739 $mimeType = $value['type'];
1741 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1743 // rename this file to go into the secure directory
1744 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1745 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1748 if ($customValueId) {
1753 $params = array(1 => array($customValueId, 'Integer'));
1754 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1757 $fileDAO = new CRM_Core_DAO_File();
1760 $fileDAO->id
= $fileId;
1763 $fileDAO->uri
= $filename;
1764 $fileDAO->mime_type
= $mimeType;
1765 $fileDAO->upload_date
= date('Ymdhis');
1767 $fileId = $fileDAO->id
;
1771 if (!is_array($customFormatted)) {
1772 $customFormatted = array();
1775 if (!array_key_exists($customFieldId, $customFormatted)) {
1776 $customFormatted[$customFieldId] = array();
1780 if ($customValueId) {
1781 $index = $customValueId;
1784 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1785 $customFormatted[$customFieldId][$index] = array();
1787 $customFormatted[$customFieldId][$index] = array(
1788 'id' => $customValueId > 0 ?
$customValueId : NULL,
1790 'type' => $customFields[$customFieldId]['data_type'],
1791 'custom_field_id' => $customFieldId,
1792 'custom_group_id' => $groupID,
1793 'table_name' => $tableName,
1794 'column_name' => $columnName,
1795 'file_id' => $fileId,
1796 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1799 //we need to sort so that custom fields are created in the order of entry
1800 krsort($customFormatted[$customFieldId]);
1801 return $customFormatted;
1805 * @param array $params
1809 public static function &defaultCustomTableSchema(&$params) {
1810 // add the id and extends_id
1812 'name' => $params['name'],
1813 'is_multiple' => $params['is_multiple'],
1814 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1818 'type' => 'int unsigned',
1821 'attributes' => 'AUTO_INCREMENT',
1822 'comment' => 'Default MySQL primary key',
1825 'name' => 'entity_id',
1826 'type' => 'int unsigned',
1828 'comment' => 'Table that this extends',
1829 'fk_table_name' => $params['extends_name'],
1830 'fk_field_name' => 'id',
1831 'fk_attributes' => 'ON DELETE CASCADE',
1836 if (!$params['is_multiple']) {
1837 $table['indexes'] = array(
1840 'field_name_1' => 'entity_id',
1850 * @param bool $indexExist
1851 * @param bool $triggerRebuild
1853 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1854 $tableName = CRM_Core_DAO
::getFieldValue(
1855 'CRM_Core_DAO_CustomGroup',
1856 $field->custom_group_id
,
1861 'table_name' => $tableName,
1862 'operation' => $operation,
1863 'name' => $field->column_name
,
1864 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1868 'required' => $field->is_required
,
1869 'searchable' => $field->is_searchable
,
1872 if ($operation == 'delete') {
1873 $fkName = "{$tableName}_{$field->column_name}";
1874 if (strlen($fkName) >= 48) {
1875 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1877 $params['fkName'] = $fkName;
1879 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1880 $params['fk_table_name'] = 'civicrm_country';
1881 $params['fk_field_name'] = 'id';
1882 $params['fk_attributes'] = 'ON DELETE SET NULL';
1884 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1885 $params['type'] = 'varchar(255)';
1887 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1888 $params['fk_table_name'] = 'civicrm_state_province';
1889 $params['fk_field_name'] = 'id';
1890 $params['fk_attributes'] = 'ON DELETE SET NULL';
1892 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1893 $params['type'] = 'varchar(255)';
1895 elseif ($field->data_type
== 'File') {
1896 $params['fk_table_name'] = 'civicrm_file';
1897 $params['fk_field_name'] = 'id';
1898 $params['fk_attributes'] = 'ON DELETE SET NULL';
1900 elseif ($field->data_type
== 'ContactReference') {
1901 $params['fk_table_name'] = 'civicrm_contact';
1902 $params['fk_field_name'] = 'id';
1903 $params['fk_attributes'] = 'ON DELETE SET NULL';
1905 if (isset($field->default_value
)) {
1906 $params['default'] = "'{$field->default_value}'";
1909 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1913 * Determine whether it would be safe to move a field
1915 * @param int $fieldID
1916 * FK to civicrm_custom_field.
1917 * @param int $newGroupID
1918 * FK to civicrm_custom_group.
1921 * array(string) or TRUE
1923 public static function _moveFieldValidate($fieldID, $newGroupID) {
1926 $field = new CRM_Core_DAO_CustomField();
1927 $field->id
= $fieldID;
1928 if (!$field->find(TRUE)) {
1929 $errors['fieldID'] = 'Invalid ID for custom field';
1933 $oldGroup = new CRM_Core_DAO_CustomGroup();
1934 $oldGroup->id
= $field->custom_group_id
;
1935 if (!$oldGroup->find(TRUE)) {
1936 $errors['fieldID'] = 'Invalid ID for old custom group';
1940 $newGroup = new CRM_Core_DAO_CustomGroup();
1941 $newGroup->id
= $newGroupID;
1942 if (!$newGroup->find(TRUE)) {
1943 $errors['newGroupID'] = 'Invalid ID for new custom group';
1949 FROM civicrm_custom_field a
1950 INNER JOIN civicrm_custom_field b
1952 AND a.label = b.label
1953 AND b.custom_group_id = %2
1956 1 => array($field->id
, 'Integer'),
1957 2 => array($newGroup->id
, 'Integer'),
1959 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1961 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1964 $tableName = $oldGroup->table_name
;
1965 $columnName = $field->column_name
;
1970 WHERE $columnName is not null
1972 $count = CRM_Core_DAO
::singleValueQuery($query,
1973 CRM_Core_DAO
::$_nullArray
1978 FROM civicrm_custom_group
1979 WHERE id IN ( %1, %2 )
1982 1 => array($oldGroup->id
, 'Integer'),
1983 2 => array($newGroup->id
, 'Integer'),
1986 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1988 while ($dao->fetch()) {
1989 $extends[] = $dao->extends;
1991 if ($extends[0] != $extends[1]) {
1992 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1996 return empty($errors) ?
TRUE : $errors;
2000 * Move a custom data field from one group (table) to another
2002 * @param int $fieldID
2003 * FK to civicrm_custom_field.
2004 * @param int $newGroupID
2005 * FK to civicrm_custom_group.
2009 public static function moveField($fieldID, $newGroupID) {
2010 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
2011 if (TRUE !== $validation) {
2012 CRM_Core_Error
::fatal(implode(' ', $validation));
2014 $field = new CRM_Core_DAO_CustomField();
2015 $field->id
= $fieldID;
2018 $newGroup = new CRM_Core_DAO_CustomGroup();
2019 $newGroup->id
= $newGroupID;
2020 $newGroup->find(TRUE);
2022 $oldGroup = new CRM_Core_DAO_CustomGroup();
2023 $oldGroup->id
= $field->custom_group_id
;
2024 $oldGroup->find(TRUE);
2027 $add->custom_group_id
= $newGroup->id
;
2028 self
::createField($add, 'add');
2030 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2031 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2032 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2034 CRM_Core_DAO
::executeQuery($sql);
2037 $del->custom_group_id
= $oldGroup->id
;
2038 self
::createField($del, 'delete');
2042 CRM_Utils_System
::flushCache();
2046 * Get the database table name and column name for a custom field
2048 * @param int $fieldID
2049 * The fieldID of the custom field.
2050 * @param bool $force
2051 * Force the sql to be run again (primarily used for tests).
2054 * fatal is fieldID does not exists, else array of tableName, columnName
2056 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2057 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2058 $cache = CRM_Utils_Cache
::singleton();
2059 $fieldValues = $cache->get($cacheKey);
2060 if (empty($fieldValues) ||
$force) {
2062 SELECT cg.table_name, cf.column_name, cg.id
2063 FROM civicrm_custom_group cg,
2064 civicrm_custom_field cf
2065 WHERE cf.custom_group_id = cg.id
2067 $params = array(1 => array($fieldID, 'Integer'));
2068 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2070 if (!$dao->fetch()) {
2071 CRM_Core_Error
::fatal();
2074 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2075 $cache->set($cacheKey, $fieldValues);
2077 return $fieldValues;
2081 * Get custom option groups
2083 * @param array $includeFieldIds
2084 * Ids of custom fields for which.
2085 * option groups must be included.
2087 * Currently this is required in the cases where option groups are to be included
2088 * for inactive fields : CRM-5369
2093 public static function &customOptionGroup($includeFieldIds = NULL) {
2094 static $customOptionGroup = NULL;
2096 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2097 if ($cacheKey == 'force') {
2098 $customOptionGroup[$cacheKey] = NULL;
2101 if (empty($customOptionGroup[$cacheKey])) {
2102 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2104 //support for single as well as array format.
2105 if (!empty($includeFieldIds)) {
2106 if (is_array($includeFieldIds)) {
2107 $includeFieldIds = implode(',', $includeFieldIds);
2109 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2113 SELECT g.id, g.title
2114 FROM civicrm_option_group g
2115 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2116 WHERE {$whereClause}";
2118 $dao = CRM_Core_DAO
::executeQuery($query);
2119 while ($dao->fetch()) {
2120 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2124 return $customOptionGroup[$cacheKey];
2130 * @param int $customFieldId
2132 * @param int $optionGroupId
2137 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2138 // check if option group belongs to any custom Field else delete
2139 // get the current option group
2140 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2144 // get the updated option group
2145 // if both are same return
2146 if ($currentOptionGroupId == $optionGroupId) {
2150 // check if option group is related to any other field
2151 self
::checkOptionGroup($currentOptionGroupId);
2155 * Check if option group is related to more than one
2158 * @param int $optionGroupId
2163 public static function checkOptionGroup($optionGroupId) {
2166 FROM civicrm_custom_field
2167 WHERE option_group_id = {$optionGroupId}";
2169 $count = CRM_Core_DAO
::singleValueQuery($query);
2172 //delete the option group
2173 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2178 * @param int $optionGroupId
2181 * @return null|string
2183 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2185 SELECT default_value, html_type
2186 FROM civicrm_custom_field
2187 WHERE option_group_id = {$optionGroupId}
2188 AND default_value IS NOT NULL
2189 ORDER BY html_type";
2191 $dao = CRM_Core_DAO
::executeQuery($query);
2192 $defaultValue = NULL;
2193 $defaultHTMLType = NULL;
2194 while ($dao->fetch()) {
2195 if ($dao->html_type
== $htmlType) {
2196 return $dao->default_value
;
2198 if ($defaultValue == NULL) {
2199 $defaultValue = $dao->default_value
;
2200 $defaultHTMLType = $dao->html_type
;
2204 // some conversions are needed if either the old or new has a html type which has potential
2205 // multiple default values.
2206 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2207 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2209 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2211 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2212 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2214 $defaultValue = substr($defaultValue, 1, -1);
2215 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2216 substr($defaultValue, 1, -1)
2218 $defaultValue = $values[0];
2221 return $defaultValue;
2225 * @param array $params
2226 * @param $customFields
2227 * @param int $entityID
2228 * @param $customFieldExtends
2229 * @param bool $inline
2233 public static function postProcess(
2237 $customFieldExtends,
2240 $customData = array();
2242 foreach ($params as $key => $value) {
2243 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2245 // for autocomplete transfer hidden value instead of label
2246 if ($params[$key] && isset($params[$key . '_id'])) {
2247 $value = $params[$key . '_id'];
2250 // we need to append time with date
2251 if ($params[$key] && isset($params[$key . '_time'])) {
2252 $value .= ' ' . $params[$key . '_time'];
2255 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2258 $customFieldExtends,
2259 $customFieldInfo[1],
2274 public static function buildOption($field, &$options) {
2275 // Fixme - adding anything but options to the $options array is a bad idea
2276 // What if an option had the key 'attributes'?
2277 $options['attributes'] = array(
2278 'label' => $field['label'],
2279 'data_type' => $field['data_type'],
2280 'html_type' => $field['html_type'],
2283 $optionGroupID = NULL;
2284 if (($field['html_type'] == 'CheckBox' ||
2285 $field['html_type'] == 'Radio' ||
2286 $field['html_type'] == 'Select' ||
2287 $field['html_type'] == 'AdvMulti-Select' ||
2288 $field['html_type'] == 'Multi-Select' ||
2289 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2292 if ($field['option_group_id']) {
2293 $optionGroupID = $field['option_group_id'];
2295 elseif ($field['data_type'] != 'Boolean') {
2296 CRM_Core_Error
::fatal();
2300 // build the cache for custom values with options (label => value)
2301 if ($optionGroupID != NULL) {
2304 FROM civicrm_option_value
2305 WHERE option_group_id = $optionGroupID
2308 $dao = CRM_Core_DAO
::executeQuery($query);
2309 while ($dao->fetch()) {
2310 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2311 $num = round($dao->value
, 2);
2312 $options["$num"] = $dao->label
;
2315 $options[$dao->value
] = $dao->label
;
2319 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2324 * @param $fieldLabel
2325 * @param null $groupTitle
2329 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2330 $params = array(1 => array($fieldLabel, 'String'));
2332 $params[2] = array($groupTitle, 'String');
2335 FROM civicrm_custom_field f
2336 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2337 WHERE ( f.label = %1 OR f.name = %1 )
2338 AND ( g.title = %2 OR g.name = %2 )
2344 FROM civicrm_custom_field f
2345 WHERE ( f.label = %1 OR f.name = %1 )
2349 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2350 if ($dao->fetch() &&
2361 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2363 public static function getNameFromID($ids) {
2364 if (is_array($ids)) {
2365 $ids = implode(',', $ids);
2368 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2369 FROM civicrm_custom_field f
2370 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2371 WHERE f.id IN ($ids)";
2373 $dao = CRM_Core_DAO
::executeQuery($sql);
2375 while ($dao->fetch()) {
2376 $result[$dao->id
] = array(
2377 'field_name' => $dao->field_name
,
2378 'field_label' => $dao->field_label
,
2379 'group_name' => $dao->group_name
,
2380 'group_title' => $dao->group_title
,
2387 * Validate custom data.
2389 * @param array $params
2390 * Custom data submitted.
2391 * ie array( 'custom_1' => 'validate me' );
2394 * validation errors.
2396 public static function validateCustomData($params) {
2398 if (!is_array($params) ||
empty($params)) {
2402 //pick up profile fields.
2403 $profileFields = array();
2404 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2406 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2408 CRM_Core_Action
::VIEW
2412 //lets start w/ params.
2413 foreach ($params as $key => $value) {
2414 $customFieldID = self
::getKeyID($key);
2415 if (!$customFieldID) {
2419 //load the structural info for given field.
2420 $field = new CRM_Core_DAO_CustomField();
2421 $field->id
= $customFieldID;
2422 if (!$field->find(TRUE)) {
2425 $dataType = $field->data_type
;
2427 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2428 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2429 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2431 $fieldTitle = $field->label
;
2434 //no need to validate.
2435 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2439 //lets validate first for required field.
2440 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2441 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2445 //now time to take care of custom field form rules.
2446 $ruleName = $errorMsg = NULL;
2447 switch ($dataType) {
2449 $ruleName = 'integer';
2450 $errorMsg = ts('%1 must be an integer (whole number).',
2451 array(1 => $fieldTitle)
2456 $ruleName = 'money';
2457 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2458 array(1 => $fieldTitle)
2463 $ruleName = 'numeric';
2464 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2465 array(1 => $fieldTitle)
2470 $ruleName = 'wikiURL';
2471 $errorMsg = ts('%1 must be valid Website.',
2472 array(1 => $fieldTitle)
2477 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2479 $funName = "CRM_Utils_Rule::{$ruleName}";
2480 if (is_callable($funName)) {
2481 $valid = call_user_func($funName, $value);
2484 $errors[$key] = $errorMsg;
2493 * @param int $customId
2497 public static function isMultiRecordField($customId) {
2498 $isMultipleWithGid = FALSE;
2499 if (!is_numeric($customId)) {
2500 $customId = self
::getKeyID($customId);
2502 if (is_numeric($customId)) {
2503 $sql = "SELECT cg.id cgId
2504 FROM civicrm_custom_group cg
2505 INNER JOIN civicrm_custom_field cf
2506 ON cg.id = cf.custom_group_id
2507 WHERE cf.id = %1 AND cg.is_multiple = 1";
2508 $params[1] = array($customId, 'Integer');
2509 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2510 if ($dao->fetch()) {
2512 $isMultipleWithGid = $dao->cgId
;
2517 return $isMultipleWithGid;
2521 * Does this field store a serialized string?
2522 * @param CRM_Core_DAO_CustomField|array $field
2525 public static function isSerialized($field) {
2526 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2527 $field = (array) $field;
2528 // 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.
2529 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);