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 //CRM-15792 - Custom field gets disabled if is_active not set
282 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, TRUE);
283 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
284 $customField->save();
286 // make sure all values are present in the object for further processing
287 $customField->find(TRUE);
289 $triggerRebuild = CRM_Utils_Array
::value('triggerRebuild', $params, TRUE);
290 //create/drop the index when we toggle the is_searchable flag
291 if (!empty($params['id'])) {
292 self
::createField($customField, 'modify', $indexExist, $triggerRebuild);
295 if (!isset($origParams['column_name'])) {
296 $columnName .= "_{$customField->id}";
297 $params['column_name'] = $columnName;
299 $customField->column_name
= $columnName;
300 $customField->save();
301 // make sure all values are present in the object
302 $customField->find(TRUE);
305 self
::createField($customField, 'add', $indexExist, $triggerRebuild);
308 // complete transaction
309 $transaction->commit();
311 CRM_Utils_System
::flushCache();
317 * Fetch object based on array of properties.
319 * @param array $params
320 * (reference ) an assoc array of name/value pairs.
321 * @param array $defaults
322 * (reference ) an assoc array to hold the flattened values.
324 * @return CRM_Core_DAO_CustomField
326 public static function retrieve(&$params, &$defaults) {
327 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
331 * Update the is_active flag in the db.
334 * Id of the database record.
335 * @param bool $is_active
336 * Value we want to set the is_active field.
339 * DAO object on sucess, null otherwise
342 public static function setIsActive($id, $is_active) {
344 CRM_Utils_System
::flushCache();
346 //enable-disable CustomField
347 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
348 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
352 * Get the field title.
361 public static function getTitle($id) {
362 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
366 * Store and return an array of all active custom fields.
368 * @param string $customDataType
369 * Type of Custom Data; empty is a synonym for "all contact data types".
370 * @param bool $showAll
371 * If true returns all fields (includes disabled fields).
372 * @param bool $inline
373 * If true returns all inline fields (includes disabled fields).
374 * @param int $customDataSubType
375 * Custom Data sub type value.
376 * @param int $customDataSubName
377 * Custom Data sub name value.
378 * @param bool $onlyParent
379 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
380 * @param bool $onlySubType
381 * Return only custom data for subtype.
382 * @param bool $checkPermission
383 * If false, do not include permissioning clause.
386 * an array of active custom fields.
389 public static function &getFields(
390 $customDataType = 'Individual',
393 $customDataSubType = NULL,
394 $customDataSubName = NULL,
396 $onlySubType = FALSE,
397 $checkPermission = TRUE
399 if (empty($customDataType)) {
400 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
402 if ($customDataType && !is_array($customDataType)) {
404 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
405 // This is the case when getFieldsForImport() requires fields
406 // limited strictly to a subtype.
407 $customDataSubType = $customDataType;
408 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
412 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
413 // this makes the method flexible to support retrieving fields
414 // for multiple extends value.
415 $customDataType = array($customDataType);
419 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
421 if (is_array($customDataType)) {
422 $cacheKey = implode('_', $customDataType);
425 $cacheKey = $customDataType;
428 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
429 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
430 $cacheKey .= $showAll ?
'_1' : '_0';
431 $cacheKey .= $inline ?
'_1_' : '_0_';
432 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
433 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
434 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
436 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
438 // also get the permission stuff here
439 if ($checkPermission) {
440 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
445 $permissionClause = '(1)';
448 // lets md5 permission clause and take first 8 characters
449 $cacheKey .= substr(md5($permissionClause), 0, 8);
451 if (strlen($cacheKey) > 40) {
452 $cacheKey = md5($cacheKey);
455 if (!self
::$_importFields ||
456 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
458 if (!self
::$_importFields) {
459 self
::$_importFields = array();
462 // check if we can retrieve from database cache
463 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
465 if ($fields === NULL) {
466 $cfTable = self
::getTableName();
469 if (is_array($customDataType)) {
471 foreach ($customDataType as $dataType) {
472 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
473 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
474 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
477 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
479 $value = $value ?
$value . ", {$val}" : $val;
483 $extends = "AND $cgTable.extends IN ( $value ) ";
487 if (!empty($customDataType) && empty($extends)) {
488 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
489 self
::$_importFields[$cacheKey] = array();
490 return self
::$_importFields[$cacheKey];
494 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
497 $query = "SELECT $cfTable.id, $cfTable.label,
501 $cfTable.default_value,
502 $cfTable.options_per_line, $cfTable.text_length,
503 $cfTable.custom_group_id,
504 $cfTable.is_required,
505 $cgTable.extends, $cfTable.is_search_range,
506 $cgTable.extends_entity_column_value,
507 $cgTable.extends_entity_column_id,
509 $cfTable.option_group_id,
510 $cfTable.date_format,
511 $cfTable.time_format,
515 ON $cfTable.custom_group_id = $cgTable.id
519 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
523 $query .= " AND $cgTable.style = 'Inline' ";
526 //get the custom fields for specific type in
527 //combination with fields those support any type.
528 if (!empty($customDataSubType)) {
529 $subtypeClause = array();
530 foreach ($customDataSubType as $subtype) {
531 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
532 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
535 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
537 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
540 if ($customDataSubName) {
541 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
544 // also get the permission stuff here
545 if ($checkPermission) {
546 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
551 $permissionClause = '(1)';
554 $query .= " $extends AND $permissionClause
555 ORDER BY $cgTable.weight, $cgTable.title,
556 $cfTable.weight, $cfTable.label";
558 $dao = CRM_Core_DAO
::executeQuery($query);
561 while (($dao->fetch()) != NULL) {
562 $fields[$dao->id
]['label'] = $dao->label
;
563 $fields[$dao->id
]['groupTitle'] = $dao->title
;
564 $fields[$dao->id
]['data_type'] = $dao->data_type
;
565 $fields[$dao->id
]['html_type'] = $dao->html_type
;
566 $fields[$dao->id
]['default_value'] = $dao->default_value
;
567 $fields[$dao->id
]['text_length'] = $dao->text_length
;
568 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
569 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
570 $fields[$dao->id
]['extends'] = $dao->extends;
571 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
572 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
573 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
574 $fields[$dao->id
]['is_view'] = $dao->is_view
;
575 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
576 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
577 $fields[$dao->id
]['date_format'] = $dao->date_format
;
578 $fields[$dao->id
]['time_format'] = $dao->time_format
;
579 $fields[$dao->id
]['is_required'] = $dao->is_required
;
582 CRM_Core_BAO_Cache
::setItem($fields,
584 "custom importableFields $cacheKey"
587 self
::$_importFields[$cacheKey] = $fields;
590 return self
::$_importFields[$cacheKey];
594 * Return the field ids and names (with groups) for import purpose.
596 * @param int|string $contactType Contact type
597 * @param bool $showAll
598 * If true returns all fields (includes disabled fields).
599 * @param bool $onlyParent
600 * Return fields ONLY related to basic types.
601 * @param bool $search
602 * When called from search and multiple records need to be returned.
603 * @param bool $checkPermission
604 * If false, do not include permissioning clause.
606 * @param bool $withMultiple
612 public static function &getFieldsForImport(
613 $contactType = 'Individual',
617 $checkPermission = TRUE,
618 $withMultiple = FALSE
620 // Note: there are situations when we want getFieldsForImport() return fields related
621 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
622 $fields = &self
::getFields($contactType,
632 $importableFields = array();
633 foreach ($fields as $id => $values) {
634 // for now we should not allow multiple fields in profile / export etc, hence unsetting
636 (!empty($values['is_multiple']) && !$withMultiple)
641 /* generate the key for the fields array */
645 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
646 $importableFields[$key] = array(
648 'title' => CRM_Utils_Array
::value('label', $values),
649 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
651 'custom_field_id' => $id,
652 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
653 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
654 'data_type' => CRM_Utils_Array
::value('data_type', $values),
655 'html_type' => CRM_Utils_Array
::value('html_type', $values),
656 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
659 // CRM-6681, pass date and time format when html_type = Select Date
660 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
661 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
662 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
666 return $importableFields;
670 * Get the field id from an import key.
679 public static function getKeyID($key, $all = FALSE) {
681 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
688 CRM_Utils_Array
::value(2, $match),
692 return $all ?
array(NULL, NULL) : NULL;
696 * Use the cache to get all values of a specific custom field.
698 * @param int $fieldID
699 * The custom field ID.
701 * @return CRM_Core_DAO_CustomField
704 public static function getFieldObject($fieldID) {
705 $field = new CRM_Core_DAO_CustomField();
707 // check if we can get the field values from the system cache
708 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
709 $cache = CRM_Utils_Cache
::singleton();
710 $fieldValues = $cache->get($cacheKey);
711 if (empty($fieldValues)) {
712 $field->id
= $fieldID;
713 if (!$field->find(TRUE)) {
714 CRM_Core_Error
::fatal();
717 $fieldValues = array();
718 CRM_Core_DAO
::storeValues($field, $fieldValues);
720 $cache->set($cacheKey, $fieldValues);
723 $field->copyValues($fieldValues);
730 * This function for building custom fields.
732 * @param CRM_Core_Form $qf
733 * Form object (reference).
734 * @param string $elementName
735 * Name of the custom field.
736 * @param int $fieldId
737 * @param bool $inactiveNeeded
739 * @param bool $useRequired
740 * True if required else false.
741 * @param bool $search
742 * True if used for search else false.
743 * @param string $label
744 * Label for custom field.
747 public static function addQuickFormElement(
751 $inactiveNeeded = FALSE,
756 $field = self
::getFieldObject($fieldId);
757 $widget = $field->html_type
;
759 // Custom field HTML should indicate group+field name
760 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
761 $dataCrmCustomVal = $groupName . ':' . $field->name
;
762 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
763 $field->attributes
.= $dataCrmCustomAttr;
765 // Fixed for Issue CRM-2183
766 if ($widget == 'TextArea' && $search) {
770 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
772 // FIXME: Why are select state/country separate widget types?
773 $isSelect = (in_array($widget, array(
776 'Select State/Province',
777 'Multi-Select State/Province',
779 'Multi-Select Country',
786 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array(
787 'field' => "custom_$fieldId",
788 'context' => $search ?
'search' : 'create',
791 // Consolidate widget types to simplify the below switch statement
792 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
795 $selectAttributes = array(
796 'data-crm-custom' => $dataCrmCustomVal,
797 'class' => 'crm-select2',
799 // Search field is always multi-select
800 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
801 $selectAttributes['class'] .= ' huge';
802 $selectAttributes['multiple'] = 'multiple';
803 $selectAttributes['placeholder'] = $placeholder;
805 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
806 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
807 $selectAttributes +
= array(
808 'data-api-entity' => 'contact',
809 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
810 'data-api-field' => 'custom_' . $field->id
,
811 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
816 if (!isset($label)) {
817 $label = $field->label
;
821 * at some point in time we might want to split the below into small functions
827 if ($field->is_search_range
&& $search) {
828 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
829 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
832 $element = &$qf->add('text', $elementName, $label,
834 $useRequired && !$search
840 $attributes = $dataCrmCustomAttr;
841 if ($field->note_rows
) {
842 $attributes .= 'rows=' . $field->note_rows
;
845 $attributes .= 'rows=4';
847 if ($field->note_columns
) {
848 $attributes .= ' cols=' . $field->note_columns
;
851 $attributes .= ' cols=60';
853 if ($field->text_length
) {
854 $attributes .= ' maxlength=' . $field->text_length
;
856 $element = &$qf->add('textarea',
860 $useRequired && !$search
865 if ($field->is_search_range
&& $search) {
866 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
868 'format' => $field->date_format
,
869 'timeFormat' => $field->time_format
,
870 'startOffset' => $field->start_date_years
,
871 'endOffset' => $field->end_date_years
,
872 'data-crm-custom' => $dataCrmCustomVal,
876 $qf->addDate($elementName . '_to', ts('To'), FALSE,
878 'format' => $field->date_format
,
879 'timeFormat' => $field->time_format
,
880 'startOffset' => $field->start_date_years
,
881 'endOffset' => $field->end_date_years
,
882 'data-crm-custom' => $dataCrmCustomVal,
887 $required = $useRequired && !$search;
889 $qf->addDate($elementName, $label, $required, array(
890 'format' => $field->date_format
,
891 'timeFormat' => $field->time_format
,
892 'startOffset' => $field->start_date_years
,
893 'endOffset' => $field->end_date_years
,
894 'data-crm-custom' => $dataCrmCustomVal,
901 foreach ($options as $v => $l) {
902 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
904 $group = $qf->addGroup($choice, $elementName, $label);
905 if ($useRequired && !$search) {
906 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
909 $group->setAttribute('allowClear', TRUE);
913 // For all select elements
915 if (empty($selectAttributes['multiple'])) {
916 $options = array('' => $placeholder) +
$options;
918 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
920 // Add and/or option for fields that store multiple values
921 if ($search && self
::isSerialized($field)) {
924 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
925 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
927 $qf->addGroup($operators, $elementName . '_operator');
928 $qf->setDefaults(array($elementName . '_operator' => 'or'));
932 case 'AdvMulti-Select':
933 $include =& $qf->addElement(
940 'class' => 'advmultiselect',
941 'data-crm-custom' => $dataCrmCustomVal,
945 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
946 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
948 if ($useRequired && !$search) {
949 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
955 foreach ($options as $v => $l) {
956 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
958 $qf->addGroup($check, $elementName, $label);
959 if ($useRequired && !$search) {
960 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
965 // we should not build upload file in search mode
970 strtolower($field->html_type
),
974 $useRequired && !$search
976 $qf->addUploadElement($elementName);
979 case 'RichTextEditor':
981 'rows' => $field->note_rows
,
982 'cols' => $field->note_columns
,
983 'data-crm-custom' => $dataCrmCustomVal,
985 if ($field->text_length
) {
986 $attributes['maxlength'] = $field->text_length
;
988 $qf->addWysiwyg($elementName, $label, $attributes, $search);
991 case 'Autocomplete-Select':
992 static $customUrls = array();
993 // Fixme: why is this a string in the first place??
994 $attributes = array();
995 if ($field->attributes
) {
996 foreach (explode(' ', $field->attributes
) as $at) {
997 if (strpos($at, '=')) {
998 list($k, $v) = explode('=', $at);
999 $attributes[$k] = trim($v, ' "');
1003 if ($field->data_type
== 'ContactReference') {
1004 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1005 $attributes['data-api-entity'] = 'contact';
1006 $qf->add('text', $elementName, $label, $attributes,
1007 $useRequired && !$search
1010 $urlParams = "context=customfield&id={$field->id}";
1012 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1019 // FIXME: This won't work with customFieldOptions hook
1020 $attributes +
= array(
1021 'entity' => 'option_value',
1022 'placeholder' => $placeholder,
1023 'multiple' => $search,
1025 'params' => array('option_group_id' => $field->option_group_id
),
1028 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1031 $qf->assign('customUrls', $customUrls);
1035 switch ($field->data_type
) {
1037 // integers will have numeric rule applied to them.
1038 if ($field->is_search_range
&& $search) {
1039 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1040 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1042 elseif ($widget == 'Text') {
1043 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1048 if ($field->is_search_range
&& $search) {
1049 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1050 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1052 elseif ($widget == 'Text') {
1053 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1058 if ($field->is_search_range
&& $search) {
1059 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1060 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1062 elseif ($widget == 'Text') {
1063 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1068 $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
1069 $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
1070 $element->setAttribute('class', "url");
1071 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1074 if ($field->is_view
&& !$search) {
1075 $qf->freeze($elementName);
1080 * Delete the Custom Field.
1082 * @param object $field
1085 public static function deleteField($field) {
1086 CRM_Utils_System
::flushCache();
1088 // first delete the custom option group and values associated with this field
1089 if ($field->option_group_id
) {
1090 //check if option group is related to any other field, if
1091 //not delete the option group and related option values
1092 self
::checkOptionGroup($field->option_group_id
);
1095 // next drop the column from the custom value table
1096 self
::createField($field, 'delete');
1099 CRM_Core_BAO_UFField
::delUFField($field->id
);
1100 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1104 * Given a custom field value, its id and the set of options
1105 * find the display value for this field
1107 * @param mixed $value
1108 * The custom field value.
1110 * The custom field id.
1111 * @param int $options
1112 * The assoc array of option name/value pairs.
1114 * @param int $contactID
1115 * @param int $fieldID
1121 public static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1122 $option = &$options[$id];
1123 $attributes = &$option['attributes'];
1124 $html_type = $attributes['html_type'];
1125 $data_type = $attributes['data_type'];
1126 $format = CRM_Utils_Array
::value('format', $attributes);
1128 return self
::getDisplayValueCommon($value,
1143 * @param null $format
1144 * @param int $contactID
1145 * @param int $fieldID
1147 * @return array|mixed|null|string
1149 public static function getDisplayValueCommon(
1161 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1162 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1163 $html_type == 'Select' ||
1164 $html_type == 'CheckBox' ||
1165 $html_type == 'AdvMulti-Select' ||
1166 $html_type == 'Multi-Select'
1169 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1172 switch ($html_type) {
1174 if ($data_type == 'Boolean') {
1175 // Do not assume that if not yes means no.
1178 $display = ts('Yes');
1180 elseif ((string) $value === '0') {
1181 $display = ts('No');
1185 $display = CRM_Utils_Array
::value($value, $option);
1189 case 'Autocomplete-Select':
1190 if ($data_type == 'ContactReference' &&
1193 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1196 $display = CRM_Utils_Array
::value($value, $option);
1201 $display = CRM_Utils_Array
::value($value, $option);
1205 case 'AdvMulti-Select':
1206 case 'Multi-Select':
1207 if (is_array($value)) {
1208 $checkedData = $value;
1211 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1212 substr($value, 1, -1)
1214 if ($html_type == 'CheckBox') {
1216 foreach ($checkedData as $v) {
1219 $checkedData = $newData;
1225 foreach ($checkedData as $key => $val) {
1226 if ($html_type == 'CheckBox') {
1229 $v[] = CRM_Utils_Array
::value($key, $option);
1234 $v[] = CRM_Utils_Array
::value($val, $option);
1238 $display = implode(', ', $v);
1243 if (is_array($value)) {
1244 foreach ($value as $key => $val) {
1245 $display[$key] = CRM_Utils_Date
::customFormat($val);
1249 // remove time element display if time is not set
1250 if (empty($option['attributes']['time_format'])) {
1251 $value = substr($value, 0, 10);
1253 $display = CRM_Utils_Date
::customFormat($value);
1257 case 'Select State/Province':
1258 if (empty($value)) {
1262 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1266 case 'Multi-Select State/Province':
1267 if (is_array($value)) {
1268 $checkedData = $value;
1271 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1272 substr($value, 1, -1)
1276 $states = CRM_Core_PseudoConstant
::stateProvince();
1278 foreach ($checkedData as $stateID) {
1282 $display .= $states[$stateID];
1286 case 'Select Country':
1287 if (empty($value)) {
1291 $display = CRM_Core_PseudoConstant
::country($value);
1295 case 'Multi-Select Country':
1296 if (is_array($value)) {
1297 $checkedData = $value;
1300 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1301 substr($value, 1, -1)
1305 $countries = CRM_Core_PseudoConstant
::country();
1307 foreach ($checkedData as $countryID) {
1311 $display .= $countries[$countryID];
1317 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1318 $display = $icons[$value];
1323 if (empty($value)) {
1327 $display = nl2br($value);
1332 if (empty($value)) {
1339 return $display ?
$display : $value;
1343 * Set default values for custom data used in profile.
1345 * @param int $customFieldId
1347 * @param string $elementName
1348 * Custom field name.
1349 * @param array $defaults
1350 * Associated array of fields.
1351 * @param int $contactId
1355 * @param mixed $value
1356 * If passed - dont fetch value from db,.
1357 * just format the given value
1360 public static function setProfileDefaults(
1368 //get the type of custom field
1369 $customField = new CRM_Core_BAO_CustomField();
1370 $customField->id
= $customFieldId;
1371 $customField->find(TRUE);
1374 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1375 $value = $customField->default_value
;
1379 if (!isset($value)) {
1380 $info = self
::getTableColumnGroup($customFieldId);
1381 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1382 $result = CRM_Core_DAO
::executeQuery($query);
1383 if ($result->fetch()) {
1384 $value = $result->value
;
1388 if ($customField->data_type
== 'Country') {
1390 $config = CRM_Core_Config
::singleton();
1391 if ($config->defaultContactCountry
) {
1392 $value = $config->defaultContactCountry();
1398 //set defaults if mode is registration
1399 if (!trim($value) &&
1401 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1403 $value = $customField->default_value
;
1406 if ($customField->data_type
== 'Money' && isset($value)) {
1407 $value = number_format($value, 2);
1409 switch ($customField->html_type
) {
1411 case 'AdvMulti-Select':
1412 case 'Multi-Select':
1413 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1414 $defaults[$elementName] = array();
1415 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1416 substr($value, 1, -1)
1418 foreach ($customOption as $val) {
1419 if (in_array($val['value'], $checkedValue)) {
1420 if ($customField->html_type
== 'CheckBox') {
1421 $defaults[$elementName][$val['value']] = 1;
1423 elseif ($customField->html_type
== 'Multi-Select' ||
1424 $customField->html_type
== 'AdvMulti-Select'
1426 $defaults[$elementName][$val['value']] = $val['value'];
1434 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1437 $customField->date_format
,
1438 $customField->time_format
1443 case 'Autocomplete-Select':
1444 if ($customField->data_type
== 'ContactReference') {
1445 if (is_numeric($value)) {
1446 $defaults[$elementName . '_id'] = $value;
1447 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1451 $defaults[$elementName] = $value;
1456 $defaults[$elementName] = $value;
1461 * @param int $contactID
1463 * @param int $fileID
1464 * @param bool $absolute
1469 * @param int $contactID
1471 * @param int $fileID
1472 * @param bool $absolute
1476 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1479 $params = array('id' => $cfID);
1480 $defaults = array();
1481 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1482 $columnName = $defaults['column_name'];
1484 //table name of custom data
1485 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1486 $defaults['custom_group_id'],
1490 //query to fetch id from civicrm_file
1491 if ($multiRecordWhereClause) {
1492 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1495 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1497 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1502 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1507 $result['file_id'] = $fileID;
1509 if ($fileType == 'image/jpeg' ||
1510 $fileType == 'image/pjpeg' ||
1511 $fileType == 'image/gif' ||
1512 $fileType == 'image/x-png' ||
1513 $fileType == 'image/png'
1515 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1520 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1521 list($imageWidth, $imageHeight) = getimagesize($path);
1522 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1523 $url = CRM_Utils_System
::url('civicrm/file',
1524 "reset=1&id=$fileID&eid=$contactID",
1525 $absolute, NULL, TRUE, TRUE
1527 $result['file_url'] = "
1528 <a href=\"$url\" class='crm-image-popup'>
1529 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1531 // for non image files
1534 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1538 $url = CRM_Utils_System
::url('civicrm/file',
1539 "reset=1&id=$fileID&eid=$contactID",
1540 $absolute, NULL, TRUE, TRUE
1542 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1550 * Format custom fields before inserting.
1552 * @param int $customFieldId
1554 * @param array $customFormatted
1557 * Value of custom field.
1558 * @param string $customFieldExtend
1559 * Custom field extends.
1560 * @param int $customValueId
1561 * Custom option value id.
1562 * @param int $entityId
1563 * Entity id (contribution, membership...).
1564 * @param bool $inline
1565 * Consider inline custom groups only.
1566 * @param bool $checkPermission
1567 * If false, do not include permissioning clause.
1568 * @param bool $includeViewOnly
1569 * If true, fields marked 'View Only' are included. Required for APIv3.
1571 * @return array|NULL
1572 * formatted custom field array
1574 public static function formatCustomField(
1575 $customFieldId, &$customFormatted, $value,
1576 $customFieldExtend, $customValueId = NULL,
1579 $checkPermission = TRUE,
1580 $includeViewOnly = FALSE
1582 //get the custom fields for the entity
1583 //subtype and basic type
1584 $customDataSubType = NULL;
1585 if (is_array($customFieldExtend)) {
1586 $customFieldExtend = $customFieldExtend[0];
1589 if (in_array($customFieldExtend,
1590 CRM_Contact_BAO_ContactType
::subTypes()
1592 // This is the case when getFieldsForImport() requires fields
1593 // of subtype and its parent.CRM-5143
1594 $customDataSubType = $customFieldExtend;
1595 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1598 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1608 if (!array_key_exists($customFieldId, $customFields)) {
1612 // return if field is a 'code' field
1613 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1617 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1619 if (!$customValueId &&
1620 // we always create new entites for is_multiple unless specified
1621 !$customFields[$customFieldId]['is_multiple'] &&
1627 WHERE entity_id={$entityId}";
1629 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1632 //fix checkbox, now check box always submits values
1633 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1635 // Note that only during merge this is not an array, and you can directly use value
1636 if (is_array($value)) {
1637 $selectedValues = array();
1638 foreach ($value as $selId => $val) {
1640 $selectedValues[] = $selId;
1643 if (!empty($selectedValues)) {
1644 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1646 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1655 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1656 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1659 // Note that only during merge this is not an array,
1660 // and you can directly use value, CRM-4385
1661 if (is_array($value)) {
1662 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1663 array_values($value)
1664 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1672 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1673 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1674 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1676 $customFields[$customFieldId]['data_type'] == 'String' &&
1677 !empty($customFields[$customFieldId]['text_length']) &&
1680 // lets make sure that value is less than the length, else we'll
1681 // be losing some data, CRM-7481
1682 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1683 // need to do a few things here
1685 // 1. lets find a new length
1686 $newLength = $customFields[$customFieldId]['text_length'];
1687 $minLength = strlen($value);
1688 while ($newLength < $minLength) {
1689 $newLength = $newLength * 2;
1692 // set the custom field meta data to have a length larger than value
1693 // alter the custom value table column to match this length
1694 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1699 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1700 if (!CRM_Utils_System
::isNull($value)) {
1701 $format = $customFields[$customFieldId]['date_format'];
1702 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1707 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1708 $customFields[$customFieldId]['data_type'] == 'Money'
1714 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1715 $value = CRM_Utils_Rule
::cleanMoney($value);
1719 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1720 $customFields[$customFieldId]['data_type'] == 'Country'
1730 if ($customFields[$customFieldId]['data_type'] == 'File') {
1731 if (empty($value)) {
1735 $config = CRM_Core_Config
::singleton();
1737 $fName = $value['name'];
1738 $mimeType = $value['type'];
1740 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1742 // rename this file to go into the secure directory
1743 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1744 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1747 if ($customValueId) {
1752 $params = array(1 => array($customValueId, 'Integer'));
1753 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1756 $fileDAO = new CRM_Core_DAO_File();
1759 $fileDAO->id
= $fileId;
1762 $fileDAO->uri
= $filename;
1763 $fileDAO->mime_type
= $mimeType;
1764 $fileDAO->upload_date
= date('Ymdhis');
1766 $fileId = $fileDAO->id
;
1770 if (!is_array($customFormatted)) {
1771 $customFormatted = array();
1774 if (!array_key_exists($customFieldId, $customFormatted)) {
1775 $customFormatted[$customFieldId] = array();
1779 if ($customValueId) {
1780 $index = $customValueId;
1783 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1784 $customFormatted[$customFieldId][$index] = array();
1786 $customFormatted[$customFieldId][$index] = array(
1787 'id' => $customValueId > 0 ?
$customValueId : NULL,
1789 'type' => $customFields[$customFieldId]['data_type'],
1790 'custom_field_id' => $customFieldId,
1791 'custom_group_id' => $groupID,
1792 'table_name' => $tableName,
1793 'column_name' => $columnName,
1794 'file_id' => $fileId,
1795 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1798 //we need to sort so that custom fields are created in the order of entry
1799 krsort($customFormatted[$customFieldId]);
1800 return $customFormatted;
1804 * @param array $params
1808 public static function &defaultCustomTableSchema(&$params) {
1809 // add the id and extends_id
1811 'name' => $params['name'],
1812 'is_multiple' => $params['is_multiple'],
1813 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1817 'type' => 'int unsigned',
1820 'attributes' => 'AUTO_INCREMENT',
1821 'comment' => 'Default MySQL primary key',
1824 'name' => 'entity_id',
1825 'type' => 'int unsigned',
1827 'comment' => 'Table that this extends',
1828 'fk_table_name' => $params['extends_name'],
1829 'fk_field_name' => 'id',
1830 'fk_attributes' => 'ON DELETE CASCADE',
1835 if (!$params['is_multiple']) {
1836 $table['indexes'] = array(
1839 'field_name_1' => 'entity_id',
1849 * @param bool $indexExist
1850 * @param bool $triggerRebuild
1852 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1853 $tableName = CRM_Core_DAO
::getFieldValue(
1854 'CRM_Core_DAO_CustomGroup',
1855 $field->custom_group_id
,
1860 'table_name' => $tableName,
1861 'operation' => $operation,
1862 'name' => $field->column_name
,
1863 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1867 'required' => $field->is_required
,
1868 'searchable' => $field->is_searchable
,
1871 if ($operation == 'delete') {
1872 $fkName = "{$tableName}_{$field->column_name}";
1873 if (strlen($fkName) >= 48) {
1874 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1876 $params['fkName'] = $fkName;
1878 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1879 $params['fk_table_name'] = 'civicrm_country';
1880 $params['fk_field_name'] = 'id';
1881 $params['fk_attributes'] = 'ON DELETE SET NULL';
1883 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1884 $params['type'] = 'varchar(255)';
1886 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1887 $params['fk_table_name'] = 'civicrm_state_province';
1888 $params['fk_field_name'] = 'id';
1889 $params['fk_attributes'] = 'ON DELETE SET NULL';
1891 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1892 $params['type'] = 'varchar(255)';
1894 elseif ($field->data_type
== 'File') {
1895 $params['fk_table_name'] = 'civicrm_file';
1896 $params['fk_field_name'] = 'id';
1897 $params['fk_attributes'] = 'ON DELETE SET NULL';
1899 elseif ($field->data_type
== 'ContactReference') {
1900 $params['fk_table_name'] = 'civicrm_contact';
1901 $params['fk_field_name'] = 'id';
1902 $params['fk_attributes'] = 'ON DELETE SET NULL';
1904 if (isset($field->default_value
)) {
1905 $params['default'] = "'{$field->default_value}'";
1908 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1912 * Determine whether it would be safe to move a field.
1914 * @param int $fieldID
1915 * FK to civicrm_custom_field.
1916 * @param int $newGroupID
1917 * FK to civicrm_custom_group.
1920 * array(string) or TRUE
1922 public static function _moveFieldValidate($fieldID, $newGroupID) {
1925 $field = new CRM_Core_DAO_CustomField();
1926 $field->id
= $fieldID;
1927 if (!$field->find(TRUE)) {
1928 $errors['fieldID'] = 'Invalid ID for custom field';
1932 $oldGroup = new CRM_Core_DAO_CustomGroup();
1933 $oldGroup->id
= $field->custom_group_id
;
1934 if (!$oldGroup->find(TRUE)) {
1935 $errors['fieldID'] = 'Invalid ID for old custom group';
1939 $newGroup = new CRM_Core_DAO_CustomGroup();
1940 $newGroup->id
= $newGroupID;
1941 if (!$newGroup->find(TRUE)) {
1942 $errors['newGroupID'] = 'Invalid ID for new custom group';
1948 FROM civicrm_custom_field a
1949 INNER JOIN civicrm_custom_field b
1951 AND a.label = b.label
1952 AND b.custom_group_id = %2
1955 1 => array($field->id
, 'Integer'),
1956 2 => array($newGroup->id
, 'Integer'),
1958 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1960 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1963 $tableName = $oldGroup->table_name
;
1964 $columnName = $field->column_name
;
1969 WHERE $columnName is not null
1971 $count = CRM_Core_DAO
::singleValueQuery($query,
1972 CRM_Core_DAO
::$_nullArray
1977 FROM civicrm_custom_group
1978 WHERE id IN ( %1, %2 )
1981 1 => array($oldGroup->id
, 'Integer'),
1982 2 => array($newGroup->id
, 'Integer'),
1985 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1987 while ($dao->fetch()) {
1988 $extends[] = $dao->extends;
1990 if ($extends[0] != $extends[1]) {
1991 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1995 return empty($errors) ?
TRUE : $errors;
1999 * Move a custom data field from one group (table) to another
2001 * @param int $fieldID
2002 * FK to civicrm_custom_field.
2003 * @param int $newGroupID
2004 * FK to civicrm_custom_group.
2008 public static function moveField($fieldID, $newGroupID) {
2009 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
2010 if (TRUE !== $validation) {
2011 CRM_Core_Error
::fatal(implode(' ', $validation));
2013 $field = new CRM_Core_DAO_CustomField();
2014 $field->id
= $fieldID;
2017 $newGroup = new CRM_Core_DAO_CustomGroup();
2018 $newGroup->id
= $newGroupID;
2019 $newGroup->find(TRUE);
2021 $oldGroup = new CRM_Core_DAO_CustomGroup();
2022 $oldGroup->id
= $field->custom_group_id
;
2023 $oldGroup->find(TRUE);
2026 $add->custom_group_id
= $newGroup->id
;
2027 self
::createField($add, 'add');
2029 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2030 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2031 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2033 CRM_Core_DAO
::executeQuery($sql);
2036 $del->custom_group_id
= $oldGroup->id
;
2037 self
::createField($del, 'delete');
2041 CRM_Utils_System
::flushCache();
2045 * Get the database table name and column name for a custom field.
2047 * @param int $fieldID
2048 * The fieldID of the custom field.
2049 * @param bool $force
2050 * Force the sql to be run again (primarily used for tests).
2053 * fatal is fieldID does not exists, else array of tableName, columnName
2055 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2056 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2057 $cache = CRM_Utils_Cache
::singleton();
2058 $fieldValues = $cache->get($cacheKey);
2059 if (empty($fieldValues) ||
$force) {
2061 SELECT cg.table_name, cf.column_name, cg.id
2062 FROM civicrm_custom_group cg,
2063 civicrm_custom_field cf
2064 WHERE cf.custom_group_id = cg.id
2066 $params = array(1 => array($fieldID, 'Integer'));
2067 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2069 if (!$dao->fetch()) {
2070 CRM_Core_Error
::fatal();
2073 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2074 $cache->set($cacheKey, $fieldValues);
2076 return $fieldValues;
2080 * Get custom option groups.
2082 * @param array $includeFieldIds
2083 * Ids of custom fields for which.
2084 * option groups must be included.
2086 * Currently this is required in the cases where option groups are to be included
2087 * for inactive fields : CRM-5369
2092 public static function &customOptionGroup($includeFieldIds = NULL) {
2093 static $customOptionGroup = NULL;
2095 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2096 if ($cacheKey == 'force') {
2097 $customOptionGroup[$cacheKey] = NULL;
2100 if (empty($customOptionGroup[$cacheKey])) {
2101 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2103 //support for single as well as array format.
2104 if (!empty($includeFieldIds)) {
2105 if (is_array($includeFieldIds)) {
2106 $includeFieldIds = implode(',', $includeFieldIds);
2108 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2112 SELECT g.id, g.title
2113 FROM civicrm_option_group g
2114 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2115 WHERE {$whereClause}";
2117 $dao = CRM_Core_DAO
::executeQuery($query);
2118 while ($dao->fetch()) {
2119 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2123 return $customOptionGroup[$cacheKey];
2127 * Fix orphan groups.
2129 * @param int $customFieldId
2131 * @param int $optionGroupId
2136 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2137 // check if option group belongs to any custom Field else delete
2138 // get the current option group
2139 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2143 // get the updated option group
2144 // if both are same return
2145 if ($currentOptionGroupId == $optionGroupId) {
2149 // check if option group is related to any other field
2150 self
::checkOptionGroup($currentOptionGroupId);
2154 * Check if option group is related to more than one
2157 * @param int $optionGroupId
2162 public static function checkOptionGroup($optionGroupId) {
2165 FROM civicrm_custom_field
2166 WHERE option_group_id = {$optionGroupId}";
2168 $count = CRM_Core_DAO
::singleValueQuery($query);
2171 //delete the option group
2172 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2177 * @param int $optionGroupId
2180 * @return null|string
2182 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2184 SELECT default_value, html_type
2185 FROM civicrm_custom_field
2186 WHERE option_group_id = {$optionGroupId}
2187 AND default_value IS NOT NULL
2188 ORDER BY html_type";
2190 $dao = CRM_Core_DAO
::executeQuery($query);
2191 $defaultValue = NULL;
2192 $defaultHTMLType = NULL;
2193 while ($dao->fetch()) {
2194 if ($dao->html_type
== $htmlType) {
2195 return $dao->default_value
;
2197 if ($defaultValue == NULL) {
2198 $defaultValue = $dao->default_value
;
2199 $defaultHTMLType = $dao->html_type
;
2203 // some conversions are needed if either the old or new has a html type which has potential
2204 // multiple default values.
2205 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2206 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2208 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2210 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2211 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2213 $defaultValue = substr($defaultValue, 1, -1);
2214 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2215 substr($defaultValue, 1, -1)
2217 $defaultValue = $values[0];
2220 return $defaultValue;
2224 * @param array $params
2225 * @param $customFields
2226 * @param int $entityID
2227 * @param $customFieldExtends
2228 * @param bool $inline
2232 public static function postProcess(
2236 $customFieldExtends,
2239 $customData = array();
2241 foreach ($params as $key => $value) {
2242 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2244 // for autocomplete transfer hidden value instead of label
2245 if ($params[$key] && isset($params[$key . '_id'])) {
2246 $value = $params[$key . '_id'];
2249 // we need to append time with date
2250 if ($params[$key] && isset($params[$key . '_time'])) {
2251 $value .= ' ' . $params[$key . '_time'];
2254 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2257 $customFieldExtends,
2258 $customFieldInfo[1],
2273 public static function buildOption($field, &$options) {
2274 // Fixme - adding anything but options to the $options array is a bad idea
2275 // What if an option had the key 'attributes'?
2276 $options['attributes'] = array(
2277 'label' => $field['label'],
2278 'data_type' => $field['data_type'],
2279 'html_type' => $field['html_type'],
2282 $optionGroupID = NULL;
2283 if (($field['html_type'] == 'CheckBox' ||
2284 $field['html_type'] == 'Radio' ||
2285 $field['html_type'] == 'Select' ||
2286 $field['html_type'] == 'AdvMulti-Select' ||
2287 $field['html_type'] == 'Multi-Select' ||
2288 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2291 if ($field['option_group_id']) {
2292 $optionGroupID = $field['option_group_id'];
2294 elseif ($field['data_type'] != 'Boolean') {
2295 CRM_Core_Error
::fatal();
2299 // build the cache for custom values with options (label => value)
2300 if ($optionGroupID != NULL) {
2303 FROM civicrm_option_value
2304 WHERE option_group_id = $optionGroupID
2307 $dao = CRM_Core_DAO
::executeQuery($query);
2308 while ($dao->fetch()) {
2309 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2310 $num = round($dao->value
, 2);
2311 $options["$num"] = $dao->label
;
2314 $options[$dao->value
] = $dao->label
;
2318 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2323 * @param $fieldLabel
2324 * @param null $groupTitle
2328 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2329 $params = array(1 => array($fieldLabel, 'String'));
2331 $params[2] = array($groupTitle, 'String');
2334 FROM civicrm_custom_field f
2335 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2336 WHERE ( f.label = %1 OR f.name = %1 )
2337 AND ( g.title = %2 OR g.name = %2 )
2343 FROM civicrm_custom_field f
2344 WHERE ( f.label = %1 OR f.name = %1 )
2348 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2349 if ($dao->fetch() &&
2360 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2362 public static function getNameFromID($ids) {
2363 if (is_array($ids)) {
2364 $ids = implode(',', $ids);
2367 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2368 FROM civicrm_custom_field f
2369 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2370 WHERE f.id IN ($ids)";
2372 $dao = CRM_Core_DAO
::executeQuery($sql);
2374 while ($dao->fetch()) {
2375 $result[$dao->id
] = array(
2376 'field_name' => $dao->field_name
,
2377 'field_label' => $dao->field_label
,
2378 'group_name' => $dao->group_name
,
2379 'group_title' => $dao->group_title
,
2386 * Validate custom data.
2388 * @param array $params
2389 * Custom data submitted.
2390 * ie array( 'custom_1' => 'validate me' );
2393 * validation errors.
2395 public static function validateCustomData($params) {
2397 if (!is_array($params) ||
empty($params)) {
2401 //pick up profile fields.
2402 $profileFields = array();
2403 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2405 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2407 CRM_Core_Action
::VIEW
2411 //lets start w/ params.
2412 foreach ($params as $key => $value) {
2413 $customFieldID = self
::getKeyID($key);
2414 if (!$customFieldID) {
2418 //load the structural info for given field.
2419 $field = new CRM_Core_DAO_CustomField();
2420 $field->id
= $customFieldID;
2421 if (!$field->find(TRUE)) {
2424 $dataType = $field->data_type
;
2426 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2427 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2428 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2430 $fieldTitle = $field->label
;
2433 //no need to validate.
2434 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2438 //lets validate first for required field.
2439 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2440 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2444 //now time to take care of custom field form rules.
2445 $ruleName = $errorMsg = NULL;
2446 switch ($dataType) {
2448 $ruleName = 'integer';
2449 $errorMsg = ts('%1 must be an integer (whole number).',
2450 array(1 => $fieldTitle)
2455 $ruleName = 'money';
2456 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2457 array(1 => $fieldTitle)
2462 $ruleName = 'numeric';
2463 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2464 array(1 => $fieldTitle)
2469 $ruleName = 'wikiURL';
2470 $errorMsg = ts('%1 must be valid Website.',
2471 array(1 => $fieldTitle)
2476 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2478 $funName = "CRM_Utils_Rule::{$ruleName}";
2479 if (is_callable($funName)) {
2480 $valid = call_user_func($funName, $value);
2483 $errors[$key] = $errorMsg;
2492 * @param int $customId
2496 public static function isMultiRecordField($customId) {
2497 $isMultipleWithGid = FALSE;
2498 if (!is_numeric($customId)) {
2499 $customId = self
::getKeyID($customId);
2501 if (is_numeric($customId)) {
2502 $sql = "SELECT cg.id cgId
2503 FROM civicrm_custom_group cg
2504 INNER JOIN civicrm_custom_field cf
2505 ON cg.id = cf.custom_group_id
2506 WHERE cf.id = %1 AND cg.is_multiple = 1";
2507 $params[1] = array($customId, 'Integer');
2508 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2509 if ($dao->fetch()) {
2511 $isMultipleWithGid = $dao->cgId
;
2516 return $isMultipleWithGid;
2520 * Does this field store a serialized string?
2521 * @param CRM_Core_DAO_CustomField|array $field
2524 public static function isSerialized($field) {
2525 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2526 $field = (array) $field;
2527 // 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.
2528 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);