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,
512 $cgTable.is_multiple,
513 og.name as option_group_name
516 ON $cfTable.custom_group_id = $cgTable.id
517 LEFT JOIN civicrm_option_group og
518 ON $cfTable.option_group_id = og.id
522 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
526 $query .= " AND $cgTable.style = 'Inline' ";
529 //get the custom fields for specific type in
530 //combination with fields those support any type.
531 if (!empty($customDataSubType)) {
532 $subtypeClause = array();
533 foreach ($customDataSubType as $subtype) {
534 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
535 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
538 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
540 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
543 if ($customDataSubName) {
544 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
547 // also get the permission stuff here
548 if ($checkPermission) {
549 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
554 $permissionClause = '(1)';
557 $query .= " $extends AND $permissionClause
558 ORDER BY $cgTable.weight, $cgTable.title,
559 $cfTable.weight, $cfTable.label";
561 $dao = CRM_Core_DAO
::executeQuery($query);
564 while (($dao->fetch()) != NULL) {
565 $fields[$dao->id
]['label'] = $dao->label
;
566 $fields[$dao->id
]['groupTitle'] = $dao->title
;
567 $fields[$dao->id
]['data_type'] = $dao->data_type
;
568 $fields[$dao->id
]['html_type'] = $dao->html_type
;
569 $fields[$dao->id
]['default_value'] = $dao->default_value
;
570 $fields[$dao->id
]['text_length'] = $dao->text_length
;
571 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
572 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
573 $fields[$dao->id
]['extends'] = $dao->extends;
574 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
575 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
576 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
577 $fields[$dao->id
]['is_view'] = $dao->is_view
;
578 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
579 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
580 $fields[$dao->id
]['date_format'] = $dao->date_format
;
581 $fields[$dao->id
]['time_format'] = $dao->time_format
;
582 $fields[$dao->id
]['is_required'] = $dao->is_required
;
583 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
586 CRM_Core_BAO_Cache
::setItem($fields,
588 "custom importableFields $cacheKey"
591 self
::$_importFields[$cacheKey] = $fields;
594 return self
::$_importFields[$cacheKey];
598 * Return the field ids and names (with groups) for import purpose.
600 * @param int|string $contactType Contact type
601 * @param bool $showAll
602 * If true returns all fields (includes disabled fields).
603 * @param bool $onlyParent
604 * Return fields ONLY related to basic types.
605 * @param bool $search
606 * When called from search and multiple records need to be returned.
607 * @param bool $checkPermission
608 * If false, do not include permissioning clause.
610 * @param bool $withMultiple
616 public static function &getFieldsForImport(
617 $contactType = 'Individual',
621 $checkPermission = TRUE,
622 $withMultiple = FALSE
624 // Note: there are situations when we want getFieldsForImport() return fields related
625 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
626 $fields = &self
::getFields($contactType,
636 $importableFields = array();
637 foreach ($fields as $id => $values) {
638 // for now we should not allow multiple fields in profile / export etc, hence unsetting
640 (!empty($values['is_multiple']) && !$withMultiple)
645 /* generate the key for the fields array */
649 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
650 $importableFields[$key] = array(
652 'title' => CRM_Utils_Array
::value('label', $values),
653 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
655 'custom_field_id' => $id,
656 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
657 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
658 'data_type' => CRM_Utils_Array
::value('data_type', $values),
659 'html_type' => CRM_Utils_Array
::value('html_type', $values),
660 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
663 // CRM-6681, pass date and time format when html_type = Select Date
664 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
665 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
666 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
670 return $importableFields;
674 * Get the field id from an import key.
683 public static function getKeyID($key, $all = FALSE) {
685 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
692 CRM_Utils_Array
::value(2, $match),
696 return $all ?
array(NULL, NULL) : NULL;
700 * Use the cache to get all values of a specific custom field.
702 * @param int $fieldID
703 * The custom field ID.
705 * @return CRM_Core_DAO_CustomField
708 public static function getFieldObject($fieldID) {
709 $field = new CRM_Core_DAO_CustomField();
711 // check if we can get the field values from the system cache
712 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
713 $cache = CRM_Utils_Cache
::singleton();
714 $fieldValues = $cache->get($cacheKey);
715 if (empty($fieldValues)) {
716 $field->id
= $fieldID;
717 if (!$field->find(TRUE)) {
718 CRM_Core_Error
::fatal();
721 $fieldValues = array();
722 CRM_Core_DAO
::storeValues($field, $fieldValues);
724 $cache->set($cacheKey, $fieldValues);
727 $field->copyValues($fieldValues);
734 * This function for building custom fields.
736 * @param CRM_Core_Form $qf
737 * Form object (reference).
738 * @param string $elementName
739 * Name of the custom field.
740 * @param int $fieldId
741 * @param bool $inactiveNeeded
743 * @param bool $useRequired
744 * True if required else false.
745 * @param bool $search
746 * True if used for search else false.
747 * @param string $label
748 * Label for custom field.
751 public static function addQuickFormElement(
755 $inactiveNeeded = FALSE,
760 $field = self
::getFieldObject($fieldId);
761 $widget = $field->html_type
;
763 // Custom field HTML should indicate group+field name
764 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
765 $dataCrmCustomVal = $groupName . ':' . $field->name
;
766 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
767 $field->attributes
.= $dataCrmCustomAttr;
769 // Fixed for Issue CRM-2183
770 if ($widget == 'TextArea' && $search) {
774 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
776 // FIXME: Why are select state/country separate widget types?
777 $isSelect = (in_array($widget, array(
780 'Select State/Province',
781 'Multi-Select State/Province',
783 'Multi-Select Country',
790 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array(
791 'field' => "custom_$fieldId",
792 'context' => $search ?
'search' : 'create',
795 // Consolidate widget types to simplify the below switch statement
796 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
799 $selectAttributes = array(
800 'data-crm-custom' => $dataCrmCustomVal,
801 'class' => 'crm-select2',
803 // Search field is always multi-select
804 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
805 $selectAttributes['class'] .= ' huge';
806 $selectAttributes['multiple'] = 'multiple';
807 $selectAttributes['placeholder'] = $placeholder;
809 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
810 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
811 $selectAttributes +
= array(
812 'data-api-entity' => 'contact',
813 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
814 'data-api-field' => 'custom_' . $field->id
,
815 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
820 if (!isset($label)) {
821 $label = $field->label
;
825 * at some point in time we might want to split the below into small functions
831 if ($field->is_search_range
&& $search) {
832 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
833 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
836 $element = &$qf->add('text', $elementName, $label,
838 $useRequired && !$search
844 $attributes = $dataCrmCustomAttr;
845 if ($field->note_rows
) {
846 $attributes .= 'rows=' . $field->note_rows
;
849 $attributes .= 'rows=4';
851 if ($field->note_columns
) {
852 $attributes .= ' cols=' . $field->note_columns
;
855 $attributes .= ' cols=60';
857 if ($field->text_length
) {
858 $attributes .= ' maxlength=' . $field->text_length
;
860 $element = &$qf->add('textarea',
864 $useRequired && !$search
869 if ($field->is_search_range
&& $search) {
870 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
872 'format' => $field->date_format
,
873 'timeFormat' => $field->time_format
,
874 'startOffset' => $field->start_date_years
,
875 'endOffset' => $field->end_date_years
,
876 'data-crm-custom' => $dataCrmCustomVal,
880 $qf->addDate($elementName . '_to', ts('To'), FALSE,
882 'format' => $field->date_format
,
883 'timeFormat' => $field->time_format
,
884 'startOffset' => $field->start_date_years
,
885 'endOffset' => $field->end_date_years
,
886 'data-crm-custom' => $dataCrmCustomVal,
891 $required = $useRequired && !$search;
893 $qf->addDate($elementName, $label, $required, array(
894 'format' => $field->date_format
,
895 'timeFormat' => $field->time_format
,
896 'startOffset' => $field->start_date_years
,
897 'endOffset' => $field->end_date_years
,
898 'data-crm-custom' => $dataCrmCustomVal,
905 foreach ($options as $v => $l) {
906 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
908 $group = $qf->addGroup($choice, $elementName, $label);
909 if ($useRequired && !$search) {
910 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
913 $group->setAttribute('allowClear', TRUE);
917 // For all select elements
919 if (empty($selectAttributes['multiple'])) {
920 $options = array('' => $placeholder) +
$options;
922 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
924 // Add and/or option for fields that store multiple values
925 if ($search && self
::isSerialized($field)) {
928 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
929 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
931 $qf->addGroup($operators, $elementName . '_operator');
932 $qf->setDefaults(array($elementName . '_operator' => 'or'));
936 case 'AdvMulti-Select':
937 $include =& $qf->addElement(
944 'class' => 'advmultiselect',
945 'data-crm-custom' => $dataCrmCustomVal,
949 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
950 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
952 if ($useRequired && !$search) {
953 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
959 foreach ($options as $v => $l) {
960 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
962 $qf->addGroup($check, $elementName, $label);
963 if ($useRequired && !$search) {
964 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
969 // we should not build upload file in search mode
974 strtolower($field->html_type
),
978 $useRequired && !$search
980 $qf->addUploadElement($elementName);
983 case 'RichTextEditor':
985 'rows' => $field->note_rows
,
986 'cols' => $field->note_columns
,
987 'data-crm-custom' => $dataCrmCustomVal,
989 if ($field->text_length
) {
990 $attributes['maxlength'] = $field->text_length
;
992 $qf->addWysiwyg($elementName, $label, $attributes, $search);
995 case 'Autocomplete-Select':
996 static $customUrls = array();
997 // Fixme: why is this a string in the first place??
998 $attributes = array();
999 if ($field->attributes
) {
1000 foreach (explode(' ', $field->attributes
) as $at) {
1001 if (strpos($at, '=')) {
1002 list($k, $v) = explode('=', $at);
1003 $attributes[$k] = trim($v, ' "');
1007 if ($field->data_type
== 'ContactReference') {
1008 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1009 $attributes['data-api-entity'] = 'contact';
1010 $qf->add('text', $elementName, $label, $attributes,
1011 $useRequired && !$search
1014 $urlParams = "context=customfield&id={$field->id}";
1016 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1023 // FIXME: This won't work with customFieldOptions hook
1024 $attributes +
= array(
1025 'entity' => 'option_value',
1026 'placeholder' => $placeholder,
1027 'multiple' => $search,
1029 'params' => array('option_group_id' => $field->option_group_id
),
1032 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1035 $qf->assign('customUrls', $customUrls);
1039 switch ($field->data_type
) {
1041 // integers will have numeric rule applied to them.
1042 if ($field->is_search_range
&& $search) {
1043 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1044 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1046 elseif ($widget == 'Text') {
1047 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1052 if ($field->is_search_range
&& $search) {
1053 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1054 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1056 elseif ($widget == 'Text') {
1057 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1062 if ($field->is_search_range
&& $search) {
1063 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1064 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1066 elseif ($widget == 'Text') {
1067 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1072 $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
1073 $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
1074 $element->setAttribute('class', "url");
1075 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1078 if ($field->is_view
&& !$search) {
1079 $qf->freeze($elementName);
1084 * Delete the Custom Field.
1086 * @param object $field
1089 public static function deleteField($field) {
1090 CRM_Utils_System
::flushCache();
1092 // first delete the custom option group and values associated with this field
1093 if ($field->option_group_id
) {
1094 //check if option group is related to any other field, if
1095 //not delete the option group and related option values
1096 self
::checkOptionGroup($field->option_group_id
);
1099 // next drop the column from the custom value table
1100 self
::createField($field, 'delete');
1103 CRM_Core_BAO_UFField
::delUFField($field->id
);
1104 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1108 * Given a custom field value, its id and the set of options
1109 * find the display value for this field
1111 * @param mixed $value
1112 * The custom field value.
1114 * The custom field id.
1115 * @param int $options
1116 * The assoc array of option name/value pairs.
1118 * @param int $contactID
1119 * @param int $fieldID
1125 public static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1126 $option = &$options[$id];
1127 $attributes = &$option['attributes'];
1128 $html_type = $attributes['html_type'];
1129 $data_type = $attributes['data_type'];
1130 $format = CRM_Utils_Array
::value('format', $attributes);
1132 return self
::getDisplayValueCommon($value,
1147 * @param null $format
1148 * @param int $contactID
1149 * @param int $fieldID
1151 * @return array|mixed|null|string
1153 public static function getDisplayValueCommon(
1165 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1166 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1167 $html_type == 'Select' ||
1168 $html_type == 'CheckBox' ||
1169 $html_type == 'AdvMulti-Select' ||
1170 $html_type == 'Multi-Select'
1173 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1176 switch ($html_type) {
1178 if ($data_type == 'Boolean') {
1179 // Do not assume that if not yes means no.
1182 $display = ts('Yes');
1184 elseif ((string) $value === '0') {
1185 $display = ts('No');
1189 $display = CRM_Utils_Array
::value($value, $option);
1193 case 'Autocomplete-Select':
1194 if ($data_type == 'ContactReference' &&
1197 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1200 $display = CRM_Utils_Array
::value($value, $option);
1205 $display = CRM_Utils_Array
::value($value, $option);
1209 case 'AdvMulti-Select':
1210 case 'Multi-Select':
1211 if (is_array($value)) {
1212 $checkedData = $value;
1215 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1216 substr($value, 1, -1)
1218 if ($html_type == 'CheckBox') {
1220 foreach ($checkedData as $v) {
1223 $checkedData = $newData;
1229 foreach ($checkedData as $key => $val) {
1230 if ($html_type == 'CheckBox') {
1233 $v[] = CRM_Utils_Array
::value($key, $option);
1238 $v[] = CRM_Utils_Array
::value($val, $option);
1242 $display = implode(', ', $v);
1247 if (is_array($value)) {
1248 foreach ($value as $key => $val) {
1249 $display[$key] = CRM_Utils_Date
::customFormat($val);
1253 // remove time element display if time is not set
1254 if (empty($option['attributes']['time_format'])) {
1255 $value = substr($value, 0, 10);
1257 $display = CRM_Utils_Date
::customFormat($value);
1261 case 'Select State/Province':
1262 if (empty($value)) {
1266 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1270 case 'Multi-Select State/Province':
1271 if (is_array($value)) {
1272 $checkedData = $value;
1275 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1276 substr($value, 1, -1)
1280 $states = CRM_Core_PseudoConstant
::stateProvince();
1282 foreach ($checkedData as $stateID) {
1286 $display .= $states[$stateID];
1290 case 'Select Country':
1291 if (empty($value)) {
1295 $display = CRM_Core_PseudoConstant
::country($value);
1299 case 'Multi-Select Country':
1300 if (is_array($value)) {
1301 $checkedData = $value;
1304 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1305 substr($value, 1, -1)
1309 $countries = CRM_Core_PseudoConstant
::country();
1311 foreach ($checkedData as $countryID) {
1315 $display .= $countries[$countryID];
1320 // In the context of displaying a profile, show file/image
1321 if ($contactID && $value) {
1322 $url = self
::getFileURL($contactID, $fieldID, $value);
1324 $display = $url['file_url'];
1327 // In other contexts show a paperclip icon
1329 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1330 $display = $icons[$value];
1335 if (empty($value)) {
1339 $display = nl2br($value);
1344 if (empty($value)) {
1351 return $display ?
$display : $value;
1355 * Set default values for custom data used in profile.
1357 * @param int $customFieldId
1359 * @param string $elementName
1360 * Custom field name.
1361 * @param array $defaults
1362 * Associated array of fields.
1363 * @param int $contactId
1367 * @param mixed $value
1368 * If passed - dont fetch value from db,.
1369 * just format the given value
1372 public static function setProfileDefaults(
1380 //get the type of custom field
1381 $customField = new CRM_Core_BAO_CustomField();
1382 $customField->id
= $customFieldId;
1383 $customField->find(TRUE);
1386 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1387 $value = $customField->default_value
;
1391 if (!isset($value)) {
1392 $info = self
::getTableColumnGroup($customFieldId);
1393 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1394 $result = CRM_Core_DAO
::executeQuery($query);
1395 if ($result->fetch()) {
1396 $value = $result->value
;
1400 if ($customField->data_type
== 'Country') {
1402 $config = CRM_Core_Config
::singleton();
1403 if ($config->defaultContactCountry
) {
1404 $value = $config->defaultContactCountry();
1410 //set defaults if mode is registration
1411 if (!trim($value) &&
1413 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1415 $value = $customField->default_value
;
1418 if ($customField->data_type
== 'Money' && isset($value)) {
1419 $value = number_format($value, 2);
1421 switch ($customField->html_type
) {
1423 case 'AdvMulti-Select':
1424 case 'Multi-Select':
1425 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1426 $defaults[$elementName] = array();
1427 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1428 substr($value, 1, -1)
1430 foreach ($customOption as $val) {
1431 if (in_array($val['value'], $checkedValue)) {
1432 if ($customField->html_type
== 'CheckBox') {
1433 $defaults[$elementName][$val['value']] = 1;
1435 elseif ($customField->html_type
== 'Multi-Select' ||
1436 $customField->html_type
== 'AdvMulti-Select'
1438 $defaults[$elementName][$val['value']] = $val['value'];
1446 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1449 $customField->date_format
,
1450 $customField->time_format
1455 case 'Autocomplete-Select':
1456 if ($customField->data_type
== 'ContactReference') {
1457 if (is_numeric($value)) {
1458 $defaults[$elementName . '_id'] = $value;
1459 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1463 $defaults[$elementName] = $value;
1468 $defaults[$elementName] = $value;
1473 * @param int $contactID
1475 * @param int $fileID
1476 * @param bool $absolute
1481 * @param int $contactID
1483 * @param int $fileID
1484 * @param bool $absolute
1488 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1491 $params = array('id' => $cfID);
1492 $defaults = array();
1493 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1494 $columnName = $defaults['column_name'];
1496 //table name of custom data
1497 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1498 $defaults['custom_group_id'],
1502 //query to fetch id from civicrm_file
1503 if ($multiRecordWhereClause) {
1504 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1507 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1509 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1514 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1519 $result['file_id'] = $fileID;
1521 if ($fileType == 'image/jpeg' ||
1522 $fileType == 'image/pjpeg' ||
1523 $fileType == 'image/gif' ||
1524 $fileType == 'image/x-png' ||
1525 $fileType == 'image/png'
1527 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1532 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1533 list($imageWidth, $imageHeight) = getimagesize($path);
1534 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1535 $url = CRM_Utils_System
::url('civicrm/file',
1536 "reset=1&id=$fileID&eid=$contactID",
1537 $absolute, NULL, TRUE, TRUE
1539 $result['file_url'] = "
1540 <a href=\"$url\" class='crm-image-popup'>
1541 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1543 // for non image files
1546 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1550 $url = CRM_Utils_System
::url('civicrm/file',
1551 "reset=1&id=$fileID&eid=$contactID",
1552 $absolute, NULL, TRUE, TRUE
1554 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1562 * Format custom fields before inserting.
1564 * @param int $customFieldId
1566 * @param array $customFormatted
1569 * Value of custom field.
1570 * @param string $customFieldExtend
1571 * Custom field extends.
1572 * @param int $customValueId
1573 * Custom option value id.
1574 * @param int $entityId
1575 * Entity id (contribution, membership...).
1576 * @param bool $inline
1577 * Consider inline custom groups only.
1578 * @param bool $checkPermission
1579 * If false, do not include permissioning clause.
1580 * @param bool $includeViewOnly
1581 * If true, fields marked 'View Only' are included. Required for APIv3.
1583 * @return array|NULL
1584 * formatted custom field array
1586 public static function formatCustomField(
1587 $customFieldId, &$customFormatted, $value,
1588 $customFieldExtend, $customValueId = NULL,
1591 $checkPermission = TRUE,
1592 $includeViewOnly = FALSE
1594 //get the custom fields for the entity
1595 //subtype and basic type
1596 $customDataSubType = NULL;
1597 if (is_array($customFieldExtend)) {
1598 // This is the case when getFieldsForImport() requires fields
1599 // of subtype and its parent.CRM-5143
1600 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1601 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1602 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1603 $customFieldExtend = array_unique(array_values(CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType)));
1607 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1617 if (!array_key_exists($customFieldId, $customFields)) {
1621 // return if field is a 'code' field
1622 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1626 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1628 if (!$customValueId &&
1629 // we always create new entites for is_multiple unless specified
1630 !$customFields[$customFieldId]['is_multiple'] &&
1636 WHERE entity_id={$entityId}";
1638 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1641 //fix checkbox, now check box always submits values
1642 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1644 // Note that only during merge this is not an array, and you can directly use value
1645 if (is_array($value)) {
1646 $selectedValues = array();
1647 foreach ($value as $selId => $val) {
1649 $selectedValues[] = $selId;
1652 if (!empty($selectedValues)) {
1653 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1655 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1664 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1665 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1668 // Note that only during merge this is not an array,
1669 // and you can directly use value, CRM-4385
1670 if (is_array($value)) {
1671 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1672 array_values($value)
1673 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1681 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1682 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1683 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1685 $customFields[$customFieldId]['data_type'] == 'String' &&
1686 !empty($customFields[$customFieldId]['text_length']) &&
1689 // lets make sure that value is less than the length, else we'll
1690 // be losing some data, CRM-7481
1691 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1692 // need to do a few things here
1694 // 1. lets find a new length
1695 $newLength = $customFields[$customFieldId]['text_length'];
1696 $minLength = strlen($value);
1697 while ($newLength < $minLength) {
1698 $newLength = $newLength * 2;
1701 // set the custom field meta data to have a length larger than value
1702 // alter the custom value table column to match this length
1703 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1708 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1709 if (!CRM_Utils_System
::isNull($value)) {
1710 $format = $customFields[$customFieldId]['date_format'];
1711 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1716 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1717 $customFields[$customFieldId]['data_type'] == 'Money'
1723 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1724 $value = CRM_Utils_Rule
::cleanMoney($value);
1728 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1729 $customFields[$customFieldId]['data_type'] == 'Country'
1739 if ($customFields[$customFieldId]['data_type'] == 'File') {
1740 if (empty($value)) {
1744 $config = CRM_Core_Config
::singleton();
1746 $fName = $value['name'];
1747 $mimeType = $value['type'];
1749 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1751 // rename this file to go into the secure directory
1752 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1753 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1756 if ($customValueId) {
1761 $params = array(1 => array($customValueId, 'Integer'));
1762 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1765 $fileDAO = new CRM_Core_DAO_File();
1768 $fileDAO->id
= $fileId;
1771 $fileDAO->uri
= $filename;
1772 $fileDAO->mime_type
= $mimeType;
1773 $fileDAO->upload_date
= date('Ymdhis');
1775 $fileId = $fileDAO->id
;
1779 if (!is_array($customFormatted)) {
1780 $customFormatted = array();
1783 if (!array_key_exists($customFieldId, $customFormatted)) {
1784 $customFormatted[$customFieldId] = array();
1788 if ($customValueId) {
1789 $index = $customValueId;
1792 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1793 $customFormatted[$customFieldId][$index] = array();
1795 $customFormatted[$customFieldId][$index] = array(
1796 'id' => $customValueId > 0 ?
$customValueId : NULL,
1798 'type' => $customFields[$customFieldId]['data_type'],
1799 'custom_field_id' => $customFieldId,
1800 'custom_group_id' => $groupID,
1801 'table_name' => $tableName,
1802 'column_name' => $columnName,
1803 'file_id' => $fileId,
1804 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1807 //we need to sort so that custom fields are created in the order of entry
1808 krsort($customFormatted[$customFieldId]);
1809 return $customFormatted;
1813 * @param array $params
1817 public static function &defaultCustomTableSchema(&$params) {
1818 // add the id and extends_id
1820 'name' => $params['name'],
1821 'is_multiple' => $params['is_multiple'],
1822 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1826 'type' => 'int unsigned',
1829 'attributes' => 'AUTO_INCREMENT',
1830 'comment' => 'Default MySQL primary key',
1833 'name' => 'entity_id',
1834 'type' => 'int unsigned',
1836 'comment' => 'Table that this extends',
1837 'fk_table_name' => $params['extends_name'],
1838 'fk_field_name' => 'id',
1839 'fk_attributes' => 'ON DELETE CASCADE',
1844 if (!$params['is_multiple']) {
1845 $table['indexes'] = array(
1848 'field_name_1' => 'entity_id',
1858 * @param bool $indexExist
1859 * @param bool $triggerRebuild
1861 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1862 $tableName = CRM_Core_DAO
::getFieldValue(
1863 'CRM_Core_DAO_CustomGroup',
1864 $field->custom_group_id
,
1869 'table_name' => $tableName,
1870 'operation' => $operation,
1871 'name' => $field->column_name
,
1872 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1876 'required' => $field->is_required
,
1877 'searchable' => $field->is_searchable
,
1880 if ($operation == 'delete') {
1881 $fkName = "{$tableName}_{$field->column_name}";
1882 if (strlen($fkName) >= 48) {
1883 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1885 $params['fkName'] = $fkName;
1887 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1888 $params['fk_table_name'] = 'civicrm_country';
1889 $params['fk_field_name'] = 'id';
1890 $params['fk_attributes'] = 'ON DELETE SET NULL';
1892 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1893 $params['type'] = 'varchar(255)';
1895 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1896 $params['fk_table_name'] = 'civicrm_state_province';
1897 $params['fk_field_name'] = 'id';
1898 $params['fk_attributes'] = 'ON DELETE SET NULL';
1900 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1901 $params['type'] = 'varchar(255)';
1903 elseif ($field->data_type
== 'File') {
1904 $params['fk_table_name'] = 'civicrm_file';
1905 $params['fk_field_name'] = 'id';
1906 $params['fk_attributes'] = 'ON DELETE SET NULL';
1908 elseif ($field->data_type
== 'ContactReference') {
1909 $params['fk_table_name'] = 'civicrm_contact';
1910 $params['fk_field_name'] = 'id';
1911 $params['fk_attributes'] = 'ON DELETE SET NULL';
1913 if (isset($field->default_value
)) {
1914 $params['default'] = "'{$field->default_value}'";
1917 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1921 * Determine whether it would be safe to move a field.
1923 * @param int $fieldID
1924 * FK to civicrm_custom_field.
1925 * @param int $newGroupID
1926 * FK to civicrm_custom_group.
1929 * array(string) or TRUE
1931 public static function _moveFieldValidate($fieldID, $newGroupID) {
1934 $field = new CRM_Core_DAO_CustomField();
1935 $field->id
= $fieldID;
1936 if (!$field->find(TRUE)) {
1937 $errors['fieldID'] = 'Invalid ID for custom field';
1941 $oldGroup = new CRM_Core_DAO_CustomGroup();
1942 $oldGroup->id
= $field->custom_group_id
;
1943 if (!$oldGroup->find(TRUE)) {
1944 $errors['fieldID'] = 'Invalid ID for old custom group';
1948 $newGroup = new CRM_Core_DAO_CustomGroup();
1949 $newGroup->id
= $newGroupID;
1950 if (!$newGroup->find(TRUE)) {
1951 $errors['newGroupID'] = 'Invalid ID for new custom group';
1957 FROM civicrm_custom_field a
1958 INNER JOIN civicrm_custom_field b
1960 AND a.label = b.label
1961 AND b.custom_group_id = %2
1964 1 => array($field->id
, 'Integer'),
1965 2 => array($newGroup->id
, 'Integer'),
1967 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1969 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1972 $tableName = $oldGroup->table_name
;
1973 $columnName = $field->column_name
;
1978 WHERE $columnName is not null
1980 $count = CRM_Core_DAO
::singleValueQuery($query,
1981 CRM_Core_DAO
::$_nullArray
1986 FROM civicrm_custom_group
1987 WHERE id IN ( %1, %2 )
1990 1 => array($oldGroup->id
, 'Integer'),
1991 2 => array($newGroup->id
, 'Integer'),
1994 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1996 while ($dao->fetch()) {
1997 $extends[] = $dao->extends;
1999 if ($extends[0] != $extends[1]) {
2000 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
2004 return empty($errors) ?
TRUE : $errors;
2008 * Move a custom data field from one group (table) to another
2010 * @param int $fieldID
2011 * FK to civicrm_custom_field.
2012 * @param int $newGroupID
2013 * FK to civicrm_custom_group.
2017 public static function moveField($fieldID, $newGroupID) {
2018 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
2019 if (TRUE !== $validation) {
2020 CRM_Core_Error
::fatal(implode(' ', $validation));
2022 $field = new CRM_Core_DAO_CustomField();
2023 $field->id
= $fieldID;
2026 $newGroup = new CRM_Core_DAO_CustomGroup();
2027 $newGroup->id
= $newGroupID;
2028 $newGroup->find(TRUE);
2030 $oldGroup = new CRM_Core_DAO_CustomGroup();
2031 $oldGroup->id
= $field->custom_group_id
;
2032 $oldGroup->find(TRUE);
2035 $add->custom_group_id
= $newGroup->id
;
2036 self
::createField($add, 'add');
2038 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2039 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2040 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2042 CRM_Core_DAO
::executeQuery($sql);
2045 $del->custom_group_id
= $oldGroup->id
;
2046 self
::createField($del, 'delete');
2050 CRM_Utils_System
::flushCache();
2054 * Get the database table name and column name for a custom field.
2056 * @param int $fieldID
2057 * The fieldID of the custom field.
2058 * @param bool $force
2059 * Force the sql to be run again (primarily used for tests).
2062 * fatal is fieldID does not exists, else array of tableName, columnName
2064 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2065 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2066 $cache = CRM_Utils_Cache
::singleton();
2067 $fieldValues = $cache->get($cacheKey);
2068 if (empty($fieldValues) ||
$force) {
2070 SELECT cg.table_name, cf.column_name, cg.id
2071 FROM civicrm_custom_group cg,
2072 civicrm_custom_field cf
2073 WHERE cf.custom_group_id = cg.id
2075 $params = array(1 => array($fieldID, 'Integer'));
2076 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2078 if (!$dao->fetch()) {
2079 CRM_Core_Error
::fatal();
2082 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2083 $cache->set($cacheKey, $fieldValues);
2085 return $fieldValues;
2089 * Get custom option groups.
2091 * @param array $includeFieldIds
2092 * Ids of custom fields for which.
2093 * option groups must be included.
2095 * Currently this is required in the cases where option groups are to be included
2096 * for inactive fields : CRM-5369
2101 public static function &customOptionGroup($includeFieldIds = NULL) {
2102 static $customOptionGroup = NULL;
2104 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2105 if ($cacheKey == 'force') {
2106 $customOptionGroup[$cacheKey] = NULL;
2109 if (empty($customOptionGroup[$cacheKey])) {
2110 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2112 //support for single as well as array format.
2113 if (!empty($includeFieldIds)) {
2114 if (is_array($includeFieldIds)) {
2115 $includeFieldIds = implode(',', $includeFieldIds);
2117 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2121 SELECT g.id, g.title
2122 FROM civicrm_option_group g
2123 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2124 WHERE {$whereClause}";
2126 $dao = CRM_Core_DAO
::executeQuery($query);
2127 while ($dao->fetch()) {
2128 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2132 return $customOptionGroup[$cacheKey];
2136 * Fix orphan groups.
2138 * @param int $customFieldId
2140 * @param int $optionGroupId
2145 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2146 // check if option group belongs to any custom Field else delete
2147 // get the current option group
2148 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2152 // get the updated option group
2153 // if both are same return
2154 if ($currentOptionGroupId == $optionGroupId) {
2158 // check if option group is related to any other field
2159 self
::checkOptionGroup($currentOptionGroupId);
2163 * Check if option group is related to more than one
2166 * @param int $optionGroupId
2171 public static function checkOptionGroup($optionGroupId) {
2174 FROM civicrm_custom_field
2175 WHERE option_group_id = {$optionGroupId}";
2177 $count = CRM_Core_DAO
::singleValueQuery($query);
2180 //delete the option group
2181 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2186 * @param int $optionGroupId
2189 * @return null|string
2191 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2193 SELECT default_value, html_type
2194 FROM civicrm_custom_field
2195 WHERE option_group_id = {$optionGroupId}
2196 AND default_value IS NOT NULL
2197 ORDER BY html_type";
2199 $dao = CRM_Core_DAO
::executeQuery($query);
2200 $defaultValue = NULL;
2201 $defaultHTMLType = NULL;
2202 while ($dao->fetch()) {
2203 if ($dao->html_type
== $htmlType) {
2204 return $dao->default_value
;
2206 if ($defaultValue == NULL) {
2207 $defaultValue = $dao->default_value
;
2208 $defaultHTMLType = $dao->html_type
;
2212 // some conversions are needed if either the old or new has a html type which has potential
2213 // multiple default values.
2214 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2215 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2217 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2219 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2220 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2222 $defaultValue = substr($defaultValue, 1, -1);
2223 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2224 substr($defaultValue, 1, -1)
2226 $defaultValue = $values[0];
2229 return $defaultValue;
2233 * @param array $params
2234 * @param $customFields
2235 * @param int $entityID
2236 * @param $customFieldExtends
2237 * @param bool $inline
2241 public static function postProcess(
2245 $customFieldExtends,
2248 $customData = array();
2250 foreach ($params as $key => $value) {
2251 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2253 // for autocomplete transfer hidden value instead of label
2254 if ($params[$key] && isset($params[$key . '_id'])) {
2255 $value = $params[$key . '_id'];
2258 // we need to append time with date
2259 if ($params[$key] && isset($params[$key . '_time'])) {
2260 $value .= ' ' . $params[$key . '_time'];
2263 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2266 $customFieldExtends,
2267 $customFieldInfo[1],
2282 public static function buildOption($field, &$options) {
2283 // Fixme - adding anything but options to the $options array is a bad idea
2284 // What if an option had the key 'attributes'?
2285 $options['attributes'] = array(
2286 'label' => $field['label'],
2287 'data_type' => $field['data_type'],
2288 'html_type' => $field['html_type'],
2291 $optionGroupID = NULL;
2292 if (($field['html_type'] == 'CheckBox' ||
2293 $field['html_type'] == 'Radio' ||
2294 $field['html_type'] == 'Select' ||
2295 $field['html_type'] == 'AdvMulti-Select' ||
2296 $field['html_type'] == 'Multi-Select' ||
2297 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2300 if ($field['option_group_id']) {
2301 $optionGroupID = $field['option_group_id'];
2303 elseif ($field['data_type'] != 'Boolean') {
2304 CRM_Core_Error
::fatal();
2308 // build the cache for custom values with options (label => value)
2309 if ($optionGroupID != NULL) {
2312 FROM civicrm_option_value
2313 WHERE option_group_id = $optionGroupID
2316 $dao = CRM_Core_DAO
::executeQuery($query);
2317 while ($dao->fetch()) {
2318 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2319 $num = round($dao->value
, 2);
2320 $options["$num"] = $dao->label
;
2323 $options[$dao->value
] = $dao->label
;
2327 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2332 * @param $fieldLabel
2333 * @param null $groupTitle
2337 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2338 $params = array(1 => array($fieldLabel, 'String'));
2340 $params[2] = array($groupTitle, 'String');
2343 FROM civicrm_custom_field f
2344 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2345 WHERE ( f.label = %1 OR f.name = %1 )
2346 AND ( g.title = %2 OR g.name = %2 )
2352 FROM civicrm_custom_field f
2353 WHERE ( f.label = %1 OR f.name = %1 )
2357 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2358 if ($dao->fetch() &&
2369 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2375 public static function getNameFromID($ids) {
2376 if (is_array($ids)) {
2377 $ids = implode(',', $ids);
2380 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2381 FROM civicrm_custom_field f
2382 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2383 WHERE f.id IN ($ids)";
2385 $dao = CRM_Core_DAO
::executeQuery($sql);
2387 while ($dao->fetch()) {
2388 $result[$dao->id
] = array(
2389 'field_name' => $dao->field_name
,
2390 'field_label' => $dao->field_label
,
2391 'group_name' => $dao->group_name
,
2392 'group_title' => $dao->group_title
,
2399 * Validate custom data.
2401 * @param array $params
2402 * Custom data submitted.
2403 * ie array( 'custom_1' => 'validate me' );
2406 * validation errors.
2408 public static function validateCustomData($params) {
2410 if (!is_array($params) ||
empty($params)) {
2414 //pick up profile fields.
2415 $profileFields = array();
2416 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2418 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2420 CRM_Core_Action
::VIEW
2424 //lets start w/ params.
2425 foreach ($params as $key => $value) {
2426 $customFieldID = self
::getKeyID($key);
2427 if (!$customFieldID) {
2431 //load the structural info for given field.
2432 $field = new CRM_Core_DAO_CustomField();
2433 $field->id
= $customFieldID;
2434 if (!$field->find(TRUE)) {
2437 $dataType = $field->data_type
;
2439 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2440 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2441 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2443 $fieldTitle = $field->label
;
2446 //no need to validate.
2447 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2451 //lets validate first for required field.
2452 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2453 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2457 //now time to take care of custom field form rules.
2458 $ruleName = $errorMsg = NULL;
2459 switch ($dataType) {
2461 $ruleName = 'integer';
2462 $errorMsg = ts('%1 must be an integer (whole number).',
2463 array(1 => $fieldTitle)
2468 $ruleName = 'money';
2469 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2470 array(1 => $fieldTitle)
2475 $ruleName = 'numeric';
2476 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2477 array(1 => $fieldTitle)
2482 $ruleName = 'wikiURL';
2483 $errorMsg = ts('%1 must be valid Website.',
2484 array(1 => $fieldTitle)
2489 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2491 $funName = "CRM_Utils_Rule::{$ruleName}";
2492 if (is_callable($funName)) {
2493 $valid = call_user_func($funName, $value);
2496 $errors[$key] = $errorMsg;
2505 * @param int $customId
2509 public static function isMultiRecordField($customId) {
2510 $isMultipleWithGid = FALSE;
2511 if (!is_numeric($customId)) {
2512 $customId = self
::getKeyID($customId);
2514 if (is_numeric($customId)) {
2515 $sql = "SELECT cg.id cgId
2516 FROM civicrm_custom_group cg
2517 INNER JOIN civicrm_custom_field cf
2518 ON cg.id = cf.custom_group_id
2519 WHERE cf.id = %1 AND cg.is_multiple = 1";
2520 $params[1] = array($customId, 'Integer');
2521 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2522 if ($dao->fetch()) {
2524 $isMultipleWithGid = $dao->cgId
;
2529 return $isMultipleWithGid;
2533 * Does this field store a serialized string?
2534 * @param CRM_Core_DAO_CustomField|array $field
2537 public static function isSerialized($field) {
2538 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2539 $field = (array) $field;
2540 // 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.
2541 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2545 * @param array $field
2546 * @param string|null $optionGroupName
2548 private static function getOptionsForField(&$field, $optionGroupName) {
2549 if ($optionGroupName) {
2550 $field['pseudoconstant'] = array(
2551 'optionGroupName' => $optionGroupName,
2552 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2555 elseif ($field['data_type'] == 'Boolean') {
2556 $field['pseudoconstant'] = array(
2557 'callback' => 'CRM_Core_SelectValues::boolean',
2560 elseif ($field['data_type'] == 'Country') {
2561 $field['pseudoconstant'] = array(
2562 'table' => 'civicrm_country',
2563 'keyColumn' => 'id',
2564 'labelColumn' => 'name',
2565 'nameColumn' => 'iso_code',
2568 elseif ($field['data_type'] == 'StateProvince') {
2569 $field['pseudoconstant'] = array(
2570 'table' => 'civicrm_state_province',
2571 'keyColumn' => 'id',
2572 'labelColumn' => 'name',