3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Business objects for managing custom data fields.
40 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
43 * Array for valid combinations of data_type & descriptions
48 public static $_dataType = NULL;
51 * Array for valid combinations of data_type & html_type
56 public static $_dataToHtml = NULL;
59 * Array to hold (formatted) fields for import
64 public static $_importFields = NULL;
67 * Build and retrieve the list of data types and descriptions
71 * @return array Data type => Description
74 public static function &dataType() {
75 if (!(self
::$_dataType)) {
76 self
::$_dataType = array(
77 'String' => ts('Alphanumeric'),
78 'Int' => ts('Integer'),
79 'Float' => ts('Number'),
80 'Money' => ts('Money'),
83 'Boolean' => ts('Yes or No'),
84 'StateProvince' => ts('State/Province'),
85 'Country' => ts('Country'),
88 'ContactReference' => ts('Contact Reference'),
91 return self
::$_dataType;
97 public static function dataToHtml() {
98 if (!self
::$_dataToHtml) {
99 self
::$_dataToHtml = array(
102 'Select' => 'Select',
104 'CheckBox' => 'CheckBox',
105 'Multi-Select' => 'Multi-Select',
106 'AdvMulti-Select' => 'AdvMulti-Select',
107 'Autocomplete-Select' => 'Autocomplete-Select',
109 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
110 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
111 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
112 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
113 array('Date' => 'Select Date'),
114 array('Radio' => 'Radio'),
115 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
116 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
117 array('File' => 'File'),
118 array('Link' => 'Link'),
119 array('ContactReference' => 'Autocomplete-Select'),
122 return self
::$_dataToHtml;
126 * Takes an associative array and creates a custom field object
128 * This function is invoked from within the web form layer and also from the api layer
130 * @param array $params
131 * (reference) an assoc array of name/value pairs.
133 * @return CRM_Core_DAO_CustomField object
136 public static function create(&$params) {
137 $origParams = array_merge(array(), $params);
139 if (!isset($params['id'])) {
140 if (!isset($params['column_name'])) {
141 // if add mode & column_name not present, calculate it.
142 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
144 if (!isset($params['name'])) {
145 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
149 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
154 $columnName = $params['column_name'];
157 //as during create if field is_searchable we had created index.
158 if (!empty($params['id'])) {
159 $indexExist = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $params['id'], 'is_searchable');
162 switch (CRM_Utils_Array
::value('html_type', $params)) {
164 if (empty($params['date_format'])) {
165 $config = CRM_Core_Config
::singleton();
166 $params['date_format'] = $config->dateInputFormat
;
171 case 'AdvMulti-Select':
173 if (isset($params['default_checkbox_option'])) {
174 $tempArray = array_keys($params['default_checkbox_option']);
175 $defaultArray = array();
176 foreach ($tempArray as $k => $v) {
177 if ($params['option_value'][$v]) {
178 $defaultArray[] = $params['option_value'][$v];
182 if (!empty($defaultArray)) {
183 // also add the seperator before and after the value per new conventio (CRM-1604)
184 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
188 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
190 $params['default_value'] = $params['option_value'][$params['default_option']];
196 $transaction = new CRM_Core_Transaction();
197 // create any option group & values if required
198 if ($params['html_type'] != 'Text' &&
199 in_array($params['data_type'], array(
207 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
208 $params['custom_group_id'],
212 if ($params['option_type'] == 1 && empty($params['option_group_id'])) {
213 // first create an option group for this custom group
214 $optionGroup = new CRM_Core_DAO_OptionGroup();
215 $optionGroup->name
= "{$columnName}_" . date('YmdHis');
216 $optionGroup->title
= $params['label'];
217 $optionGroup->is_active
= 1;
218 $optionGroup->save();
219 $params['option_group_id'] = $optionGroup->id
;
220 if (!empty($params['option_value']) && is_array($params['option_value'])) {
221 foreach ($params['option_value'] as $k => $v) {
222 if (strlen(trim($v))) {
223 $optionValue = new CRM_Core_DAO_OptionValue();
224 $optionValue->option_group_id
= $optionGroup->id
;
225 $optionValue->label
= $params['option_label'][$k];
226 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$k]);
227 switch ($params['data_type']) {
229 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($v);
233 $optionValue->value
= intval($v);
237 $optionValue->value
= floatval($v);
241 $optionValue->value
= trim($v);
244 $optionValue->weight
= $params['option_weight'][$k];
245 $optionValue->is_active
= CRM_Utils_Array
::value($k, $params['option_status'], FALSE);
246 $optionValue->save();
253 // check for orphan option groups
254 if (!empty($params['option_group_id'])) {
255 if (!empty($params['id'])) {
256 self
::fixOptionGroups($params['id'], $params['option_group_id']);
259 // if we dont have a default value
260 // retrive it from one of the other custom fields which use this option group
261 if (empty($params['default_value'])) {
262 //don't insert only value separator as default value, CRM-4579
263 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
267 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
271 $params['default_value'] = $defaultValue;
276 // since we need to save option group id :)
277 if (!isset($params['attributes']) && strtolower($params['html_type']) == 'textarea') {
278 $params['attributes'] = 'rows=4, cols=60';
281 $customField = new CRM_Core_DAO_CustomField();
282 $customField->copyValues($params);
283 $customField->is_required
= CRM_Utils_Array
::value('is_required', $params, FALSE);
284 $customField->is_searchable
= CRM_Utils_Array
::value('is_searchable', $params, FALSE);
285 $customField->in_selector
= CRM_Utils_Array
::value('in_selector', $params, FALSE);
286 $customField->is_search_range
= CRM_Utils_Array
::value('is_search_range', $params, FALSE);
287 $customField->is_active
= CRM_Utils_Array
::value('is_active', $params, FALSE);
288 $customField->is_view
= CRM_Utils_Array
::value('is_view', $params, FALSE);
289 $customField->save();
291 // make sure all values are present in the object for further processing
292 $customField->find(TRUE);
294 $triggerRebuild = CRM_Utils_Array
::value('triggerRebuild', $params, TRUE);
295 //create/drop the index when we toggle the is_searchable flag
296 if (!empty($params['id'])) {
297 self
::createField($customField, 'modify', $indexExist, $triggerRebuild);
300 if (!isset($origParams['column_name'])) {
301 $columnName .= "_{$customField->id}";
302 $params['column_name'] = $columnName;
304 $customField->column_name
= $columnName;
305 $customField->save();
306 // make sure all values are present in the object
307 $customField->find(TRUE);
310 self
::createField($customField, 'add', $indexExist, $triggerRebuild);
313 // complete transaction
314 $transaction->commit();
316 CRM_Utils_System
::flushCache();
322 * Fetch object based on array of properties
324 * @param array $params
325 * (reference ) an assoc array of name/value pairs.
326 * @param array $defaults
327 * (reference ) an assoc array to hold the flattened values.
329 * @return CRM_Core_DAO_CustomField object
332 public static function retrieve(&$params, &$defaults) {
333 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
337 * Update the is_active flag in the db
340 * Id of the database record.
341 * @param bool $is_active
342 * Value we want to set the is_active field.
344 * @return Object DAO object on sucess, null otherwise
348 public static function setIsActive($id, $is_active) {
350 CRM_Utils_System
::flushCache();
352 //enable-disable CustomField
353 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
354 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
358 * Get the field title.
363 * @return string name
368 public static function getTitle($id) {
369 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
373 * Store and return an array of all active custom fields.
375 * @param string $customDataType
376 * Type of Custom Data; empty is a synonym for "all contact data types".
377 * @param bool $showAll
378 * If true returns all fields (includes disabled fields).
379 * @param bool $inline
380 * If true returns all inline fields (includes disabled fields).
381 * @param int $customDataSubType
382 * Custom Data sub type value.
383 * @param int $customDataSubName
384 * Custom Data sub name value.
385 * @param bool $onlyParent
386 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
387 * @param bool $onlySubType
388 * Return only custom data for subtype.
389 * @param bool $checkPermission
390 * If false, do not include permissioning clause.
392 * @return array $fields - an array of active custom fields.
396 public static function &getFields(
397 $customDataType = 'Individual',
400 $customDataSubType = NULL,
401 $customDataSubName = NULL,
403 $onlySubType = FALSE,
404 $checkPermission = TRUE
406 if (empty($customDataType)) {
407 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
409 if ($customDataType && !is_array($customDataType)) {
411 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
412 // This is the case when getFieldsForImport() requires fields
413 // limited strictly to a subtype.
414 $customDataSubType = $customDataType;
415 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
419 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
420 // this makes the method flexible to support retrieving fields
421 // for multiple extends value.
422 $customDataType = array($customDataType);
426 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
428 if (is_array($customDataType)) {
429 $cacheKey = implode('_', $customDataType);
432 $cacheKey = $customDataType;
435 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
436 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
437 $cacheKey .= $showAll ?
'_1' : '_0';
438 $cacheKey .= $inline ?
'_1_' : '_0_';
439 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
440 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
441 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
443 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
445 // also get the permission stuff here
446 if ($checkPermission) {
447 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
452 $permissionClause = '(1)';
455 // lets md5 permission clause and take first 8 characters
456 $cacheKey .= substr(md5($permissionClause), 0, 8);
458 if (strlen($cacheKey) > 40) {
459 $cacheKey = md5($cacheKey);
462 if (!self
::$_importFields ||
463 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
465 if (!self
::$_importFields) {
466 self
::$_importFields = array();
469 // check if we can retrieve from database cache
470 $fields = CRM_Core_BAO_Cache
::getItem('contact fields', "custom importableFields $cacheKey");
472 if ($fields === NULL) {
473 $cfTable = self
::getTableName();
476 if (is_array($customDataType)) {
478 foreach ($customDataType as $dataType) {
479 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
480 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
481 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
484 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
486 $value = $value ?
$value . ", {$val}" : $val;
490 $extends = "AND $cgTable.extends IN ( $value ) ";
494 if (!empty($customDataType) && empty($extends)) {
495 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
496 self
::$_importFields[$cacheKey] = array();
497 return self
::$_importFields[$cacheKey];
501 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
504 $query = "SELECT $cfTable.id, $cfTable.label,
508 $cfTable.default_value,
509 $cfTable.options_per_line, $cfTable.text_length,
510 $cfTable.custom_group_id,
511 $cfTable.is_required,
512 $cgTable.extends, $cfTable.is_search_range,
513 $cgTable.extends_entity_column_value,
514 $cgTable.extends_entity_column_id,
516 $cfTable.option_group_id,
517 $cfTable.date_format,
518 $cfTable.time_format,
522 ON $cfTable.custom_group_id = $cgTable.id
526 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
530 $query .= " AND $cgTable.style = 'Inline' ";
533 //get the custom fields for specific type in
534 //combination with fields those support any type.
535 if (!empty($customDataSubType)) {
536 $subtypeClause = array();
537 foreach ($customDataSubType as $subtype) {
538 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. $subtype . CRM_Core_DAO
::VALUE_SEPARATOR
;
539 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
542 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
544 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
547 if ($customDataSubName) {
548 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
551 // also get the permission stuff here
552 if ($checkPermission) {
553 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
558 $permissionClause = '(1)';
561 $query .= " $extends AND $permissionClause
562 ORDER BY $cgTable.weight, $cgTable.title,
563 $cfTable.weight, $cfTable.label";
565 $dao = CRM_Core_DAO
::executeQuery($query);
568 while (($dao->fetch()) != NULL) {
569 $fields[$dao->id
]['label'] = $dao->label
;
570 $fields[$dao->id
]['groupTitle'] = $dao->title
;
571 $fields[$dao->id
]['data_type'] = $dao->data_type
;
572 $fields[$dao->id
]['html_type'] = $dao->html_type
;
573 $fields[$dao->id
]['default_value'] = $dao->default_value
;
574 $fields[$dao->id
]['text_length'] = $dao->text_length
;
575 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
576 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
577 $fields[$dao->id
]['extends'] = $dao->extends;
578 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
579 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
580 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
581 $fields[$dao->id
]['is_view'] = $dao->is_view
;
582 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
583 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
584 $fields[$dao->id
]['date_format'] = $dao->date_format
;
585 $fields[$dao->id
]['time_format'] = $dao->time_format
;
586 $fields[$dao->id
]['is_required'] = $dao->is_required
;
589 CRM_Core_BAO_Cache
::setItem($fields,
591 "custom importableFields $cacheKey"
594 self
::$_importFields[$cacheKey] = $fields;
597 return self
::$_importFields[$cacheKey];
601 * Return the field ids and names (with groups) for import purpose.
603 * @param int|string $contactType Contact type
604 * @param bool $showAll
605 * If true returns all fields (includes disabled fields).
606 * @param bool $onlyParent
607 * Return fields ONLY related to basic types.
608 * @param bool $search
609 * When called from search and multiple records need to be returned.
610 * @param bool $checkPermission
611 * If false, do not include permissioning clause.
613 * @param bool $withMultiple
615 * @return array $fields -
619 public static function &getFieldsForImport(
620 $contactType = 'Individual',
624 $checkPermission = TRUE,
625 $withMultiple = FALSE
627 // Note: there are situations when we want getFieldsForImport() return fields related
628 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
629 $fields = &self
::getFields($contactType,
639 $importableFields = array();
640 foreach ($fields as $id => $values) {
641 // for now we should not allow multiple fields in profile / export etc, hence unsetting
643 (!empty($values['is_multiple']) && !$withMultiple)
648 /* generate the key for the fields array */
652 $regexp = preg_replace('/[.,;:!?]/', '', CRM_Utils_Array
::value(0, $values));
653 $importableFields[$key] = array(
655 'title' => CRM_Utils_Array
::value('label', $values),
656 'headerPattern' => '/' . preg_quote($regexp, '/') . '/',
658 'custom_field_id' => $id,
659 'options_per_line' => CRM_Utils_Array
::value('options_per_line', $values),
660 'text_length' => CRM_Utils_Array
::value('text_length', $values, 255),
661 'data_type' => CRM_Utils_Array
::value('data_type', $values),
662 'html_type' => CRM_Utils_Array
::value('html_type', $values),
663 'is_search_range' => CRM_Utils_Array
::value('is_search_range', $values),
666 // CRM-6681, pass date and time format when html_type = Select Date
667 if (CRM_Utils_Array
::value('html_type', $values) == 'Select Date') {
668 $importableFields[$key]['date_format'] = CRM_Utils_Array
::value('date_format', $values);
669 $importableFields[$key]['time_format'] = CRM_Utils_Array
::value('time_format', $values);
673 return $importableFields;
677 * Get the field id from an import key
683 * @return int|null The id (if exists)
686 public static function getKeyID($key, $all = FALSE) {
688 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
695 CRM_Utils_Array
::value(2, $match),
699 return $all ?
array(NULL, NULL) : NULL;
703 * Use the cache to get all values of a specific custom field
705 * @param int $fieldID
706 * The custom field ID.
708 * @return CRM_Core_DAO_CustomField $field the field object
712 public static function getFieldObject($fieldID) {
713 $field = new CRM_Core_DAO_CustomField();
715 // check if we can get the field values from the system cache
716 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
717 $cache = CRM_Utils_Cache
::singleton();
718 $fieldValues = $cache->get($cacheKey);
719 if (empty($fieldValues)) {
720 $field->id
= $fieldID;
721 if (!$field->find(TRUE)) {
722 CRM_Core_Error
::fatal();
725 $fieldValues = array();
726 CRM_Core_DAO
::storeValues($field, $fieldValues);
728 $cache->set($cacheKey, $fieldValues);
731 $field->copyValues($fieldValues);
738 * This function for building custom fields
740 * @param CRM_Core_Form $qf
741 * Form object (reference).
742 * @param string $elementName
743 * Name of the custom field.
744 * @param int $fieldId
745 * @param bool $inactiveNeeded
747 * @param bool $useRequired
748 * True if required else false.
749 * @param bool $search
750 * True if used for search else false.
751 * @param string $label
752 * Label for custom field.
756 public static function addQuickFormElement(
760 $inactiveNeeded = FALSE,
765 $field = self
::getFieldObject($fieldId);
766 $widget = $field->html_type
;
768 // Custom field HTML should indicate group+field name
769 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
770 $dataCrmCustomVal = $groupName . ':' . $field->name
;
771 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
772 $field->attributes
.= $dataCrmCustomAttr;
774 // Fixed for Issue CRM-2183
775 if ($widget == 'TextArea' && $search) {
779 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
781 // FIXME: Why are select state/country separate widget types?
782 $isSelect = (in_array($widget, array(
785 'Select State/Province',
786 'Multi-Select State/Province',
788 'Multi-Select Country',
795 $options = CRM_Utils_Array
::value('values', civicrm_api3('contact', 'getoptions', array(
796 'field' => "custom_$fieldId",
797 'context' => $search ?
'search' : 'create'
800 // Consolidate widget types to simplify the below switch statement
801 if ($search ||
($widget !== 'AdvMulti-Select' && strpos($widget, 'Select') !== FALSE)) {
804 $selectAttributes = array(
805 'data-crm-custom' => $dataCrmCustomVal,
806 'class' => 'crm-select2',
808 // Search field is always multi-select
809 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
810 $selectAttributes['class'] .= ' huge';
811 $selectAttributes['multiple'] = 'multiple';
812 $selectAttributes['placeholder'] = $placeholder;
814 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
815 if ($field->option_group_id
&& !$search && $widget == 'Select' && CRM_Core_Permission
::check('administer CiviCRM')) {
816 $selectAttributes +
= array(
817 'data-api-entity' => 'contact',
818 // FIXME: This works because the getoptions api isn't picky about custom fields, but it's WRONG
819 'data-api-field' => 'custom_' . $field->id
,
820 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
825 if (!isset($label)) {
826 $label = $field->label
;
830 * at some point in time we might want to split the below into small functions
836 if ($field->is_search_range
&& $search) {
837 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
838 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
841 $element = &$qf->add('text', $elementName, $label,
843 $useRequired && !$search
849 $attributes = $dataCrmCustomAttr;
850 if ($field->note_rows
) {
851 $attributes .= 'rows=' . $field->note_rows
;
854 $attributes .= 'rows=4';
856 if ($field->note_columns
) {
857 $attributes .= ' cols=' . $field->note_columns
;
860 $attributes .= ' cols=60';
862 if ($field->text_length
) {
863 $attributes .= ' maxlength=' . $field->text_length
;
865 $element = &$qf->add('textarea',
869 $useRequired && !$search
874 if ($field->is_search_range
&& $search) {
875 $qf->addDate($elementName . '_from', $label . ' - ' . ts('From'), FALSE,
877 'format' => $field->date_format
,
878 'timeFormat' => $field->time_format
,
879 'startOffset' => $field->start_date_years
,
880 'endOffset' => $field->end_date_years
,
881 'data-crm-custom' => $dataCrmCustomVal,
885 $qf->addDate($elementName . '_to', ts('To'), FALSE,
887 'format' => $field->date_format
,
888 'timeFormat' => $field->time_format
,
889 'startOffset' => $field->start_date_years
,
890 'endOffset' => $field->end_date_years
,
891 'data-crm-custom' => $dataCrmCustomVal,
896 $required = $useRequired && !$search;
898 $qf->addDate($elementName, $label, $required, array(
899 'format' => $field->date_format
,
900 'timeFormat' => $field->time_format
,
901 'startOffset' => $field->start_date_years
,
902 'endOffset' => $field->end_date_years
,
903 'data-crm-custom' => $dataCrmCustomVal,
910 foreach ($options as $v => $l) {
911 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $field->attributes
);
913 $group = $qf->addGroup($choice, $elementName, $label);
914 if ($useRequired && !$search) {
915 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
918 $group->setAttribute('allowClear', TRUE);
922 // For all select elements
924 if (empty($selectAttributes['multiple'])) {
925 $options = array('' => $placeholder) +
$options;
927 $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
929 // Add and/or option for fields that store multiple values
930 if ($search && self
::isSerialized($field)) {
933 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
934 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
936 $qf->addGroup($operators, $elementName . '_operator');
937 $qf->setDefaults(array($elementName . '_operator' => 'or'));
941 case 'AdvMulti-Select':
942 $include =& $qf->addElement(
949 'class' => 'advmultiselect',
950 'data-crm-custom' => $dataCrmCustomVal,
954 $include->setButtonAttributes('add', array('value' => ts('Add >>')));
955 $include->setButtonAttributes('remove', array('value' => ts('<< Remove')));
957 if ($useRequired && !$search) {
958 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
964 foreach ($options as $v => $l) {
965 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, array('data-crm-custom' => $dataCrmCustomVal));
967 $qf->addGroup($check, $elementName, $label);
968 if ($useRequired && !$search) {
969 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
974 // we should not build upload file in search mode
979 strtolower($field->html_type
),
983 $useRequired && !$search
985 $qf->addUploadElement($elementName);
988 case 'RichTextEditor':
990 'rows' => $field->note_rows
,
991 'cols' => $field->note_columns
,
992 'data-crm-custom' => $dataCrmCustomVal
994 if ($field->text_length
) {
995 $attributes['maxlength'] = $field->text_length
;
997 $qf->addWysiwyg($elementName, $label, $attributes, $search);
1000 case 'Autocomplete-Select':
1001 static $customUrls = array();
1002 // Fixme: why is this a string in the first place??
1003 $attributes = array();
1004 if ($field->attributes
) {
1005 foreach (explode(' ', $field->attributes
) as $at) {
1006 if (strpos($at, '=')) {
1007 list($k, $v) = explode('=', $at);
1008 $attributes[$k] = trim($v, ' "');
1012 if ($field->data_type
== 'ContactReference') {
1013 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
1014 $attributes['data-api-entity'] = 'contact';
1015 $qf->add('text', $elementName, $label, $attributes,
1016 $useRequired && !$search
1019 $urlParams = "context=customfield&id={$field->id}";
1021 $customUrls[$elementName] = CRM_Utils_System
::url('civicrm/ajax/contactref',
1028 // FIXME: This won't work with customFieldOptions hook
1029 $attributes +
= array(
1030 'entity' => 'option_value',
1031 'placeholder' => $placeholder,
1032 'multiple' => $search,
1034 'params' => array('option_group_id' => $field->option_group_id
),
1037 $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
1040 $qf->assign('customUrls', $customUrls);
1044 switch ($field->data_type
) {
1046 // integers will have numeric rule applied to them.
1047 if ($field->is_search_range
&& $search) {
1048 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
1049 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
1051 elseif ($widget == 'Text') {
1052 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
1057 if ($field->is_search_range
&& $search) {
1058 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1059 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1061 elseif ($widget == 'Text') {
1062 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1067 if ($field->is_search_range
&& $search) {
1068 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1069 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1071 elseif ($widget == 'Text') {
1072 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1077 $element->setAttribute('onfocus', "if (!this.value) {this.value='http://';}");
1078 $element->setAttribute('onblur', "if (this.value == 'http://') {this.value='';}");
1079 $element->setAttribute('class', "url");
1080 $qf->addRule($elementName, ts('Enter a valid Website.'), 'wikiURL');
1083 if ($field->is_view
&& !$search) {
1084 $qf->freeze($elementName);
1089 * Delete the Custom Field.
1091 * @param object $field
1099 public static function deleteField($field) {
1100 CRM_Utils_System
::flushCache();
1102 // first delete the custom option group and values associated with this field
1103 if ($field->option_group_id
) {
1104 //check if option group is related to any other field, if
1105 //not delete the option group and related option values
1106 self
::checkOptionGroup($field->option_group_id
);
1109 // next drop the column from the custom value table
1110 self
::createField($field, 'delete');
1113 CRM_Core_BAO_UFField
::delUFField($field->id
);
1114 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1120 * Given a custom field value, its id and the set of options
1121 * find the display value for this field
1123 * @param mixed $value
1124 * The custom field value.
1126 * The custom field id.
1127 * @param int $options
1128 * The assoc array of option name/value pairs.
1130 * @param int $contactID
1131 * @param int $fieldID
1133 * @return string the display value
1137 public static function getDisplayValue($value, $id, &$options, $contactID = NULL, $fieldID = NULL) {
1138 $option = &$options[$id];
1139 $attributes = &$option['attributes'];
1140 $html_type = $attributes['html_type'];
1141 $data_type = $attributes['data_type'];
1142 $format = CRM_Utils_Array
::value('format', $attributes);
1144 return self
::getDisplayValueCommon($value,
1159 * @param null $format
1160 * @param int $contactID
1161 * @param int $fieldID
1163 * @return array|mixed|null|string
1165 static function getDisplayValueCommon(
1177 (($html_type == 'Radio' && $data_type != 'Boolean') ||
1178 ($html_type == 'Autocomplete-Select' && $data_type != 'ContactReference') ||
1179 $html_type == 'Select' ||
1180 $html_type == 'CheckBox' ||
1181 $html_type == 'AdvMulti-Select' ||
1182 $html_type == 'Multi-Select'
1185 CRM_Utils_Hook
::customFieldOptions($fieldID, $option);
1188 switch ($html_type) {
1190 if ($data_type == 'Boolean') {
1191 // Do not assume that if not yes means no.
1194 $display = ts('Yes');
1196 elseif ((string) $value === '0') {
1197 $display = ts('No');
1201 $display = CRM_Utils_Array
::value($value, $option);
1205 case 'Autocomplete-Select':
1206 if ($data_type == 'ContactReference' &&
1209 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1212 $display = CRM_Utils_Array
::value($value, $option);
1217 $display = CRM_Utils_Array
::value($value, $option);
1221 case 'AdvMulti-Select':
1222 case 'Multi-Select':
1223 if (is_array($value)) {
1224 $checkedData = $value;
1227 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1228 substr($value, 1, -1)
1230 if ($html_type == 'CheckBox') {
1232 foreach ($checkedData as $v) {
1235 $checkedData = $newData;
1241 foreach ($checkedData as $key => $val) {
1242 if ($html_type == 'CheckBox') {
1245 $v[] = CRM_Utils_Array
::value($key, $option);
1250 $v[] = CRM_Utils_Array
::value($val, $option);
1254 $display = implode(', ', $v);
1259 if (is_array($value)) {
1260 foreach ($value as $key => $val) {
1261 $display[$key] = CRM_Utils_Date
::customFormat($val);
1265 // remove time element display if time is not set
1266 if (empty($option['attributes']['time_format'])) {
1267 $value = substr($value, 0, 10);
1269 $display = CRM_Utils_Date
::customFormat($value);
1273 case 'Select State/Province':
1274 if (empty($value)) {
1278 $display = CRM_Core_PseudoConstant
::stateProvince($value);
1282 case 'Multi-Select State/Province':
1283 if (is_array($value)) {
1284 $checkedData = $value;
1287 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1288 substr($value, 1, -1)
1292 $states = CRM_Core_PseudoConstant
::stateProvince();
1294 foreach ($checkedData as $stateID) {
1298 $display .= $states[$stateID];
1302 case 'Select Country':
1303 if (empty($value)) {
1307 $display = CRM_Core_PseudoConstant
::country($value);
1311 case 'Multi-Select Country':
1312 if (is_array($value)) {
1313 $checkedData = $value;
1316 $checkedData = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1317 substr($value, 1, -1)
1321 $countries = CRM_Core_PseudoConstant
::country();
1323 foreach ($checkedData as $countryID) {
1327 $display .= $countries[$countryID];
1333 $url = self
::getFileURL($contactID, $fieldID, $value);
1335 $display = $url['file_url'];
1341 if (empty($value)) {
1345 $display = nl2br($value);
1350 if (empty($value)) {
1357 return $display ?
$display : $value;
1361 * Set default values for custom data used in profile
1363 * @param int $customFieldId
1365 * @param string $elementName
1366 * Custom field name.
1367 * @param array $defaults
1368 * Associated array of fields.
1369 * @param int $contactId
1373 * @param mixed $value
1374 * If passed - dont fetch value from db,.
1375 * just format the given value
1379 static function setProfileDefaults(
1387 //get the type of custom field
1388 $customField = new CRM_Core_BAO_CustomField();
1389 $customField->id
= $customFieldId;
1390 $customField->find(TRUE);
1393 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1394 $value = $customField->default_value
;
1398 if (!isset($value)) {
1399 $info = self
::getTableColumnGroup($customFieldId);
1400 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1401 $result = CRM_Core_DAO
::executeQuery($query);
1402 if ($result->fetch()) {
1403 $value = $result->value
;
1407 if ($customField->data_type
== 'Country') {
1409 $config = CRM_Core_Config
::singleton();
1410 if ($config->defaultContactCountry
) {
1411 $value = $config->defaultContactCountry();
1417 //set defaults if mode is registration
1418 if (!trim($value) &&
1420 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1422 $value = $customField->default_value
;
1425 if ($customField->data_type
== 'Money' && isset($value)) {
1426 $value = number_format($value, 2);
1428 switch ($customField->html_type
) {
1430 case 'AdvMulti-Select':
1431 case 'Multi-Select':
1432 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1433 $defaults[$elementName] = array();
1434 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1435 substr($value, 1, -1)
1437 foreach ($customOption as $val) {
1438 if (in_array($val['value'], $checkedValue)) {
1439 if ($customField->html_type
== 'CheckBox') {
1440 $defaults[$elementName][$val['value']] = 1;
1442 elseif ($customField->html_type
== 'Multi-Select' ||
1443 $customField->html_type
== 'AdvMulti-Select'
1445 $defaults[$elementName][$val['value']] = $val['value'];
1453 list($defaults[$elementName], $defaults[$elementName . '_time']) = CRM_Utils_Date
::setDateDefaults(
1456 $customField->date_format
,
1457 $customField->time_format
1462 case 'Autocomplete-Select':
1463 if ($customField->data_type
== 'ContactReference') {
1464 if (is_numeric($value)) {
1465 $defaults[$elementName . '_id'] = $value;
1466 $defaults[$elementName] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name');
1470 $defaults[$elementName] = $value;
1475 $defaults[$elementName] = $value;
1480 * @param int $contactID
1482 * @param int $fileID
1483 * @param bool $absolute
1488 * @param int $contactID
1490 * @param int $fileID
1491 * @param bool $absolute
1495 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1498 $params = array('id' => $cfID);
1499 $defaults = array();
1500 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1501 $columnName = $defaults['column_name'];
1503 //table name of custom data
1504 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1505 $defaults['custom_group_id'],
1509 //query to fetch id from civicrm_file
1510 if ($multiRecordWhereClause) {
1511 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1514 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1516 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1521 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1526 $result['file_id'] = $fileID;
1528 if ($fileType == 'image/jpeg' ||
1529 $fileType == 'image/pjpeg' ||
1530 $fileType == 'image/gif' ||
1531 $fileType == 'image/x-png' ||
1532 $fileType == 'image/png'
1534 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1539 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId, NULL, NULL);
1540 list($imageWidth, $imageHeight) = getimagesize($path);
1541 list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact
::getThumbSize($imageWidth, $imageHeight);
1542 $url = CRM_Utils_System
::url('civicrm/file',
1543 "reset=1&id=$fileID&eid=$contactID",
1544 $absolute, NULL, TRUE, TRUE
1546 $result['file_url'] = "
1547 <a href=\"$url\" class='crm-image-popup'>
1548 <img src=\"$url\" width=$imageThumbWidth height=$imageThumbHeight/>
1550 // for non image files
1553 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1557 $url = CRM_Utils_System
::url('civicrm/file',
1558 "reset=1&id=$fileID&eid=$contactID",
1559 $absolute, NULL, TRUE, TRUE
1561 $result['file_url'] = "<a href=\"$url\">{$uri}</a>";
1569 * Format custom fields before inserting
1571 * @param int $customFieldId
1573 * @param array $customFormatted
1576 * Value of custom field.
1577 * @param string $customFieldExtend
1578 * Custom field extends.
1579 * @param int $customValueId
1580 * Custom option value id.
1581 * @param int $entityId
1582 * Entity id (contribution, membership...).
1583 * @param bool $inline
1584 * Consider inline custom groups only.
1585 * @param bool $checkPermission
1586 * If false, do not include permissioning clause.
1587 * @param bool $includeViewOnly
1588 * If true, fields marked 'View Only' are included. Required for APIv3.
1590 * @return array $customFormatted formatted custom field array
1593 static function formatCustomField(
1594 $customFieldId, &$customFormatted, $value,
1595 $customFieldExtend, $customValueId = NULL,
1598 $checkPermission = TRUE,
1599 $includeViewOnly = FALSE
1601 //get the custom fields for the entity
1602 //subtype and basic type
1603 $customDataSubType = NULL;
1604 if (is_array($customFieldExtend)) {
1605 $customFieldExtend = $customFieldExtend[0];
1608 if (in_array($customFieldExtend,
1609 CRM_Contact_BAO_ContactType
::subTypes()
1611 // This is the case when getFieldsForImport() requires fields
1612 // of subtype and its parent.CRM-5143
1613 $customDataSubType = $customFieldExtend;
1614 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1617 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1627 if (!array_key_exists($customFieldId, $customFields)) {
1631 // return if field is a 'code' field
1632 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1636 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1638 if (!$customValueId &&
1639 // we always create new entites for is_multiple unless specified
1640 !$customFields[$customFieldId]['is_multiple'] &&
1646 WHERE entity_id={$entityId}";
1648 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1651 //fix checkbox, now check box always submits values
1652 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1654 // Note that only during merge this is not an array, and you can directly use value
1655 if (is_array($value)) {
1656 $selectedValues = array();
1657 foreach ($value as $selId => $val) {
1659 $selectedValues[] = $selId;
1662 if (!empty($selectedValues)) {
1663 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1665 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1674 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1675 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select'
1678 // Note that only during merge this is not an array,
1679 // and you can directly use value, CRM-4385
1680 if (is_array($value)) {
1681 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1682 array_values($value)
1683 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1691 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1692 $customFields[$customFieldId]['html_type'] == 'AdvMulti-Select' ||
1693 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1695 $customFields[$customFieldId]['data_type'] == 'String' &&
1696 !empty($customFields[$customFieldId]['text_length']) &&
1699 // lets make sure that value is less than the length, else we'll
1700 // be losing some data, CRM-7481
1701 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1702 // need to do a few things here
1704 // 1. lets find a new length
1705 $newLength = $customFields[$customFieldId]['text_length'];
1706 $minLength = strlen($value);
1707 while ($newLength < $minLength) {
1708 $newLength = $newLength * 2;
1711 // set the custom field meta data to have a length larger than value
1712 // alter the custom value table column to match this length
1713 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1718 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1719 if (!CRM_Utils_System
::isNull($value)) {
1720 $format = $customFields[$customFieldId]['date_format'];
1721 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1726 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1727 $customFields[$customFieldId]['data_type'] == 'Money'
1733 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1734 $value = CRM_Utils_Rule
::cleanMoney($value);
1738 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1739 $customFields[$customFieldId]['data_type'] == 'Country'
1749 if ($customFields[$customFieldId]['data_type'] == 'File') {
1750 if (empty($value)) {
1754 $config = CRM_Core_Config
::singleton();
1756 $fName = $value['name'];
1757 $mimeType = $value['type'];
1759 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1761 // rename this file to go into the secure directory
1762 if (!rename($fName, $config->customFileUploadDir
. $filename)) {
1763 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1766 if ($customValueId) {
1771 $params = array(1 => array($customValueId, 'Integer'));
1772 $fileId = CRM_Core_DAO
::singleValueQuery($query, $params);
1775 $fileDAO = new CRM_Core_DAO_File();
1778 $fileDAO->id
= $fileId;
1781 $fileDAO->uri
= $filename;
1782 $fileDAO->mime_type
= $mimeType;
1783 $fileDAO->upload_date
= date('Ymdhis');
1785 $fileId = $fileDAO->id
;
1789 if (!is_array($customFormatted)) {
1790 $customFormatted = array();
1793 if (!array_key_exists($customFieldId, $customFormatted)) {
1794 $customFormatted[$customFieldId] = array();
1798 if ($customValueId) {
1799 $index = $customValueId;
1802 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1803 $customFormatted[$customFieldId][$index] = array();
1805 $customFormatted[$customFieldId][$index] = array(
1806 'id' => $customValueId > 0 ?
$customValueId : NULL,
1808 'type' => $customFields[$customFieldId]['data_type'],
1809 'custom_field_id' => $customFieldId,
1810 'custom_group_id' => $groupID,
1811 'table_name' => $tableName,
1812 'column_name' => $columnName,
1813 'file_id' => $fileId,
1814 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1817 //we need to sort so that custom fields are created in the order of entry
1818 krsort($customFormatted[$customFieldId]);
1819 return $customFormatted;
1823 * @param array $params
1827 public static function &defaultCustomTableSchema(&$params) {
1828 // add the id and extends_id
1830 'name' => $params['name'],
1831 'is_multiple' => $params['is_multiple'],
1832 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1836 'type' => 'int unsigned',
1839 'attributes' => 'AUTO_INCREMENT',
1840 'comment' => 'Default MySQL primary key',
1843 'name' => 'entity_id',
1844 'type' => 'int unsigned',
1846 'comment' => 'Table that this extends',
1847 'fk_table_name' => $params['extends_name'],
1848 'fk_field_name' => 'id',
1849 'fk_attributes' => 'ON DELETE CASCADE',
1854 if (!$params['is_multiple']) {
1855 $table['indexes'] = array(
1858 'field_name_1' => 'entity_id',
1868 * @param bool $indexExist
1869 * @param bool $triggerRebuild
1871 public static function createField($field, $operation, $indexExist = FALSE, $triggerRebuild = TRUE) {
1872 $tableName = CRM_Core_DAO
::getFieldValue(
1873 'CRM_Core_DAO_CustomGroup',
1874 $field->custom_group_id
,
1879 'table_name' => $tableName,
1880 'operation' => $operation,
1881 'name' => $field->column_name
,
1882 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
1886 'required' => $field->is_required
,
1887 'searchable' => $field->is_searchable
,
1890 if ($operation == 'delete') {
1891 $fkName = "{$tableName}_{$field->column_name}";
1892 if (strlen($fkName) >= 48) {
1893 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
1895 $params['fkName'] = $fkName;
1897 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
1898 $params['fk_table_name'] = 'civicrm_country';
1899 $params['fk_field_name'] = 'id';
1900 $params['fk_attributes'] = 'ON DELETE SET NULL';
1902 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
1903 $params['type'] = 'varchar(255)';
1905 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
1906 $params['fk_table_name'] = 'civicrm_state_province';
1907 $params['fk_field_name'] = 'id';
1908 $params['fk_attributes'] = 'ON DELETE SET NULL';
1910 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
1911 $params['type'] = 'varchar(255)';
1913 elseif ($field->data_type
== 'File') {
1914 $params['fk_table_name'] = 'civicrm_file';
1915 $params['fk_field_name'] = 'id';
1916 $params['fk_attributes'] = 'ON DELETE SET NULL';
1918 elseif ($field->data_type
== 'ContactReference') {
1919 $params['fk_table_name'] = 'civicrm_contact';
1920 $params['fk_field_name'] = 'id';
1921 $params['fk_attributes'] = 'ON DELETE SET NULL';
1923 if (isset($field->default_value
)) {
1924 $params['default'] = "'{$field->default_value}'";
1927 CRM_Core_BAO_SchemaHandler
::alterFieldSQL($params, $indexExist, $triggerRebuild);
1931 * Determine whether it would be safe to move a field
1933 * @param int $fieldID
1934 * FK to civicrm_custom_field.
1935 * @param int $newGroupID
1936 * FK to civicrm_custom_group.
1941 public static function _moveFieldValidate($fieldID, $newGroupID) {
1944 $field = new CRM_Core_DAO_CustomField();
1945 $field->id
= $fieldID;
1946 if (!$field->find(TRUE)) {
1947 $errors['fieldID'] = 'Invalid ID for custom field';
1951 $oldGroup = new CRM_Core_DAO_CustomGroup();
1952 $oldGroup->id
= $field->custom_group_id
;
1953 if (!$oldGroup->find(TRUE)) {
1954 $errors['fieldID'] = 'Invalid ID for old custom group';
1958 $newGroup = new CRM_Core_DAO_CustomGroup();
1959 $newGroup->id
= $newGroupID;
1960 if (!$newGroup->find(TRUE)) {
1961 $errors['newGroupID'] = 'Invalid ID for new custom group';
1967 FROM civicrm_custom_field a
1968 INNER JOIN civicrm_custom_field b
1970 AND a.label = b.label
1971 AND b.custom_group_id = %2
1974 1 => array($field->id
, 'Integer'),
1975 2 => array($newGroup->id
, 'Integer'),
1977 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1979 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1982 $tableName = $oldGroup->table_name
;
1983 $columnName = $field->column_name
;
1988 WHERE $columnName is not null
1990 $count = CRM_Core_DAO
::singleValueQuery($query,
1991 CRM_Core_DAO
::$_nullArray
1996 FROM civicrm_custom_group
1997 WHERE id IN ( %1, %2 )
2000 1 => array($oldGroup->id
, 'Integer'),
2001 2 => array($newGroup->id
, 'Integer'),
2004 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2006 while ($dao->fetch()) {
2007 $extends[] = $dao->extends;
2009 if ($extends[0] != $extends[1]) {
2010 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
2014 return empty($errors) ?
TRUE : $errors;
2018 * Move a custom data field from one group (table) to another
2020 * @param int $fieldID
2021 * FK to civicrm_custom_field.
2022 * @param int $newGroupID
2023 * FK to civicrm_custom_group.
2027 public static function moveField($fieldID, $newGroupID) {
2028 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
2029 if (TRUE !== $validation) {
2030 CRM_Core_Error
::fatal(implode(' ', $validation));
2032 $field = new CRM_Core_DAO_CustomField();
2033 $field->id
= $fieldID;
2036 $newGroup = new CRM_Core_DAO_CustomGroup();
2037 $newGroup->id
= $newGroupID;
2038 $newGroup->find(TRUE);
2040 $oldGroup = new CRM_Core_DAO_CustomGroup();
2041 $oldGroup->id
= $field->custom_group_id
;
2042 $oldGroup->find(TRUE);
2045 $add->custom_group_id
= $newGroup->id
;
2046 self
::createField($add, 'add');
2048 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
2049 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
2050 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
2052 CRM_Core_DAO
::executeQuery($sql);
2055 $del->custom_group_id
= $oldGroup->id
;
2056 self
::createField($del, 'delete');
2060 CRM_Utils_System
::flushCache();
2064 * Get the database table name and column name for a custom field
2066 * @param int $fieldID
2067 * The fieldID of the custom field.
2068 * @param bool $force
2069 * Force the sql to be run again (primarily used for tests).
2071 * @return array - fatal is fieldID does not exists, else array of tableName, columnName
2074 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2075 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2076 $cache = CRM_Utils_Cache
::singleton();
2077 $fieldValues = $cache->get($cacheKey);
2078 if (empty($fieldValues) ||
$force) {
2080 SELECT cg.table_name, cf.column_name, cg.id
2081 FROM civicrm_custom_group cg,
2082 civicrm_custom_field cf
2083 WHERE cf.custom_group_id = cg.id
2085 $params = array(1 => array($fieldID, 'Integer'));
2086 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2088 if (!$dao->fetch()) {
2089 CRM_Core_Error
::fatal();
2092 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2093 $cache->set($cacheKey, $fieldValues);
2095 return $fieldValues;
2099 * Get custom option groups
2101 * @param array $includeFieldIds
2102 * Ids of custom fields for which.
2103 * option groups must be included.
2105 * Currently this is required in the cases where option groups are to be included
2106 * for inactive fields : CRM-5369
2109 * @return mixed $customOptionGroup@static
2111 public static function &customOptionGroup($includeFieldIds = NULL) {
2112 static $customOptionGroup = NULL;
2114 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2115 if ($cacheKey == 'force') {
2116 $customOptionGroup[$cacheKey] = NULL;
2119 if (empty($customOptionGroup[$cacheKey])) {
2120 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2122 //support for single as well as array format.
2123 if (!empty($includeFieldIds)) {
2124 if (is_array($includeFieldIds)) {
2125 $includeFieldIds = implode(',', $includeFieldIds);
2127 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2131 SELECT g.id, g.title
2132 FROM civicrm_option_group g
2133 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2134 WHERE {$whereClause}";
2136 $dao = CRM_Core_DAO
::executeQuery($query);
2137 while ($dao->fetch()) {
2138 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2142 return $customOptionGroup[$cacheKey];
2148 * @param int $customFieldId
2150 * @param int $optionGroupId
2156 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2157 // check if option group belongs to any custom Field else delete
2158 // get the current option group
2159 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2163 // get the updated option group
2164 // if both are same return
2165 if ($currentOptionGroupId == $optionGroupId) {
2169 // check if option group is related to any other field
2170 self
::checkOptionGroup($currentOptionGroupId);
2174 * Check if option group is related to more than one
2177 * @param int $optionGroupId
2183 public static function checkOptionGroup($optionGroupId) {
2186 FROM civicrm_custom_field
2187 WHERE option_group_id = {$optionGroupId}";
2189 $count = CRM_Core_DAO
::singleValueQuery($query);
2192 //delete the option group
2193 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2198 * @param int $optionGroupId
2201 * @return null|string
2203 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2205 SELECT default_value, html_type
2206 FROM civicrm_custom_field
2207 WHERE option_group_id = {$optionGroupId}
2208 AND default_value IS NOT NULL
2209 ORDER BY html_type";
2211 $dao = CRM_Core_DAO
::executeQuery($query);
2212 $defaultValue = NULL;
2213 $defaultHTMLType = NULL;
2214 while ($dao->fetch()) {
2215 if ($dao->html_type
== $htmlType) {
2216 return $dao->default_value
;
2218 if ($defaultValue == NULL) {
2219 $defaultValue = $dao->default_value
;
2220 $defaultHTMLType = $dao->html_type
;
2224 // some conversions are needed if either the old or new has a html type which has potential
2225 // multiple default values.
2226 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2227 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2229 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2231 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2232 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2234 $defaultValue = substr($defaultValue, 1, -1);
2235 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2236 substr($defaultValue, 1, -1)
2238 $defaultValue = $values[0];
2241 return $defaultValue;
2245 * @param array $params
2246 * @param $customFields
2247 * @param int $entityID
2248 * @param $customFieldExtends
2249 * @param bool $inline
2253 static function postProcess(
2257 $customFieldExtends,
2260 $customData = array();
2262 foreach ($params as $key => $value) {
2263 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2265 // for autocomplete transfer hidden value instead of label
2266 if ($params[$key] && isset($params[$key . '_id'])) {
2267 $value = $params[$key . '_id'];
2270 // we need to append time with date
2271 if ($params[$key] && isset($params[$key . '_time'])) {
2272 $value .= ' ' . $params[$key . '_time'];
2275 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2278 $customFieldExtends,
2279 $customFieldInfo[1],
2294 public static function buildOption($field, &$options) {
2295 // Fixme - adding anything but options to the $options array is a bad idea
2296 // What if an option had the key 'attributes'?
2297 $options['attributes'] = array(
2298 'label' => $field['label'],
2299 'data_type' => $field['data_type'],
2300 'html_type' => $field['html_type'],
2303 $optionGroupID = NULL;
2304 if (($field['html_type'] == 'CheckBox' ||
2305 $field['html_type'] == 'Radio' ||
2306 $field['html_type'] == 'Select' ||
2307 $field['html_type'] == 'AdvMulti-Select' ||
2308 $field['html_type'] == 'Multi-Select' ||
2309 ($field['html_type'] == 'Autocomplete-Select' && $field['data_type'] != 'ContactReference')
2312 if ($field['option_group_id']) {
2313 $optionGroupID = $field['option_group_id'];
2315 elseif ($field['data_type'] != 'Boolean') {
2316 CRM_Core_Error
::fatal();
2320 // build the cache for custom values with options (label => value)
2321 if ($optionGroupID != NULL) {
2324 FROM civicrm_option_value
2325 WHERE option_group_id = $optionGroupID
2328 $dao = CRM_Core_DAO
::executeQuery($query);
2329 while ($dao->fetch()) {
2330 if ($field['data_type'] == 'Int' ||
$field['data_type'] == 'Float') {
2331 $num = round($dao->value
, 2);
2332 $options["$num"] = $dao->label
;
2335 $options[$dao->value
] = $dao->label
;
2339 CRM_Utils_Hook
::customFieldOptions($field['id'], $options);
2344 * @param $fieldLabel
2345 * @param null $groupTitle
2349 public static function getCustomFieldID($fieldLabel, $groupTitle = NULL) {
2350 $params = array(1 => array($fieldLabel, 'String'));
2352 $params[2] = array($groupTitle, 'String');
2355 FROM civicrm_custom_field f
2356 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2357 WHERE ( f.label = %1 OR f.name = %1 )
2358 AND ( g.title = %2 OR g.name = %2 )
2364 FROM civicrm_custom_field f
2365 WHERE ( f.label = %1 OR f.name = %1 )
2369 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2370 if ($dao->fetch() &&
2381 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2384 public static function getNameFromID($ids) {
2385 if (is_array($ids)) {
2386 $ids = implode(',', $ids);
2389 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2390 FROM civicrm_custom_field f
2391 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2392 WHERE f.id IN ($ids)";
2394 $dao = CRM_Core_DAO
::executeQuery($sql);
2396 while ($dao->fetch()) {
2397 $result[$dao->id
] = array(
2398 'field_name' => $dao->field_name
,
2399 'field_label' => $dao->field_label
,
2400 'group_name' => $dao->group_name
,
2401 'group_title' => $dao->group_title
,
2408 * Validate custom data.
2410 * @param array $params
2411 * Custom data submitted.
2412 * ie array( 'custom_1' => 'validate me' );
2414 * @return array $errors validation errors.
2417 public static function validateCustomData($params) {
2419 if (!is_array($params) ||
empty($params)) {
2423 //pick up profile fields.
2424 $profileFields = array();
2425 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2427 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2429 CRM_Core_Action
::VIEW
2433 //lets start w/ params.
2434 foreach ($params as $key => $value) {
2435 $customFieldID = self
::getKeyID($key);
2436 if (!$customFieldID) {
2440 //load the structural info for given field.
2441 $field = new CRM_Core_DAO_CustomField();
2442 $field->id
= $customFieldID;
2443 if (!$field->find(TRUE)) {
2446 $dataType = $field->data_type
;
2448 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2449 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2450 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2452 $fieldTitle = $field->label
;
2455 //no need to validate.
2456 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2460 //lets validate first for required field.
2461 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2462 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2466 //now time to take care of custom field form rules.
2467 $ruleName = $errorMsg = NULL;
2468 switch ($dataType) {
2470 $ruleName = 'integer';
2471 $errorMsg = ts('%1 must be an integer (whole number).',
2472 array(1 => $fieldTitle)
2477 $ruleName = 'money';
2478 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2479 array(1 => $fieldTitle)
2484 $ruleName = 'numeric';
2485 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2486 array(1 => $fieldTitle)
2491 $ruleName = 'wikiURL';
2492 $errorMsg = ts('%1 must be valid Website.',
2493 array(1 => $fieldTitle)
2498 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2500 $funName = "CRM_Utils_Rule::{$ruleName}";
2501 if (is_callable($funName)) {
2502 $valid = call_user_func($funName, $value);
2505 $errors[$key] = $errorMsg;
2514 * @param int $customId
2518 public static function isMultiRecordField($customId) {
2519 $isMultipleWithGid = FALSE;
2520 if (!is_numeric($customId)) {
2521 $customId = self
::getKeyID($customId);
2523 if (is_numeric($customId)) {
2524 $sql = "SELECT cg.id cgId
2525 FROM civicrm_custom_group cg
2526 INNER JOIN civicrm_custom_field cf
2527 ON cg.id = cf.custom_group_id
2528 WHERE cf.id = %1 AND cg.is_multiple = 1";
2529 $params[1] = array($customId, 'Integer');
2530 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2531 if ($dao->fetch()) {
2533 $isMultipleWithGid = $dao->cgId
;
2538 return $isMultipleWithGid;
2542 * Does this field store a serialized string?
2543 * @param CRM_Core_DAO_CustomField|array $field
2546 public static function isSerialized($field) {
2547 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2548 $field = (array) $field;
2549 // 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.
2550 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);