3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
35 * Business objects for managing custom data fields.
37 class CRM_Core_BAO_CustomField
extends CRM_Core_DAO_CustomField
{
40 * Array for valid combinations of data_type & descriptions.
44 public static $_dataType = NULL;
47 * Array for valid combinations of data_type & html_type.
51 public static $_dataToHtml = NULL;
54 * Array to hold (formatted) fields for import
58 public static $_importFields = NULL;
61 * Build and retrieve the list of data types and descriptions.
64 * Data type => Description
66 public static function &dataType() {
67 if (!(self
::$_dataType)) {
68 self
::$_dataType = array(
69 'String' => ts('Alphanumeric'),
70 'Int' => ts('Integer'),
71 'Float' => ts('Number'),
72 'Money' => ts('Money'),
75 'Boolean' => ts('Yes or No'),
76 'StateProvince' => ts('State/Province'),
77 'Country' => ts('Country'),
80 'ContactReference' => ts('Contact Reference'),
83 return self
::$_dataType;
87 * Build the map of custom field's data types and there respective Util type
90 * Data data-type => CRM_Utils_Type
92 public static function dataToType() {
94 'String' => CRM_Utils_Type
::T_STRING
,
95 'Int' => CRM_Utils_Type
::T_INT
,
96 'Money' => CRM_Utils_Type
::T_MONEY
,
97 'Memo' => CRM_Utils_Type
::T_LONGTEXT
,
98 'Float' => CRM_Utils_Type
::T_FLOAT
,
99 'Date' => CRM_Utils_Type
::T_DATE
,
100 'DateTime' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
101 'Boolean' => CRM_Utils_Type
::T_BOOLEAN
,
102 'StateProvince' => CRM_Utils_Type
::T_INT
,
103 'File' => CRM_Utils_Type
::T_STRING
,
104 'Link' => CRM_Utils_Type
::T_STRING
,
105 'ContactReference' => CRM_Utils_Type
::T_INT
,
106 'Country' => CRM_Utils_Type
::T_INT
,
111 * Get data to html array.
113 * (Does this caching achieve anything?)
117 public static function dataToHtml() {
118 if (!self
::$_dataToHtml) {
119 self
::$_dataToHtml = array(
122 'Select' => 'Select',
124 'CheckBox' => 'CheckBox',
125 'Multi-Select' => 'Multi-Select',
126 'Autocomplete-Select' => 'Autocomplete-Select',
128 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
129 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
130 array('Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'),
131 array('TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'),
132 array('Date' => 'Select Date'),
133 array('Radio' => 'Radio'),
134 array('StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'),
135 array('Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'),
136 array('File' => 'File'),
137 array('Link' => 'Link'),
138 array('ContactReference' => 'Autocomplete-Select'),
141 return self
::$_dataToHtml;
145 * Takes an associative array and creates a custom field object.
147 * This function is invoked from within the web form layer and also from the api layer
149 * @param array $params
150 * (reference) an assoc array of name/value pairs.
152 * @return CRM_Core_DAO_CustomField
154 public static function create($params) {
155 $customField = self
::createCustomFieldRecord($params);
156 $op = empty($params['id']) ?
'add' : 'modify';
157 self
::createField($customField, $op);
159 CRM_Utils_Hook
::post(($op === 'add' ?
'create' : 'edit'), 'CustomField', $customField->id
, $customField);
161 CRM_Utils_System
::flushCache();
167 * Create/ update several fields at once in a mysql efficient way.
169 * https://lab.civicrm.org/dev/core/issues/1093
171 * The intention is that apiv4 would expose any BAO with bulkSave as a new action.
173 * @param array $bulkParams
174 * Array of arrays as would be passed into create
175 * @param array $defaults
176 * Default parameters to be be merged into each of the params.
178 public static function bulkSave($bulkParams, $defaults = []) {
179 $sql = $tables = $customFields = [];
180 foreach ($bulkParams as $index => $fieldParams) {
181 $params = array_merge($defaults, $fieldParams);
182 $customField = self
::createCustomFieldRecord($params);
183 $fieldSQL = self
::getAlterFieldSQL($customField, empty($params['id']) ?
'add' : 'modify');
184 if (!isset($params['custom_group_id'])) {
185 $params['custom_group_id'] = civicrm_api3('CustomField', 'getvalue', ['id' => $customField->id
, 'return' => 'custom_group_id']);
187 if (!isset($params['table_name'])) {
188 if (!isset($tables[$params['custom_group_id']])) {
189 $tables[$params['custom_group_id']] = civicrm_api3('CustomGroup', 'getvalue', [
190 'id' => $params['custom_group_id'],
191 'return' => 'table_name',
194 $params['table_name'] = $tables[$params['custom_group_id']];
196 $sql[$params['table_name']][] = $fieldSQL;
197 $customFields[$index] = $customField;
199 foreach ($sql as $tableName => $statements) {
200 // CRM-7007: do not i18n-rewrite this query
201 CRM_Core_DAO
::executeQuery("ALTER TABLE $tableName " . implode(', ', $statements), [], TRUE, NULL, FALSE, FALSE);
202 Civi
::service('sql_triggers')->rebuild($params['table_name'], TRUE);
204 CRM_Utils_System
::flushCache();
205 foreach ($customFields as $index => $customField) {
206 CRM_Utils_Hook
::post(empty($bulkParams[$index]['id']) ?
'create' : 'edit', 'CustomField', $customField->id
, $customField);
211 * Fetch object based on array of properties.
213 * @param array $params
214 * (reference ) an assoc array of name/value pairs.
215 * @param array $defaults
216 * (reference ) an assoc array to hold the flattened values.
218 * @return CRM_Core_DAO_CustomField
220 public static function retrieve(&$params, &$defaults) {
221 return CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
225 * Update the is_active flag in the db.
228 * Id of the database record.
229 * @param bool $is_active
230 * Value we want to set the is_active field.
233 * true if we found and updated the object, else false
235 public static function setIsActive($id, $is_active) {
237 CRM_Utils_System
::flushCache();
239 //enable-disable CustomField
240 CRM_Core_BAO_UFField
::setUFField($id, $is_active);
241 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_CustomField', $id, 'is_active', $is_active);
245 * Get the field title.
253 public static function getTitle($id) {
254 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $id, 'label');
258 * @param string $context
261 public function getOptions($context = NULL) {
262 CRM_Core_DAO
::buildOptionsContext($context);
267 if (!$this->data_type ||
!$this->custom_group_id
) {
271 // This will hold the list of options in format key => label
274 if (!empty($this->option_group_id
)) {
275 $options = CRM_Core_OptionGroup
::valuesByID(
276 $this->option_group_id
,
281 !($context == 'validate' ||
$context == 'get')
284 elseif ($this->data_type
=== 'StateProvince') {
285 $options = CRM_Core_PseudoConstant
::stateProvince();
287 elseif ($this->data_type
=== 'Country') {
288 $options = $context == 'validate' ? CRM_Core_PseudoConstant
::countryIsoCode() : CRM_Core_PseudoConstant
::country();
290 elseif ($this->data_type
=== 'Boolean') {
291 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
293 CRM_Utils_Hook
::customFieldOptions($this->id
, $options, FALSE);
294 CRM_Utils_Hook
::fieldOptions($this->getEntity(), "custom_{$this->id}", $options, array('context' => $context));
299 * Store and return an array of all active custom fields.
301 * @param string $customDataType
302 * Type of Custom Data; 'ANY' is a synonym for "all contact data types".
303 * @param bool $showAll
304 * If true returns all fields (includes disabled fields).
305 * @param bool $inline
306 * If true returns all inline fields (includes disabled fields).
307 * @param int $customDataSubType
308 * Custom Data sub type value.
309 * @param int $customDataSubName
310 * Custom Data sub name value.
311 * @param bool $onlyParent
312 * Return only top level custom data, for eg, only Participant and ignore subname and subtype.
313 * @param bool $onlySubType
314 * Return only custom data for subtype.
315 * @param bool $checkPermission
316 * If false, do not include permissioning clause.
319 * an array of active custom fields.
321 public static function &getFields(
322 $customDataType = 'Individual',
325 $customDataSubType = NULL,
326 $customDataSubName = NULL,
328 $onlySubType = FALSE,
329 $checkPermission = TRUE
331 if (empty($customDataType)) {
332 $customDataType = array('Contact', 'Individual', 'Organization', 'Household');
334 if ($customDataType === 'ANY') {
335 // NULL should have been respected but the line above broke that.
336 // boo for us not having enough unit tests back them.
337 $customDataType = NULL;
339 if ($customDataType && !is_array($customDataType)) {
341 if (in_array($customDataType, CRM_Contact_BAO_ContactType
::subTypes())) {
342 // This is the case when getFieldsForImport() requires fields
343 // limited strictly to a subtype.
344 $customDataSubType = $customDataType;
345 $customDataType = CRM_Contact_BAO_ContactType
::getBasicType($customDataType);
349 if (in_array($customDataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
350 // this makes the method flexible to support retrieving fields
351 // for multiple extends value.
352 $customDataType = array($customDataType);
356 $customDataSubType = CRM_Utils_Array
::explodePadded($customDataSubType);
358 if (is_array($customDataType)) {
359 $cacheKey = implode('_', $customDataType);
362 $cacheKey = $customDataType;
365 $cacheKey .= !empty($customDataSubType) ?
('_' . implode('_', $customDataSubType)) : '_0';
366 $cacheKey .= $customDataSubName ?
"{$customDataSubName}_" : '_0';
367 $cacheKey .= $showAll ?
'_1' : '_0';
368 $cacheKey .= $inline ?
'_1_' : '_0_';
369 $cacheKey .= $onlyParent ?
'_1_' : '_0_';
370 $cacheKey .= $onlySubType ?
'_1_' : '_0_';
371 $cacheKey .= $checkPermission ?
'_1_' : '_0_';
372 $cacheKey .= '_' . CRM_Core_Config
::domainID() . '_';
374 $cgTable = CRM_Core_DAO_CustomGroup
::getTableName();
376 // also get the permission stuff here
377 if ($checkPermission) {
378 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
383 $permissionClause = '(1)';
386 // lets md5 permission clause and take first 8 characters
387 $cacheKey .= substr(md5($permissionClause), 0, 8);
389 if (strlen($cacheKey) > 40) {
390 $cacheKey = md5($cacheKey);
393 if (!self
::$_importFields ||
394 CRM_Utils_Array
::value($cacheKey, self
::$_importFields) === NULL
396 if (!self
::$_importFields) {
397 self
::$_importFields = array();
400 // check if we can retrieve from database cache
401 $fields = Civi
::Cache('fields')->get("custom importableFields $cacheKey");
403 if ($fields === NULL) {
404 $cfTable = self
::getTableName();
407 if (is_array($customDataType)) {
409 foreach ($customDataType as $dataType) {
410 if (in_array($dataType, array_keys(CRM_Core_SelectValues
::customGroupExtends()))) {
411 if (in_array($dataType, array('Individual', 'Household', 'Organization'))) {
412 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "', 'Contact' ";
415 $val = "'" . CRM_Utils_Type
::escape($dataType, 'String') . "'";
417 $value = $value ?
$value . ", {$val}" : $val;
421 $extends = "AND $cgTable.extends IN ( $value ) ";
425 if (!empty($customDataType) && empty($extends)) {
426 // $customDataType specified a filter, but there is no corresponding SQL ($extends)
427 self
::$_importFields[$cacheKey] = array();
428 return self
::$_importFields[$cacheKey];
432 $extends .= " AND $cgTable.extends_entity_column_value IS NULL AND $cgTable.extends_entity_column_id IS NULL ";
435 $query = "SELECT $cfTable.id, $cfTable.label,
439 $cfTable.default_value,
440 $cfTable.options_per_line, $cfTable.text_length,
441 $cfTable.custom_group_id,
442 $cfTable.is_required,
443 $cfTable.column_name,
444 $cgTable.extends, $cfTable.is_search_range,
445 $cgTable.extends_entity_column_value,
446 $cgTable.extends_entity_column_id,
448 $cfTable.option_group_id,
449 $cfTable.date_format,
450 $cfTable.time_format,
451 $cgTable.is_multiple,
453 og.name as option_group_name
456 ON $cfTable.custom_group_id = $cgTable.id
457 LEFT JOIN civicrm_option_group og
458 ON $cfTable.option_group_id = og.id
462 $query .= " AND $cfTable.is_active = 1 AND $cgTable.is_active = 1 ";
466 $query .= " AND $cgTable.style = 'Inline' ";
469 //get the custom fields for specific type in
470 //combination with fields those support any type.
471 if (!empty($customDataSubType)) {
472 $subtypeClause = array();
473 foreach ($customDataSubType as $subtype) {
474 $subtype = CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($subtype, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
;
475 $subtypeClause[] = "$cgTable.extends_entity_column_value LIKE '%{$subtype}%'";
478 $subtypeClause[] = "$cgTable.extends_entity_column_value IS NULL";
480 $query .= " AND ( " . implode(' OR ', $subtypeClause) . " )";
483 if ($customDataSubName) {
484 $query .= " AND ( $cgTable.extends_entity_column_id = $customDataSubName ) ";
487 // also get the permission stuff here
488 if ($checkPermission) {
489 $permissionClause = CRM_Core_Permission
::customGroupClause(CRM_Core_Permission
::VIEW
,
494 $permissionClause = '(1)';
497 $query .= " $extends AND $permissionClause
498 ORDER BY $cgTable.weight, $cgTable.title,
499 $cfTable.weight, $cfTable.label";
501 $dao = CRM_Core_DAO
::executeQuery($query);
504 while (($dao->fetch()) != NULL) {
505 $regexp = preg_replace('/[.,;:!?]/', '', NULL);
506 $fields[$dao->id
]['id'] = $dao->id
;
507 $fields[$dao->id
]['label'] = $dao->label
;
508 // This seems broken, but not in a new way.
509 $fields[$dao->id
]['headerPattern'] = '/' . preg_quote($regexp, '/') . '/';
510 // To support the consolidation of various functions & their expectations.
511 $fields[$dao->id
]['title'] = $dao->label
;
512 $fields[$dao->id
]['custom_field_id'] = $dao->id
;
513 $fields[$dao->id
]['groupTitle'] = $dao->title
;
514 $fields[$dao->id
]['data_type'] = $dao->data_type
;
515 $fields[$dao->id
]['name'] = 'custom_' . $dao->id
;
516 $fields[$dao->id
]['type'] = CRM_Utils_Array
::value($dao->data_type
, self
::dataToType());
517 $fields[$dao->id
]['html_type'] = $dao->html_type
;
518 $fields[$dao->id
]['default_value'] = $dao->default_value
;
519 $fields[$dao->id
]['text_length'] = $dao->text_length
;
520 $fields[$dao->id
]['options_per_line'] = $dao->options_per_line
;
521 $fields[$dao->id
]['custom_group_id'] = $dao->custom_group_id
;
522 $fields[$dao->id
]['extends'] = $dao->extends;
523 $fields[$dao->id
]['is_search_range'] = $dao->is_search_range
;
524 $fields[$dao->id
]['extends_entity_column_value'] = $dao->extends_entity_column_value
;
525 $fields[$dao->id
]['extends_entity_column_id'] = $dao->extends_entity_column_id
;
526 $fields[$dao->id
]['is_view'] = $dao->is_view
;
527 $fields[$dao->id
]['is_multiple'] = $dao->is_multiple
;
528 $fields[$dao->id
]['option_group_id'] = $dao->option_group_id
;
529 $fields[$dao->id
]['date_format'] = $dao->date_format
;
530 $fields[$dao->id
]['time_format'] = $dao->time_format
;
531 $fields[$dao->id
]['is_required'] = $dao->is_required
;
532 $fields[$dao->id
]['table_name'] = $dao->table_name
;
533 $fields[$dao->id
]['column_name'] = $dao->column_name
;
534 $fields[$dao->id
]['where'] = $dao->table_name
. '.' . $dao->column_name
;
535 // Probably we should use a different fn to get the extends tables but this is a refactor so not changing that now.
536 $fields[$dao->id
]['extends_table'] = array_key_exists($dao->extends, CRM_Core_BAO_CustomQuery
::$extendsMap) ? CRM_Core_BAO_CustomQuery
::$extendsMap[$dao->extends] : '';
537 if (in_array($dao->extends, CRM_Contact_BAO_ContactType
::subTypes())) {
538 // if $extends is a subtype, refer contact table
539 $fields[$dao->id
]['extends_table'] = 'civicrm_contact';
541 // Search table is used by query object searches..
542 $fields[$dao->id
]['search_table'] = ($fields[$dao->id
]['extends_table'] == 'civicrm_contact') ?
'contact_a' : $fields[$dao->id
]['extends_table'];
543 self
::getOptionsForField($fields[$dao->id
], $dao->option_group_name
);
547 Civi
::cache('fields')->set("custom importableFields $cacheKey", $fields);
549 self
::$_importFields[$cacheKey] = $fields;
552 return self
::$_importFields[$cacheKey];
556 * Return the field ids and names (with groups) for import purpose.
558 * @param int|string $contactType Contact type
559 * @param bool $showAll
560 * If true returns all fields (includes disabled fields).
561 * @param bool $onlyParent
562 * Return fields ONLY related to basic types.
563 * @param bool $search
564 * When called from search and multiple records need to be returned.
565 * @param bool $checkPermission
566 * If false, do not include permissioning clause.
568 * @param bool $withMultiple
572 public static function getFieldsForImport(
573 $contactType = 'Individual',
577 $checkPermission = TRUE,
578 $withMultiple = FALSE
580 // Note: there are situations when we want getFieldsForImport() return fields related
581 // ONLY to basic contact types, but NOT subtypes. And thats where $onlyParent is helpful
582 $fields = &self
::getFields($contactType,
592 $importableFields = [];
593 foreach ($fields as $id => $values) {
594 // for now we should not allow multiple fields in profile / export etc, hence unsetting
596 (!empty($values['is_multiple']) && !$withMultiple)
601 /* generate the key for the fields array */
604 $importableFields[$key] = $values;
605 $importableFields[$key]['import'] = 1;
608 return $importableFields;
612 * Get the field id from an import key.
622 public static function getKeyID($key, $all = FALSE) {
624 if (preg_match('/^custom_(\d+)_?(-?\d+)?$/', $key, $match)) {
631 CRM_Utils_Array
::value(2, $match),
635 return $all ?
array(NULL, NULL) : NULL;
639 * Use the cache to get all values of a specific custom field.
641 * @param int $fieldID
642 * The custom field ID.
644 * @return CRM_Core_BAO_CustomField
647 public static function getFieldObject($fieldID) {
648 $field = new CRM_Core_BAO_CustomField();
650 // check if we can get the field values from the system cache
651 $cacheKey = "CRM_Core_DAO_CustomField_{$fieldID}";
652 $cache = CRM_Utils_Cache
::singleton();
653 $fieldValues = $cache->get($cacheKey);
654 if (empty($fieldValues)) {
655 $field->id
= $fieldID;
656 if (!$field->find(TRUE)) {
657 CRM_Core_Error
::fatal();
660 $fieldValues = array();
661 CRM_Core_DAO
::storeValues($field, $fieldValues);
663 $cache->set($cacheKey, $fieldValues);
666 $field->copyValues($fieldValues);
673 * Add a custom field to an existing form.
675 * @param CRM_Core_Form $qf
676 * Form object (reference).
677 * @param string $elementName
678 * Name of the custom field.
679 * @param int $fieldId
680 * @param bool $useRequired
681 * True if required else false.
682 * @param bool $search
683 * True if used for search else false.
684 * @param string $label
685 * Label for custom field.
686 * @return \HTML_QuickForm_Element|null
687 * @throws \CiviCRM_API3_Exception
689 public static function addQuickFormElement(
690 $qf, $elementName, $fieldId, $useRequired = TRUE, $search = FALSE, $label = NULL
692 $field = self
::getFieldObject($fieldId);
693 $widget = $field->html_type
;
695 $customFieldAttributes = array();
697 // Custom field HTML should indicate group+field name
698 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
);
699 $dataCrmCustomVal = $groupName . ':' . $field->name
;
700 $dataCrmCustomAttr = 'data-crm-custom="' . $dataCrmCustomVal . '"';
701 $field->attributes
.= $dataCrmCustomAttr;
703 // Fixed for Issue CRM-2183
704 if ($widget == 'TextArea' && $search) {
708 $placeholder = $search ?
ts('- any -') : ($useRequired ?
ts('- select -') : ts('- none -'));
710 // FIXME: Why are select state/country separate widget types?
711 $isSelect = (in_array($widget, array(
714 'Select State/Province',
715 'Multi-Select State/Province',
717 'Multi-Select Country',
723 $options = $field->getOptions($search ?
'search' : 'create');
725 // Consolidate widget types to simplify the below switch statement
726 if ($search ||
(strpos($widget, 'Select') !== FALSE)) {
730 $customFieldAttributes['data-crm-custom'] = $dataCrmCustomVal;
731 $selectAttributes = array('class' => 'crm-select2');
733 // Search field is always multi-select
734 if ($search ||
strpos($field->html_type
, 'Multi') !== FALSE) {
735 $selectAttributes['class'] .= ' huge';
736 $selectAttributes['multiple'] = 'multiple';
737 $selectAttributes['placeholder'] = $placeholder;
740 // Add data for popup link. Normally this is handled by CRM_Core_Form->addSelect
741 $isSupportedWidget = in_array($widget, ['Select', 'Radio']);
742 $canEditOptions = CRM_Core_Permission
::check('administer CiviCRM');
743 if ($field->option_group_id
&& !$search && $isSelect && $canEditOptions) {
744 $customFieldAttributes +
= array(
745 'data-api-entity' => $field->getEntity(),
746 'data-api-field' => 'custom_' . $field->id
,
747 'data-option-edit-path' => 'civicrm/admin/options/' . CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', $field->option_group_id
),
749 $selectAttributes +
= $customFieldAttributes;
753 $rangeDataTypes = ['Int', 'Float', 'Money'];
755 if (!isset($label)) {
756 $label = $field->label
;
759 // at some point in time we might want to split the below into small functions
764 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
765 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
766 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
769 if ($field->text_length
) {
770 $field->attributes
.= ' maxlength=' . $field->text_length
;
771 if ($field->text_length
< 20) {
772 $field->attributes
.= ' size=' . $field->text_length
;
775 $element = $qf->add('text', $elementName, $label,
777 $useRequired && !$search
783 $attributes = $dataCrmCustomAttr;
784 if ($field->note_rows
) {
785 $attributes .= 'rows=' . $field->note_rows
;
788 $attributes .= 'rows=4';
790 if ($field->note_columns
) {
791 $attributes .= ' cols=' . $field->note_columns
;
794 $attributes .= ' cols=60';
796 if ($field->text_length
) {
797 $attributes .= ' maxlength=' . $field->text_length
;
799 $element = $qf->add('textarea',
803 $useRequired && !$search
808 $attr = array('data-crm-custom' => $dataCrmCustomVal);
809 //CRM-18379: Fix for date range of 'Select Date' custom field when include in profile.
810 $minYear = isset($field->start_date_years
) ?
(date('Y') - $field->start_date_years
) : NULL;
811 $maxYear = isset($field->end_date_years
) ?
(date('Y') +
$field->end_date_years
) : NULL;
814 'date' => $field->date_format
,
815 'minDate' => isset($minYear) ?
$minYear . '-01-01' : NULL,
816 //CRM-18487 - max date should be the last date of the year.
817 'maxDate' => isset($maxYear) ?
$maxYear . '-12-31' : NULL,
818 'time' => $field->time_format ?
$field->time_format
* 12 : FALSE,
820 if ($field->is_search_range
&& $search) {
821 $qf->add('datepicker', $elementName . '_from', $label, $attr +
array('placeholder' => ts('From')), FALSE, $params);
822 $qf->add('datepicker', $elementName . '_to', NULL, $attr +
array('placeholder' => ts('To')), FALSE, $params);
825 $element = $qf->add('datepicker', $elementName, $label, $attr, $useRequired && !$search, $params);
830 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
831 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
832 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
836 parse_str($field->attributes
, $radioAttributes);
837 $radioAttributes = array_merge($radioAttributes, $customFieldAttributes);
839 foreach ($options as $v => $l) {
840 $choice[] = $qf->createElement('radio', NULL, '', $l, (string) $v, $radioAttributes);
842 $element = $qf->addGroup($choice, $elementName, $label);
843 $optionEditKey = 'data-option-edit-path';
844 if (isset($selectAttributes[$optionEditKey])) {
845 $element->setAttribute($optionEditKey, $selectAttributes[$optionEditKey]);
848 if ($useRequired && !$search) {
849 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
852 $element->setAttribute('allowClear', TRUE);
857 // For all select elements
859 if ($field->is_search_range
&& $search && in_array($field->data_type
, $rangeDataTypes)) {
860 $qf->add('text', $elementName . '_from', $label . ' ' . ts('From'), $field->attributes
);
861 $qf->add('text', $elementName . '_to', ts('To'), $field->attributes
);
864 if (empty($selectAttributes['multiple'])) {
865 $options = array('' => $placeholder) +
$options;
867 $element = $qf->add('select', $elementName, $label, $options, $useRequired && !$search, $selectAttributes);
869 // Add and/or option for fields that store multiple values
870 if ($search && self
::isSerialized($field)) {
873 $qf->createElement('radio', NULL, '', ts('Any'), 'or', array('title' => ts('Results may contain any of the selected options'))),
874 $qf->createElement('radio', NULL, '', ts('All'), 'and', array('title' => ts('Results must have all of the selected options'))),
876 $qf->addGroup($operators, $elementName . '_operator');
877 $qf->setDefaults(array($elementName . '_operator' => 'or'));
884 foreach ($options as $v => $l) {
885 $check[] = &$qf->addElement('advcheckbox', $v, NULL, $l, $customFieldAttributes);
888 $group = $element = $qf->addGroup($check, $elementName, $label);
889 $optionEditKey = 'data-option-edit-path';
890 if (isset($customFieldAttributes[$optionEditKey])) {
891 $group->setAttribute($optionEditKey, $customFieldAttributes[$optionEditKey]);
894 if ($useRequired && !$search) {
895 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
900 // we should not build upload file in search mode
905 strtolower($field->html_type
),
909 $useRequired && !$search
911 $qf->addUploadElement($elementName);
914 case 'RichTextEditor':
916 'rows' => $field->note_rows
,
917 'cols' => $field->note_columns
,
918 'data-crm-custom' => $dataCrmCustomVal,
920 if ($field->text_length
) {
921 $attributes['maxlength'] = $field->text_length
;
923 $element = $qf->add('wysiwyg', $elementName, $label, $attributes, $useRequired && !$search);
926 case 'Autocomplete-Select':
927 static $customUrls = array();
928 // Fixme: why is this a string in the first place??
929 $attributes = array();
930 if ($field->attributes
) {
931 foreach (explode(' ', $field->attributes
) as $at) {
932 if (strpos($at, '=')) {
933 list($k, $v) = explode('=', $at);
934 $attributes[$k] = trim($v, ' "');
938 if ($field->data_type
== 'ContactReference') {
939 // break if contact does not have permission to access ContactReference
940 if (!CRM_Core_Permission
::check('access contact reference fields')) {
943 $attributes['class'] = (isset($attributes['class']) ?
$attributes['class'] . ' ' : '') . 'crm-form-contact-reference huge';
944 $attributes['data-api-entity'] = 'Contact';
945 $element = $qf->add('text', $elementName, $label, $attributes, $useRequired && !$search);
947 $urlParams = "context=customfield&id={$field->id}";
948 $idOfelement = $elementName;
949 // dev/core#362 if in an onbehalf profile clean up the name to get rid of square brackets that break the select 2 js
950 // However this caused regression https://lab.civicrm.org/dev/core/issues/619 so it has been hacked back to
951 // only affecting on behalf - next time someone looks at this code it should be with a view to overhauling it
952 // rather than layering on more hacks.
953 if (substr($elementName, 0, 8) === 'onbehalf' && strpos($elementName, '[') && strpos($elementName, ']')) {
954 $idOfelement = substr(substr($elementName, (strpos($elementName, '[') +
1)), 0, -1);
956 $customUrls[$idOfelement] = CRM_Utils_System
::url('civicrm/ajax/contactref',
963 // FIXME: This won't work with customFieldOptions hook
964 $attributes +
= array(
965 'entity' => 'OptionValue',
966 'placeholder' => $placeholder,
967 'multiple' => $search,
969 'params' => array('option_group_id' => $field->option_group_id
, 'is_active' => 1),
972 $element = $qf->addEntityRef($elementName, $label, $attributes, $useRequired && !$search);
975 $qf->assign('customUrls', $customUrls);
979 switch ($field->data_type
) {
981 // integers will have numeric rule applied to them.
982 if ($field->is_search_range
&& $search) {
983 $qf->addRule($elementName . '_from', ts('%1 From must be an integer (whole number).', array(1 => $label)), 'integer');
984 $qf->addRule($elementName . '_to', ts('%1 To must be an integer (whole number).', array(1 => $label)), 'integer');
986 elseif ($widget == 'Text') {
987 $qf->addRule($elementName, ts('%1 must be an integer (whole number).', array(1 => $label)), 'integer');
992 if ($field->is_search_range
&& $search) {
993 $qf->addRule($elementName . '_from', ts('%1 From must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
994 $qf->addRule($elementName . '_to', ts('%1 To must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
996 elseif ($widget == 'Text') {
997 $qf->addRule($elementName, ts('%1 must be a number (with or without decimal point).', array(1 => $label)), 'numeric');
1002 if ($field->is_search_range
&& $search) {
1003 $qf->addRule($elementName . '_from', ts('%1 From must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1004 $qf->addRule($elementName . '_to', ts('%1 To must in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1006 elseif ($widget == 'Text') {
1007 $qf->addRule($elementName, ts('%1 must be in proper money format. (decimal point/comma/space is allowed).', array(1 => $label)), 'money');
1012 $element->setAttribute('class', "url");
1013 $qf->addRule($elementName, ts('Enter a valid web address beginning with \'http://\' or \'https://\'.'), 'wikiURL');
1016 if ($field->is_view
&& !$search) {
1017 $qf->freeze($elementName);
1023 * Delete the Custom Field.
1025 * @param object $field
1028 public static function deleteField($field) {
1029 CRM_Utils_System
::flushCache();
1031 // first delete the custom option group and values associated with this field
1032 if ($field->option_group_id
) {
1033 //check if option group is related to any other field, if
1034 //not delete the option group and related option values
1035 self
::checkOptionGroup($field->option_group_id
);
1038 // next drop the column from the custom value table
1039 self
::createField($field, 'delete');
1042 CRM_Core_BAO_UFField
::delUFField($field->id
);
1043 CRM_Utils_Weight
::correctDuplicateWeights('CRM_Core_DAO_CustomField');
1045 CRM_Utils_Hook
::post('delete', 'CustomField', $field->id
, $field);
1049 * @param string|int|array|null $value
1050 * @param CRM_Core_BAO_CustomField|int|array|string $field
1051 * @param int $entityId
1054 * @throws \Exception
1056 public static function displayValue($value, $field, $entityId = NULL) {
1057 $field = is_array($field) ?
$field['id'] : $field;
1058 $fieldId = is_object($field) ?
$field->id
: (int) str_replace('custom_', '', $field);
1061 throw new Exception('CRM_Core_BAO_CustomField::displayValue requires a field id');
1064 if (!is_a($field, 'CRM_Core_BAO_CustomField')) {
1065 $field = self
::getFieldObject($fieldId);
1068 $fieldInfo = array('options' => $field->getOptions()) +
(array) $field;
1070 return self
::formatDisplayValue($value, $fieldInfo, $entityId);
1074 * Lower-level logic for rendering a custom field value
1076 * @param string|array $value
1077 * @param array $field
1078 * @param int|null $entityId
1082 private static function formatDisplayValue($value, $field, $entityId = NULL) {
1084 if (self
::isSerialized($field) && !is_array($value)) {
1085 $value = CRM_Utils_Array
::explodePadded($value);
1088 if ($field['html_type'] == 'CheckBox' && $value) {
1089 $value = CRM_Utils_Array
::convertCheckboxFormatToArray($value);
1092 $display = is_array($value) ?
implode(', ', $value) : (string) $value;
1094 switch ($field['html_type']) {
1097 case 'Autocomplete-Select':
1099 case 'Select Country':
1100 case 'Select State/Province':
1102 case 'Multi-Select':
1103 case 'Multi-Select State/Province':
1104 case 'Multi-Select Country':
1105 if ($field['data_type'] == 'ContactReference' && $value) {
1106 if (is_numeric($value)) {
1107 $display = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'display_name');
1113 elseif (is_array($value)) {
1115 foreach ($value as $key => $val) {
1116 $v[] = CRM_Utils_Array
::value($val, $field['options']);
1118 $display = implode(', ', $v);
1121 $display = CRM_Utils_Array
::value($value, $field['options'], '');
1126 $customFormat = NULL;
1128 // FIXME: Are there any legitimate reasons why $value would be an array?
1129 // Or should we throw an exception here if it is?
1130 $value = is_array($value) ? CRM_Utils_Array
::first($value) : $value;
1132 $actualPHPFormats = CRM_Utils_Date
::datePluginToPHPFormats();
1133 $format = CRM_Utils_Array
::value('date_format', $field);
1136 if (array_key_exists($format, $actualPHPFormats)) {
1137 $customTimeFormat = (array) $actualPHPFormats[$format];
1138 switch (CRM_Utils_Array
::value('time_format', $field)) {
1140 $customTimeFormat[] = 'g:iA';
1144 $customTimeFormat[] = 'G:i';
1148 //If time is not selected remove time from value.
1149 $value = $value ?
date('Y-m-d', strtotime($value)) : '';
1151 $customFormat = implode(" ", $customTimeFormat);
1154 $display = CRM_Utils_Date
::processDate($value, NULL, FALSE, $customFormat);
1158 // In the context of displaying a profile, show file/image
1161 if (CRM_Utils_Rule
::positiveInteger($value)) {
1165 $fileId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File', $value, 'id', 'uri');
1167 $url = self
::getFileURL($entityId, $field['id'], $fileId);
1169 $display = $url['file_url'];
1173 // In other contexts show a paperclip icon
1174 if (CRM_Utils_Rule
::integer($value)) {
1175 $icons = CRM_Core_BAO_File
::paperIconAttachment('*', $value);
1176 $display = $icons[$value] . civicrm_api3('File', 'getvalue', ['return' => "description", 'id' => $value]);
1179 //CRM-18396, if filename is passed instead
1187 $display = $display ?
"<a href=\"$display\" target=\"_blank\">$display</a>" : $display;
1191 $display = nl2br($display);
1195 if ($field['data_type'] == 'Money' && isset($value)) {
1196 // $value can also be an array(while using IN operator from search builder or api).
1197 foreach ((array) $value as $val) {
1198 $disp[] = CRM_Utils_Money
::format($val, NULL, NULL, TRUE);
1200 $display = implode(', ', $disp);
1208 * Set default values for custom data used in profile.
1210 * @param int $customFieldId
1212 * @param string $elementName
1213 * Custom field name.
1214 * @param array $defaults
1215 * Associated array of fields.
1216 * @param int $contactId
1220 * @param mixed $value
1221 * If passed - dont fetch value from db,.
1222 * just format the given value
1224 public static function setProfileDefaults(
1232 //get the type of custom field
1233 $customField = new CRM_Core_BAO_CustomField();
1234 $customField->id
= $customFieldId;
1235 $customField->find(TRUE);
1238 if ($mode == CRM_Profile_Form
::MODE_CREATE
) {
1239 $value = $customField->default_value
;
1243 if (!isset($value)) {
1244 $info = self
::getTableColumnGroup($customFieldId);
1245 $query = "SELECT {$info[0]}.{$info[1]} as value FROM {$info[0]} WHERE {$info[0]}.entity_id = {$contactId}";
1246 $result = CRM_Core_DAO
::executeQuery($query);
1247 if ($result->fetch()) {
1248 $value = $result->value
;
1252 if ($customField->data_type
== 'Country') {
1254 $config = CRM_Core_Config
::singleton();
1255 if ($config->defaultContactCountry
) {
1256 $value = $config->defaultContactCountry();
1262 //set defaults if mode is registration
1263 if (!trim($value) &&
1265 (!in_array($mode, array(CRM_Profile_Form
::MODE_EDIT
, CRM_Profile_Form
::MODE_SEARCH
)))
1267 $value = $customField->default_value
;
1270 if ($customField->data_type
== 'Money' && isset($value)) {
1271 $value = number_format($value, 2);
1273 switch ($customField->html_type
) {
1275 case 'Multi-Select':
1276 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldId, FALSE);
1277 $defaults[$elementName] = array();
1278 $checkedValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1279 substr($value, 1, -1)
1281 foreach ($customOption as $val) {
1282 if (in_array($val['value'], $checkedValue)) {
1283 if ($customField->html_type
== 'CheckBox') {
1284 $defaults[$elementName][$val['value']] = 1;
1286 elseif ($customField->html_type
== 'Multi-Select') {
1287 $defaults[$elementName][$val['value']] = $val['value'];
1294 $defaults[$elementName] = $value;
1301 * @param int $contactID
1303 * @param int $fileID
1304 * @param bool $absolute
1306 * @param string $multiRecordWhereClause
1310 public static function getFileURL($contactID, $cfID, $fileID = NULL, $absolute = FALSE, $multiRecordWhereClause = NULL) {
1313 $params = array('id' => $cfID);
1314 $defaults = array();
1315 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $defaults);
1316 $columnName = $defaults['column_name'];
1318 //table name of custom data
1319 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup',
1320 $defaults['custom_group_id'],
1324 //query to fetch id from civicrm_file
1325 if ($multiRecordWhereClause) {
1326 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID} AND {$multiRecordWhereClause}";
1329 $query = "SELECT {$columnName} FROM {$tableName} where entity_id = {$contactID}";
1331 $fileID = CRM_Core_DAO
::singleValueQuery($query);
1336 $fileType = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1341 $result['file_id'] = $fileID;
1343 if ($fileType == 'image/jpeg' ||
1344 $fileType == 'image/pjpeg' ||
1345 $fileType == 'image/gif' ||
1346 $fileType == 'image/x-png' ||
1347 $fileType == 'image/png'
1349 $entityId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_EntityFile',
1354 list($path) = CRM_Core_BAO_File
::path($fileID, $entityId);
1355 $fileHash = CRM_Core_BAO_File
::generateFileHash($entityId, $fileID);
1356 $url = CRM_Utils_System
::url('civicrm/file',
1357 "reset=1&id=$fileID&eid=$entityId&fcs=$fileHash",
1358 $absolute, NULL, TRUE, TRUE
1360 $result['file_url'] = CRM_Utils_File
::getFileURL($path, $fileType, $url);
1362 // for non image files
1364 $uri = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_File',
1368 $fileHash = CRM_Core_BAO_File
::generateFileHash($contactID, $fileID);
1369 $url = CRM_Utils_System
::url('civicrm/file',
1370 "reset=1&id=$fileID&eid=$contactID&fcs=$fileHash",
1371 $absolute, NULL, TRUE, TRUE
1373 $result['file_url'] = CRM_Utils_File
::getFileURL($uri, $fileType, $url);
1381 * Format custom fields before inserting.
1383 * @param int $customFieldId
1385 * @param array $customFormatted
1387 * @param mixed $value
1388 * Value of custom field.
1389 * @param string $customFieldExtend
1390 * Custom field extends.
1391 * @param int $customValueId
1392 * Custom option value id.
1393 * @param int $entityId
1394 * Entity id (contribution, membership...).
1395 * @param bool $inline
1396 * Consider inline custom groups only.
1397 * @param bool $checkPermission
1398 * If false, do not include permissioning clause.
1399 * @param bool $includeViewOnly
1400 * If true, fields marked 'View Only' are included. Required for APIv3.
1402 * @return array|NULL
1403 * formatted custom field array
1405 public static function formatCustomField(
1406 $customFieldId, &$customFormatted, $value,
1407 $customFieldExtend, $customValueId = NULL,
1410 $checkPermission = TRUE,
1411 $includeViewOnly = FALSE
1413 //get the custom fields for the entity
1414 //subtype and basic type
1415 $customDataSubType = NULL;
1416 if ($customFieldExtend) {
1417 // This is the case when getFieldsForImport() requires fields
1418 // of subtype and its parent.CRM-5143
1419 // CRM-16065 - Custom field set data not being saved if contact has more than one contact sub type
1420 $customDataSubType = array_intersect(CRM_Contact_BAO_ContactType
::subTypes(), (array) $customFieldExtend);
1421 if (!empty($customDataSubType) && is_array($customDataSubType)) {
1422 $customFieldExtend = CRM_Contact_BAO_ContactType
::getBasicType($customDataSubType);
1423 if (is_array($customFieldExtend)) {
1424 $customFieldExtend = array_unique(array_values($customFieldExtend));
1429 $customFields = CRM_Core_BAO_CustomField
::getFields($customFieldExtend,
1439 if (!array_key_exists($customFieldId, $customFields)) {
1443 // return if field is a 'code' field
1444 if (!$includeViewOnly && !empty($customFields[$customFieldId]['is_view'])) {
1448 list($tableName, $columnName, $groupID) = self
::getTableColumnGroup($customFieldId);
1450 if (!$customValueId &&
1451 // we always create new entites for is_multiple unless specified
1452 !$customFields[$customFieldId]['is_multiple'] &&
1458 WHERE entity_id={$entityId}";
1460 $customValueId = CRM_Core_DAO
::singleValueQuery($query);
1463 //fix checkbox, now check box always submits values
1464 if ($customFields[$customFieldId]['html_type'] == 'CheckBox') {
1466 // Note that only during merge this is not an array, and you can directly use value
1467 if (is_array($value)) {
1468 $selectedValues = array();
1469 foreach ($value as $selId => $val) {
1471 $selectedValues[] = $selId;
1474 if (!empty($selectedValues)) {
1475 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1477 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1486 if ($customFields[$customFieldId]['html_type'] == 'Multi-Select') {
1488 $value = CRM_Utils_Array
::implodePadded($value);
1495 if (($customFields[$customFieldId]['html_type'] == 'Multi-Select' ||
1496 $customFields[$customFieldId]['html_type'] == 'CheckBox'
1498 $customFields[$customFieldId]['data_type'] == 'String' &&
1499 !empty($customFields[$customFieldId]['text_length']) &&
1502 // lets make sure that value is less than the length, else we'll
1503 // be losing some data, CRM-7481
1504 if (strlen($value) >= $customFields[$customFieldId]['text_length']) {
1505 // need to do a few things here
1507 // 1. lets find a new length
1508 $newLength = $customFields[$customFieldId]['text_length'];
1509 $minLength = strlen($value);
1510 while ($newLength < $minLength) {
1511 $newLength = $newLength * 2;
1514 // set the custom field meta data to have a length larger than value
1515 // alter the custom value table column to match this length
1516 CRM_Core_BAO_SchemaHandler
::alterFieldLength($customFieldId, $tableName, $columnName, $newLength);
1521 if ($customFields[$customFieldId]['data_type'] == 'Date') {
1522 if (!CRM_Utils_System
::isNull($value)) {
1523 $format = $customFields[$customFieldId]['date_format'];
1524 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, 'YmdHis', $format);
1529 if ($customFields[$customFieldId]['data_type'] == 'Float' ||
1530 $customFields[$customFieldId]['data_type'] == 'Money'
1536 if ($customFields[$customFieldId]['data_type'] == 'Money') {
1537 $value = CRM_Utils_Rule
::cleanMoney($value);
1541 if (($customFields[$customFieldId]['data_type'] == 'StateProvince' ||
1542 $customFields[$customFieldId]['data_type'] == 'Country'
1552 if ($customFields[$customFieldId]['data_type'] == 'File') {
1553 if (empty($value)) {
1557 $config = CRM_Core_Config
::singleton();
1559 // If we are already passing the file id as a value then retrieve and set the file data
1560 if (CRM_Utils_Rule
::integer($value)) {
1561 $fileDAO = new CRM_Core_DAO_File();
1562 $fileDAO->id
= $value;
1563 $fileDAO->find(TRUE);
1566 $fName = $fileDAO->uri
;
1567 $mimeType = $fileDAO->mime_type
;
1571 $fName = $value['name'];
1572 $mimeType = $value['type'];
1575 $filename = pathinfo($fName, PATHINFO_BASENAME
);
1577 // rename this file to go into the secure directory only if
1578 // user has uploaded new file not existing verfied on the basis of $fileID
1579 if (empty($fileID) && !rename($fName, $config->customFileUploadDir
. $filename)) {
1580 CRM_Core_Error
::statusBounce(ts('Could not move custom file to custom upload directory'));
1583 if ($customValueId && empty($fileID)) {
1588 $params = array(1 => array($customValueId, 'Integer'));
1589 $fileID = CRM_Core_DAO
::singleValueQuery($query, $params);
1592 $fileDAO = new CRM_Core_DAO_File();
1595 $fileDAO->id
= $fileID;
1598 $fileDAO->uri
= $filename;
1599 $fileDAO->mime_type
= $mimeType;
1600 $fileDAO->upload_date
= date('YmdHis');
1602 $fileID = $fileDAO->id
;
1606 if (!is_array($customFormatted)) {
1607 $customFormatted = array();
1610 if (!array_key_exists($customFieldId, $customFormatted)) {
1611 $customFormatted[$customFieldId] = array();
1615 if ($customValueId) {
1616 $index = $customValueId;
1619 if (!array_key_exists($index, $customFormatted[$customFieldId])) {
1620 $customFormatted[$customFieldId][$index] = array();
1622 $customFormatted[$customFieldId][$index] = array(
1623 'id' => $customValueId > 0 ?
$customValueId : NULL,
1625 'type' => $customFields[$customFieldId]['data_type'],
1626 'custom_field_id' => $customFieldId,
1627 'custom_group_id' => $groupID,
1628 'table_name' => $tableName,
1629 'column_name' => $columnName,
1630 'file_id' => $fileID,
1631 'is_multiple' => $customFields[$customFieldId]['is_multiple'],
1634 //we need to sort so that custom fields are created in the order of entry
1635 krsort($customFormatted[$customFieldId]);
1636 return $customFormatted;
1640 * Get default custom table schema.
1642 * @param array $params
1646 public static function defaultCustomTableSchema($params) {
1647 // add the id and extends_id
1649 'name' => $params['name'],
1650 'is_multiple' => $params['is_multiple'],
1651 'attributes' => "ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci",
1655 'type' => 'int unsigned',
1658 'attributes' => 'AUTO_INCREMENT',
1659 'comment' => 'Default MySQL primary key',
1662 'name' => 'entity_id',
1663 'type' => 'int unsigned',
1665 'comment' => 'Table that this extends',
1666 'fk_table_name' => $params['extends_name'],
1667 'fk_field_name' => 'id',
1668 'fk_attributes' => 'ON DELETE CASCADE',
1673 if (!$params['is_multiple']) {
1674 $table['indexes'] = array(
1677 'field_name_1' => 'entity_id',
1685 * Create custom field.
1687 * @param CRM_Core_DAO_CustomField $field
1688 * @param string $operation
1690 public static function createField($field, $operation) {
1691 $sql = str_repeat(' ', 8);
1692 $tableName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $field->custom_group_id
, 'table_name');
1693 $sql .= "ALTER TABLE " . $tableName;
1694 $sql .= self
::getAlterFieldSQL($field, $operation);
1696 // CRM-7007: do not i18n-rewrite this query
1697 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, FALSE, FALSE);
1699 $config = CRM_Core_Config
::singleton();
1700 if ($config->logging
) {
1701 // CRM-16717 not sure why this was originally limited to add.
1702 // For example custom tables can have field length changes - which need to flow through to logging.
1703 // Are there any modifies we DON'T was to call this function for (& shouldn't it be clever enough to cope?)
1704 if ($operation === 'add' ||
$operation === 'modify') {
1705 $logging = new CRM_Logging_Schema();
1706 $logging->fixSchemaDifferencesFor($tableName, [trim(strtoupper($operation)) => [$field->column_name
]]);
1710 Civi
::service('sql_triggers')->rebuild($tableName, TRUE);
1714 * @param CRM_Core_DAO_CustomField $field
1715 * @param string $operation
1719 public static function getAlterFieldSQL($field, $operation) {
1720 $indexExist = $operation === 'add' ?
FALSE : CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $field->id
, 'is_searchable');
1721 $params = self
::prepareCreateParams($field, $operation);
1722 // Let's suppress the required flag, since that can cause an sql issue... for unknown reasons since we are calling
1723 // a function only used by Custom Field creation...
1724 $params['required'] = FALSE;
1725 return CRM_Core_BAO_SchemaHandler
::getFieldAlterSQL($params, $indexExist);
1729 * Determine whether it would be safe to move a field.
1731 * @param int $fieldID
1732 * FK to civicrm_custom_field.
1733 * @param int $newGroupID
1734 * FK to civicrm_custom_group.
1737 * array(string) or TRUE
1739 public static function _moveFieldValidate($fieldID, $newGroupID) {
1742 $field = new CRM_Core_DAO_CustomField();
1743 $field->id
= $fieldID;
1744 if (!$field->find(TRUE)) {
1745 $errors['fieldID'] = 'Invalid ID for custom field';
1749 $oldGroup = new CRM_Core_DAO_CustomGroup();
1750 $oldGroup->id
= $field->custom_group_id
;
1751 if (!$oldGroup->find(TRUE)) {
1752 $errors['fieldID'] = 'Invalid ID for old custom group';
1756 $newGroup = new CRM_Core_DAO_CustomGroup();
1757 $newGroup->id
= $newGroupID;
1758 if (!$newGroup->find(TRUE)) {
1759 $errors['newGroupID'] = 'Invalid ID for new custom group';
1765 FROM civicrm_custom_field a
1766 INNER JOIN civicrm_custom_field b
1768 AND a.label = b.label
1769 AND b.custom_group_id = %2
1772 1 => array($field->id
, 'Integer'),
1773 2 => array($newGroup->id
, 'Integer'),
1775 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
1777 $errors['newGroupID'] = ts('A field of the same label exists in the destination group');
1780 $tableName = $oldGroup->table_name
;
1781 $columnName = $field->column_name
;
1786 WHERE $columnName is not null
1788 $count = CRM_Core_DAO
::singleValueQuery($query);
1792 FROM civicrm_custom_group
1793 WHERE id IN ( %1, %2 )
1796 1 => array($oldGroup->id
, 'Integer'),
1797 2 => array($newGroup->id
, 'Integer'),
1800 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1802 while ($dao->fetch()) {
1803 $extends[] = $dao->extends;
1805 if ($extends[0] != $extends[1]) {
1806 $errors['newGroupID'] = ts('The destination group extends a different entity type.');
1810 return empty($errors) ?
TRUE : $errors;
1814 * Move a custom data field from one group (table) to another.
1816 * @param int $fieldID
1817 * FK to civicrm_custom_field.
1818 * @param int $newGroupID
1819 * FK to civicrm_custom_group.
1821 public static function moveField($fieldID, $newGroupID) {
1822 $validation = self
::_moveFieldValidate($fieldID, $newGroupID);
1823 if (TRUE !== $validation) {
1824 CRM_Core_Error
::fatal(implode(' ', $validation));
1826 $field = new CRM_Core_DAO_CustomField();
1827 $field->id
= $fieldID;
1830 $newGroup = new CRM_Core_DAO_CustomGroup();
1831 $newGroup->id
= $newGroupID;
1832 $newGroup->find(TRUE);
1834 $oldGroup = new CRM_Core_DAO_CustomGroup();
1835 $oldGroup->id
= $field->custom_group_id
;
1836 $oldGroup->find(TRUE);
1839 $add->custom_group_id
= $newGroup->id
;
1840 self
::createField($add, 'add');
1842 $sql = "INSERT INTO {$newGroup->table_name} (entity_id, {$field->column_name})
1843 SELECT entity_id, {$field->column_name} FROM {$oldGroup->table_name}
1844 ON DUPLICATE KEY UPDATE {$field->column_name} = {$oldGroup->table_name}.{$field->column_name}
1846 CRM_Core_DAO
::executeQuery($sql);
1849 $del->custom_group_id
= $oldGroup->id
;
1850 self
::createField($del, 'delete');
1854 CRM_Utils_System
::flushCache();
1858 * Create an option value for a custom field option group ID.
1860 * @param array $params
1861 * @param string $value
1862 * @param \CRM_Core_DAO_OptionGroup $optionGroup
1863 * @param string $optionName
1864 * @param string $dataType
1866 protected static function createOptionValue(&$params, $value, CRM_Core_DAO_OptionGroup
$optionGroup, $optionName, $dataType) {
1867 if (strlen(trim($value))) {
1868 $optionValue = new CRM_Core_DAO_OptionValue();
1869 $optionValue->option_group_id
= $optionGroup->id
;
1870 $optionValue->label
= $params['option_label'][$optionName];
1871 $optionValue->name
= CRM_Utils_String
::titleToVar($params['option_label'][$optionName]);
1872 switch ($dataType) {
1874 $optionValue->value
= CRM_Utils_Rule
::cleanMoney($value);
1878 $optionValue->value
= intval($value);
1882 $optionValue->value
= floatval($value);
1886 $optionValue->value
= trim($value);
1889 $optionValue->weight
= $params['option_weight'][$optionName];
1890 $optionValue->is_active
= CRM_Utils_Array
::value($optionName, $params['option_status'], FALSE);
1891 $optionValue->save();
1896 * Prepare for the create operation.
1898 * Munge params, create the option values if needed.
1900 * This could be called by a single create or a batchCreate.
1902 * @param array $params
1906 protected static function prepareCreate($params) {
1907 $op = empty($params['id']) ?
'create' : 'edit';
1908 CRM_Utils_Hook
::pre($op, 'CustomField', CRM_Utils_Array
::value('id', $params), $params);
1909 $params['is_append_field_id_to_column_name'] = !isset($params['column_name']);
1910 if ($op === 'create') {
1911 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
1912 if (!isset($params['column_name'])) {
1913 // if add mode & column_name not present, calculate it.
1914 $params['column_name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 32));
1916 if (!isset($params['name'])) {
1917 $params['name'] = CRM_Utils_String
::munge($params['label'], '_', 64);
1921 $params['column_name'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1927 switch (CRM_Utils_Array
::value('html_type', $params)) {
1929 if (empty($params['date_format'])) {
1930 $config = CRM_Core_Config
::singleton();
1931 $params['date_format'] = $config->dateInputFormat
;
1936 case 'Multi-Select':
1937 if (isset($params['default_checkbox_option'])) {
1938 $tempArray = array_keys($params['default_checkbox_option']);
1940 foreach ($tempArray as $k => $v) {
1941 if ($params['option_value'][$v]) {
1942 $defaultArray[] = $params['option_value'][$v];
1946 if (!empty($defaultArray)) {
1947 // also add the separator before and after the value per new convention (CRM-1604)
1948 $params['default_value'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $defaultArray) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1952 if (!empty($params['default_option']) && isset($params['option_value'][$params['default_option']])
1954 $params['default_value'] = $params['option_value'][$params['default_option']];
1960 $htmlType = CRM_Utils_Array
::value('html_type', $params);
1961 $dataType = CRM_Utils_Array
::value('data_type', $params);
1962 $allowedOptionTypes = ['String', 'Int', 'Float', 'Money'];
1964 // create any option group & values if required
1965 if ($htmlType != 'Text' && in_array($dataType, $allowedOptionTypes)
1967 //CRM-16659: if option_value then create an option group for this custom field.
1968 if ($params['option_type'] == 1 && (empty($params['option_group_id']) ||
!empty($params['option_value']))) {
1969 // first create an option group for this custom group
1970 $optionGroup = new CRM_Core_DAO_OptionGroup();
1971 $optionGroup->name
= "{$params['column_name']}_" . date('YmdHis');
1972 $optionGroup->title
= $params['label'];
1973 $optionGroup->is_active
= 1;
1974 // Don't set reserved as it's not a built-in option group and may be useful for other custom fields.
1975 $optionGroup->is_reserved
= 0;
1976 $optionGroup->data_type
= $dataType;
1977 $optionGroup->save();
1978 $params['option_group_id'] = $optionGroup->id
;
1979 if (!empty($params['option_value']) && is_array($params['option_value'])) {
1980 foreach ($params['option_value'] as $k => $v) {
1981 self
::createOptionValue($params, $v, $optionGroup, $k, $dataType);
1987 // check for orphan option groups
1988 if (!empty($params['option_group_id'])) {
1989 if (!empty($params['id'])) {
1990 self
::fixOptionGroups($params['id'], $params['option_group_id']);
1993 // if we do not have a default value
1994 // retrieve it from one of the other custom fields which use this option group
1995 if (empty($params['default_value'])) {
1996 //don't insert only value separator as default value, CRM-4579
1997 $defaultValue = self
::getOptionGroupDefault($params['option_group_id'],
2001 if (!CRM_Utils_System
::isNull(explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2005 $params['default_value'] = $defaultValue;
2010 // since we need to save option group id :)
2011 if (!isset($params['attributes']) && strtolower($htmlType) == 'textarea') {
2012 $params['attributes'] = 'rows=4, cols=60';
2018 * Create database entry for custom field and related option groups.
2020 * @param array $params
2022 * @return CRM_Core_DAO_CustomField
2024 protected static function createCustomFieldRecord($params) {
2025 $transaction = new CRM_Core_Transaction();
2026 $params = self
::prepareCreate($params);
2028 $customField = new CRM_Core_DAO_CustomField();
2029 $customField->copyValues($params);
2030 $customField->save();
2032 //create/drop the index when we toggle the is_searchable flag
2033 $op = empty($params['id']) ?
'add' : 'modify';
2034 if ($op !== 'modify') {
2035 if ($params['is_append_field_id_to_column_name']) {
2036 $params['column_name'] .= "_{$customField->id}";
2038 $customField->column_name
= $params['column_name'];
2039 $customField->save();
2042 // complete transaction - note that any table alterations include an implicit commit so this is largely meaningless.
2043 $transaction->commit();
2045 // make sure all values are present in the object for further processing
2046 $customField->find(TRUE);
2047 return $customField;
2051 * Move custom data from one contact to another.
2053 * This is currently the start of a refactoring. The theory is each
2054 * entity could have a 'move' function with a DAO default one to fall back on.
2056 * At the moment this only does a small part of the process - ie deleting a file field that
2057 * is about to be overwritten. However, the goal is the whole process around the move for
2058 * custom data should be in here.
2060 * This is currently called by the merge class but it makes sense that api could
2061 * expose move actions as moving (e.g) contributions feels like a common
2062 * ask that should be handled by the form layer.
2064 * @param int $oldContactID
2065 * @param int $newContactID
2066 * @param int[] $fieldIDs
2067 * Optional list field ids to move.
2069 * @throws \CiviCRM_API3_Exception
2070 * @throws \Exception
2072 public function move($oldContactID, $newContactID, $fieldIDs) {
2073 if (empty($fieldIDs)) {
2076 $fields = civicrm_api3('CustomField', 'get', ['id' => ['IN' => $fieldIDs], 'return' => ['custom_group_id.is_multiple', 'custom_group_id.table_name', 'column_name', 'data_type'], 'options' => ['limit' => 0]])['values'];
2078 foreach ($fieldIDs as $fieldID) {
2079 $return[] = 'custom_' . $fieldID;
2081 $oldContact = civicrm_api3('Contact', 'getsingle', ['id' => $oldContactID, 'return' => $return]);
2082 $newContact = civicrm_api3('Contact', 'getsingle', ['id' => $newContactID, 'return' => $return]);
2084 // The moveAllBelongings function has functionality to move custom fields. It doesn't work very well...
2085 // @todo handle all fields here but more immediately Country since that is broken at the moment.
2086 $fieldTypesNotHandledInMergeAttempt = ['File'];
2087 foreach ($fields as $field) {
2088 $isMultiple = !empty($field['custom_group_id.is_multiple']);
2089 if ($field['data_type'] === 'File' && !$isMultiple) {
2090 if (!empty($oldContact['custom_' . $field['id']]) && !empty($newContact['custom_' . $field['id']])) {
2091 CRM_Core_BAO_File
::deleteFileReferences($oldContact['custom_' . $field['id']], $oldContactID, $field['id']);
2093 if (!empty($oldContact['custom_' . $field['id']])) {
2094 CRM_Core_DAO
::executeQuery("
2095 UPDATE civicrm_entity_file
2096 SET entity_id = $newContactID
2097 WHERE file_id = {$oldContact['custom_' . $field['id']]}"
2101 if (in_array($field['data_type'], $fieldTypesNotHandledInMergeAttempt) && !$isMultiple) {
2102 CRM_Core_DAO
::executeQuery(
2103 "INSERT INTO {$field['custom_group_id.table_name']} (entity_id, {$field['column_name']})
2104 VALUES ($newContactID, {$oldContact['custom_' . $field['id']]})
2105 ON DUPLICATE KEY UPDATE
2106 {$field['column_name']} = {$oldContact['custom_' . $field['id']]}
2113 * Get the database table name and column name for a custom field.
2115 * @param int $fieldID
2116 * The fieldID of the custom field.
2117 * @param bool $force
2118 * Force the sql to be run again (primarily used for tests).
2121 * fatal is fieldID does not exists, else array of tableName, columnName
2122 * @throws \Exception
2124 public static function getTableColumnGroup($fieldID, $force = FALSE) {
2125 $cacheKey = "CRM_Core_DAO_CustomField_CustomGroup_TableColumn_{$fieldID}";
2126 $cache = CRM_Utils_Cache
::singleton();
2127 $fieldValues = $cache->get($cacheKey);
2128 if (empty($fieldValues) ||
$force) {
2130 SELECT cg.table_name, cf.column_name, cg.id
2131 FROM civicrm_custom_group cg,
2132 civicrm_custom_field cf
2133 WHERE cf.custom_group_id = cg.id
2135 $params = array(1 => array($fieldID, 'Integer'));
2136 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2138 if (!$dao->fetch()) {
2139 CRM_Core_Error
::fatal();
2141 $fieldValues = array($dao->table_name
, $dao->column_name
, $dao->id
);
2142 $cache->set($cacheKey, $fieldValues);
2144 return $fieldValues;
2148 * Get custom option groups.
2150 * @deprecated Use the API OptionGroup.get
2152 * @param array $includeFieldIds
2153 * Ids of custom fields for which option groups must be included.
2155 * Currently this is required in the cases where option groups are to be included
2156 * for inactive fields : CRM-5369
2160 public static function customOptionGroup($includeFieldIds = NULL) {
2161 static $customOptionGroup = NULL;
2163 $cacheKey = (empty($includeFieldIds)) ?
'onlyActive' : 'force';
2164 if ($cacheKey == 'force') {
2165 $customOptionGroup[$cacheKey] = NULL;
2168 if (empty($customOptionGroup[$cacheKey])) {
2169 $whereClause = '( g.is_active = 1 AND f.is_active = 1 )';
2171 //support for single as well as array format.
2172 if (!empty($includeFieldIds)) {
2173 if (is_array($includeFieldIds)) {
2174 $includeFieldIds = implode(',', $includeFieldIds);
2176 $whereClause .= "OR f.id IN ( $includeFieldIds )";
2180 SELECT g.id, g.title
2181 FROM civicrm_option_group g
2182 INNER JOIN civicrm_custom_field f ON ( g.id = f.option_group_id )
2183 WHERE {$whereClause}";
2185 $dao = CRM_Core_DAO
::executeQuery($query);
2186 while ($dao->fetch()) {
2187 $customOptionGroup[$cacheKey][$dao->id
] = $dao->title
;
2191 return $customOptionGroup[$cacheKey];
2195 * Get defaults for new entity.
2199 public static function getDefaults() {
2201 'is_required' => FALSE,
2202 'is_searchable' => FALSE,
2203 'in_selector' => FALSE,
2204 'is_search_range' => FALSE,
2205 //CRM-15792 - Custom field gets disabled if is_active not set
2206 // this would ideally be a mysql default.
2207 'is_active' => TRUE,
2213 * Fix orphan groups.
2215 * @param int $customFieldId
2217 * @param int $optionGroupId
2220 public static function fixOptionGroups($customFieldId, $optionGroupId) {
2221 // check if option group belongs to any custom Field else delete
2222 // get the current option group
2223 $currentOptionGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
2227 // get the updated option group
2228 // if both are same return
2229 if (!$currentOptionGroupId ||
$currentOptionGroupId == $optionGroupId) {
2233 // check if option group is related to any other field
2234 self
::checkOptionGroup($currentOptionGroupId);
2238 * Check if option group is related to more than one custom field.
2240 * @param int $optionGroupId
2243 public static function checkOptionGroup($optionGroupId) {
2246 FROM civicrm_custom_field
2247 WHERE option_group_id = {$optionGroupId}";
2249 $count = CRM_Core_DAO
::singleValueQuery($query);
2252 //delete the option group
2253 CRM_Core_BAO_OptionGroup
::del($optionGroupId);
2258 * Get option group default.
2260 * @param int $optionGroupId
2261 * @param string $htmlType
2263 * @return null|string
2265 public static function getOptionGroupDefault($optionGroupId, $htmlType) {
2267 SELECT default_value, html_type
2268 FROM civicrm_custom_field
2269 WHERE option_group_id = {$optionGroupId}
2270 AND default_value IS NOT NULL
2271 ORDER BY html_type";
2273 $dao = CRM_Core_DAO
::executeQuery($query);
2274 $defaultValue = NULL;
2275 $defaultHTMLType = NULL;
2276 while ($dao->fetch()) {
2277 if ($dao->html_type
== $htmlType) {
2278 return $dao->default_value
;
2280 if ($defaultValue == NULL) {
2281 $defaultValue = $dao->default_value
;
2282 $defaultHTMLType = $dao->html_type
;
2286 // some conversions are needed if either the old or new has a html type which has potential
2287 // multiple default values.
2288 if (($htmlType == 'CheckBox' ||
$htmlType == 'Multi-Select') &&
2289 ($defaultHTMLType != 'CheckBox' && $defaultHTMLType != 'Multi-Select')
2291 $defaultValue = CRM_Core_DAO
::VALUE_SEPARATOR
. $defaultValue . CRM_Core_DAO
::VALUE_SEPARATOR
;
2293 elseif (($defaultHTMLType == 'CheckBox' ||
$defaultHTMLType == 'Multi-Select') &&
2294 ($htmlType != 'CheckBox' && $htmlType != 'Multi-Select')
2296 $defaultValue = substr($defaultValue, 1, -1);
2297 $values = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2298 substr($defaultValue, 1, -1)
2300 $defaultValue = $values[0];
2303 return $defaultValue;
2307 * Post process function.
2309 * @param array $params
2310 * @param int $entityID
2311 * @param string $customFieldExtends
2312 * @param bool $inline
2313 * @param bool $checkPermissions
2317 public static function postProcess(
2320 $customFieldExtends,
2322 $checkPermissions = TRUE
2324 $customData = array();
2326 foreach ($params as $key => $value) {
2327 if ($customFieldInfo = CRM_Core_BAO_CustomField
::getKeyID($key, TRUE)) {
2329 // for autocomplete transfer hidden value instead of label
2330 if ($params[$key] && isset($params[$key . '_id'])) {
2331 $value = $params[$key . '_id'];
2334 // we need to append time with date
2335 if ($params[$key] && isset($params[$key . '_time'])) {
2336 $value .= ' ' . $params[$key . '_time'];
2339 CRM_Core_BAO_CustomField
::formatCustomField($customFieldInfo[0],
2342 $customFieldExtends,
2343 $customFieldInfo[1],
2354 * Get custom field ID from field/group name/title.
2356 * @param string $fieldName Field name or label
2357 * @param string|null $groupName (Optional) Group name or label
2358 * @param bool $fullString Whether to return "custom_123" or "123"
2360 * @return string|int|null
2361 * @throws \CiviCRM_API3_Exception
2363 public static function getCustomFieldID($fieldName, $groupName = NULL, $fullString = FALSE) {
2364 $cacheKey = $groupName . '.' . $fieldName;
2365 if (!isset(Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey])) {
2366 $customFieldParams = [
2367 'name' => $fieldName,
2368 'label' => $fieldName,
2369 'options' => ['or' => [["name", "label"]]],
2373 $customFieldParams['custom_group_id.name'] = $groupName;
2374 $customFieldParams['custom_group_id.title'] = $groupName;
2375 $customFieldParams['options'] = ['or' => [["name", "label"], ["custom_group_id.name", "custom_group_id.title"]]];
2378 $field = civicrm_api3('CustomField', 'get', $customFieldParams);
2380 if (empty($field['id'])) {
2381 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = NULL;
2382 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = NULL;
2385 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'] = $field['id'];
2386 Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'] = 'custom_' . $field['id'];
2391 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['string'];
2393 return Civi
::$statics['CRM_Core_BAO_CustomField'][$cacheKey]['id'];
2397 * Given ID of a custom field, return its name as well as the name of the custom group it belongs to.
2403 public static function getNameFromID($ids) {
2404 if (is_array($ids)) {
2405 $ids = implode(',', $ids);
2408 SELECT f.id, f.name AS field_name, f.label AS field_label, g.name AS group_name, g.title AS group_title
2409 FROM civicrm_custom_field f
2410 INNER JOIN civicrm_custom_group g ON f.custom_group_id = g.id
2411 WHERE f.id IN ($ids)";
2413 $dao = CRM_Core_DAO
::executeQuery($sql);
2415 while ($dao->fetch()) {
2416 $result[$dao->id
] = array(
2417 'field_name' => $dao->field_name
,
2418 'field_label' => $dao->field_label
,
2419 'group_name' => $dao->group_name
,
2420 'group_title' => $dao->group_title
,
2427 * Validate custom data.
2429 * @param array $params
2430 * Custom data submitted.
2431 * ie array( 'custom_1' => 'validate me' );
2434 * validation errors.
2436 public static function validateCustomData($params) {
2438 if (!is_array($params) ||
empty($params)) {
2442 //pick up profile fields.
2443 $profileFields = array();
2444 $ufGroupId = CRM_Utils_Array
::value('ufGroupId', $params);
2446 $profileFields = CRM_Core_BAO_UFGroup
::getFields($ufGroupId,
2448 CRM_Core_Action
::VIEW
2452 //lets start w/ params.
2453 foreach ($params as $key => $value) {
2454 $customFieldID = self
::getKeyID($key);
2455 if (!$customFieldID) {
2459 //load the structural info for given field.
2460 $field = new CRM_Core_DAO_CustomField();
2461 $field->id
= $customFieldID;
2462 if (!$field->find(TRUE)) {
2465 $dataType = $field->data_type
;
2467 $profileField = CRM_Utils_Array
::value($key, $profileFields, array());
2468 $fieldTitle = CRM_Utils_Array
::value('title', $profileField);
2469 $isRequired = CRM_Utils_Array
::value('is_required', $profileField);
2471 $fieldTitle = $field->label
;
2474 //no need to validate.
2475 if (CRM_Utils_System
::isNull($value) && !$isRequired) {
2479 //lets validate first for required field.
2480 if ($isRequired && CRM_Utils_System
::isNull($value)) {
2481 $errors[$key] = ts('%1 is a required field.', array(1 => $fieldTitle));
2485 //now time to take care of custom field form rules.
2486 $ruleName = $errorMsg = NULL;
2487 switch ($dataType) {
2489 $ruleName = 'integer';
2490 $errorMsg = ts('%1 must be an integer (whole number).',
2491 array(1 => $fieldTitle)
2496 $ruleName = 'money';
2497 $errorMsg = ts('%1 must in proper money format. (decimal point/comma/space is allowed).',
2498 array(1 => $fieldTitle)
2503 $ruleName = 'numeric';
2504 $errorMsg = ts('%1 must be a number (with or without decimal point).',
2505 array(1 => $fieldTitle)
2510 $ruleName = 'wikiURL';
2511 $errorMsg = ts('%1 must be valid Website.',
2512 array(1 => $fieldTitle)
2517 if ($ruleName && !CRM_Utils_System
::isNull($value)) {
2519 $funName = "CRM_Utils_Rule::{$ruleName}";
2520 if (is_callable($funName)) {
2521 $valid = call_user_func($funName, $value);
2524 $errors[$key] = $errorMsg;
2533 * Is this field a multi record field.
2535 * @param int $customId
2539 public static function isMultiRecordField($customId) {
2540 $isMultipleWithGid = FALSE;
2541 if (!is_numeric($customId)) {
2542 $customId = self
::getKeyID($customId);
2544 if (is_numeric($customId)) {
2545 $sql = "SELECT cg.id cgId
2546 FROM civicrm_custom_group cg
2547 INNER JOIN civicrm_custom_field cf
2548 ON cg.id = cf.custom_group_id
2549 WHERE cf.id = %1 AND cg.is_multiple = 1";
2550 $params[1] = array($customId, 'Integer');
2551 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2552 if ($dao->fetch()) {
2554 $isMultipleWithGid = $dao->cgId
;
2559 return $isMultipleWithGid;
2563 * Does this field type have any select options?
2565 * @param array $field
2569 public static function hasOptions($field) {
2570 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2571 $field = (array) $field;
2572 // This will include boolean fields with Yes/No options.
2573 if (in_array($field['html_type'], ['Radio', 'CheckBox'])) {
2576 // Do this before the "Select" string search because date fields have a "Select Date" html_type
2577 // and contactRef fields have an "Autocomplete-Select" html_type - contacts are an FK not an option list.
2578 if (in_array($field['data_type'], ['ContactReference', 'Date'])) {
2581 if (strpos($field['html_type'], 'Select') !== FALSE) {
2584 return !empty($field['option_group_id']);
2588 * Does this field store a serialized string?
2590 * @param array $field
2594 public static function isSerialized($field) {
2595 // Fields retrieved via api are an array, or from the dao are an object. We'll accept either.
2596 $field = (array) $field;
2597 // 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.
2598 return ($field['html_type'] == 'CheckBox' ||
strpos($field['html_type'], 'Multi') !== FALSE);
2602 * Get api entity for this field
2606 public function getEntity() {
2607 $entity = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->custom_group_id
, 'extends');
2608 return in_array($entity, array('Individual', 'Household', 'Organization')) ?
'Contact' : $entity;
2612 * Set pseudoconstant properties for field metadata.
2614 * @param array $field
2615 * @param string|null $optionGroupName
2617 private static function getOptionsForField(&$field, $optionGroupName) {
2618 if ($optionGroupName) {
2619 $field['pseudoconstant'] = array(
2620 'optionGroupName' => $optionGroupName,
2621 'optionEditPath' => 'civicrm/admin/options/' . $optionGroupName,
2624 elseif ($field['data_type'] == 'Boolean') {
2625 $field['pseudoconstant'] = array(
2626 'callback' => 'CRM_Core_SelectValues::boolean',
2629 elseif ($field['data_type'] == 'Country') {
2630 $field['pseudoconstant'] = array(
2631 'table' => 'civicrm_country',
2632 'keyColumn' => 'id',
2633 'labelColumn' => 'name',
2634 'nameColumn' => 'iso_code',
2637 elseif ($field['data_type'] == 'StateProvince') {
2638 $field['pseudoconstant'] = array(
2639 'table' => 'civicrm_state_province',
2640 'keyColumn' => 'id',
2641 'labelColumn' => 'name',
2647 * @param CRM_Core_DAO_CustomField $field
2648 * @param 'add|modify' $operation
2652 protected static function prepareCreateParams($field, $operation) {
2653 $tableName = CRM_Core_DAO
::getFieldValue(
2654 'CRM_Core_DAO_CustomGroup',
2655 $field->custom_group_id
,
2660 'table_name' => $tableName,
2661 'operation' => $operation,
2662 'name' => $field->column_name
,
2663 'type' => CRM_Core_BAO_CustomValueTable
::fieldToSQLType(
2667 'required' => $field->is_required
,
2668 'searchable' => $field->is_searchable
,
2671 if ($operation == 'delete') {
2672 $fkName = "{$tableName}_{$field->column_name}";
2673 if (strlen($fkName) >= 48) {
2674 $fkName = substr($fkName, 0, 32) . '_' . substr(md5($fkName), 0, 16);
2676 $params['fkName'] = $fkName;
2678 if ($field->data_type
== 'Country' && $field->html_type
== 'Select Country') {
2679 $params['fk_table_name'] = 'civicrm_country';
2680 $params['fk_field_name'] = 'id';
2681 $params['fk_attributes'] = 'ON DELETE SET NULL';
2683 elseif ($field->data_type
== 'Country' && $field->html_type
== 'Multi-Select Country') {
2684 $params['type'] = 'varchar(255)';
2686 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Select State/Province') {
2687 $params['fk_table_name'] = 'civicrm_state_province';
2688 $params['fk_field_name'] = 'id';
2689 $params['fk_attributes'] = 'ON DELETE SET NULL';
2691 elseif ($field->data_type
== 'StateProvince' && $field->html_type
== 'Multi-Select State/Province') {
2692 $params['type'] = 'varchar(255)';
2694 elseif ($field->data_type
== 'File') {
2695 $params['fk_table_name'] = 'civicrm_file';
2696 $params['fk_field_name'] = 'id';
2697 $params['fk_attributes'] = 'ON DELETE SET NULL';
2699 elseif ($field->data_type
== 'ContactReference') {
2700 $params['fk_table_name'] = 'civicrm_contact';
2701 $params['fk_field_name'] = 'id';
2702 $params['fk_attributes'] = 'ON DELETE SET NULL';
2704 if (isset($field->default_value
)) {
2705 $params['default'] = "'{$field->default_value}'";