3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 * form to process actions on the field aspect of Custom
23 class CRM_Custom_Form_Field
extends CRM_Core_Form
{
26 * Constants for number of options for data types of multiple option.
28 const NUM_OPTION
= 11;
31 * The custom group id saved to the session for an update.
38 * The field id, used when editing the field
45 * The default custom data/input types, when editing the field
49 protected $_defaultDataType;
52 * Array of custom field values if update mode.
58 * Array for valid combinations of data_type & html_type
62 private static $_dataTypeValues = NULL;
63 private static $_dataTypeKeys = NULL;
65 private static $_dataToLabels = NULL;
68 * Used for mapping data types to html type options.
70 * Each item in this array corresponds to the same index in the dataType array
73 public static $_dataToHTML = [
78 'CheckBox' => 'CheckBox',
79 'Autocomplete-Select' => 'Autocomplete-Select',
81 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
82 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
83 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
84 ['TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'],
85 ['Date' => 'Select Date'],
87 ['StateProvince' => 'Select State/Province'],
88 ['Country' => 'Select Country'],
91 ['ContactReference' => 'Autocomplete-Select'],
95 * Set variables up before form is built.
99 public function preProcess() {
100 if (!(self
::$_dataTypeKeys)) {
101 self
::$_dataTypeKeys = array_keys(CRM_Core_BAO_CustomField
::dataType());
102 self
::$_dataTypeValues = array_values(CRM_Core_BAO_CustomField
::dataType());
106 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
109 //get the values form db if update.
111 $params = ['id' => $this->_id
];
112 CRM_Core_BAO_CustomField
::retrieve($params, $this->_values
);
113 // note_length is an alias for the text_length field
114 $this->_values
['note_length'] = $this->_values
['text_length'] ??
NULL;
116 $this->_gid
= $this->_values
['custom_group_id'];
120 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this);
123 if ($isReserved = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'is_reserved', 'id')) {
124 CRM_Core_Error
::fatal("You cannot add or edit fields in a reserved custom field-set.");
128 $url = CRM_Utils_System
::url('civicrm/admin/custom/group/field',
129 "reset=1&action=browse&gid={$this->_gid}"
132 $session = CRM_Core_Session
::singleton();
133 $session->pushUserContext($url);
136 if (self
::$_dataToLabels == NULL) {
137 self
::$_dataToLabels = [
139 'Text' => ts('Text'),
140 'Select' => ts('Select'),
141 'Radio' => ts('Radio'),
142 'CheckBox' => ts('CheckBox'),
143 'Autocomplete-Select' => ts('Autocomplete-Select'),
146 'Text' => ts('Text'),
147 'Select' => ts('Select'),
148 'Radio' => ts('Radio'),
151 'Text' => ts('Text'),
152 'Select' => ts('Select'),
153 'Radio' => ts('Radio'),
156 'Text' => ts('Text'),
157 'Select' => ts('Select'),
158 'Radio' => ts('Radio'),
160 ['TextArea' => ts('TextArea'), 'RichTextEditor' => ts('Rich Text Editor')],
161 ['Date' => ts('Select Date')],
162 ['Radio' => ts('Radio')],
163 ['StateProvince' => ts('Select State/Province')],
164 ['Country' => ts('Select Country')],
165 ['File' => ts('Select File')],
166 ['Link' => ts('Link')],
167 ['ContactReference' => ts('Autocomplete-Select')],
173 * Set default values for the form. Note that in edit/view mode
174 * the default values are retrieved from the database
177 * array of default values
179 public function setDefaultValues() {
180 $defaults = $this->_values
;
183 $this->assign('id', $this->_id
);
184 $this->_gid
= $defaults['custom_group_id'];
186 //get the value for state or country
187 if ($defaults['data_type'] == 'StateProvince' &&
188 $stateId = CRM_Utils_Array
::value('default_value', $defaults)
190 $defaults['default_value'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_StateProvince', $stateId);
192 elseif ($defaults['data_type'] == 'Country' &&
193 $countryId = CRM_Utils_Array
::value('default_value', $defaults)
195 $defaults['default_value'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Country', $countryId);
198 if ($defaults['data_type'] == 'ContactReference' && !empty($defaults['filter'])) {
199 $contactRefFilter = 'Advance';
200 if (strpos($defaults['filter'], 'action=lookup') !== FALSE &&
201 strpos($defaults['filter'], 'group=') !== FALSE
203 $filterParts = explode('&', $defaults['filter']);
205 if (count($filterParts) == 2) {
206 $contactRefFilter = 'Group';
207 foreach ($filterParts as $part) {
208 if (strpos($part, 'group=') === FALSE) {
211 $groups = substr($part, strpos($part, '=') +
1);
212 foreach (explode(',', $groups) as $grp) {
213 if (CRM_Utils_Rule
::positiveInteger($grp)) {
214 $defaults['group_id'][] = $grp;
220 $defaults['filter_selected'] = $contactRefFilter;
223 if (!empty($defaults['data_type'])) {
224 $defaultDataType = array_search($defaults['data_type'],
227 $defaultHTMLType = array_search($defaults['html_type'],
228 self
::$_dataToHTML[$defaultDataType]
230 $defaults['data_type'] = [
231 '0' => $defaultDataType,
232 '1' => $defaultHTMLType,
234 $this->_defaultDataType
= $defaults['data_type'];
237 $defaults['option_type'] = 2;
239 $this->assign('changeFieldType', CRM_Custom_Form_ChangeFieldType
::fieldTypeTransitions($this->_values
['data_type'], $this->_values
['html_type']));
242 $defaults['is_active'] = 1;
243 $defaults['option_type'] = 1;
244 $defaults['is_search_range'] = 1;
247 // set defaults for weight.
248 for ($i = 1; $i <= self
::NUM_OPTION
; $i++
) {
249 $defaults['option_status[' . $i . ']'] = 1;
250 $defaults['option_weight[' . $i . ']'] = $i;
251 $defaults['option_value[' . $i . ']'] = $i;
254 if ($this->_action
& CRM_Core_Action
::ADD
) {
255 $fieldValues = ['custom_group_id' => $this->_gid
];
256 $defaults['weight'] = CRM_Utils_Weight
::getDefaultWeight('CRM_Core_DAO_CustomField', $fieldValues);
258 $defaults['text_length'] = 255;
259 $defaults['note_columns'] = 60;
260 $defaults['note_rows'] = 4;
261 $defaults['is_view'] = 0;
264 if (!empty($defaults['html_type'])) {
265 $dontShowLink = substr($defaults['html_type'], -14) == 'State/Province' ||
substr($defaults['html_type'], -7) == 'Country' ?
1 : 0;
268 if (isset($dontShowLink)) {
269 $this->assign('dontShowLink', $dontShowLink);
271 if ($this->_action
& CRM_Core_Action
::ADD
&&
272 CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'is_multiple', 'id')
274 $defaults['in_selector'] = 1;
281 * Build the form object.
285 public function buildQuickForm() {
287 $this->_title
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'title');
288 CRM_Utils_System
::setTitle($this->_title
. ' - ' . ($this->_id ?
ts('Edit Field') : ts('New Field')));
289 $this->assign('gid', $this->_gid
);
292 $this->assign('dataTypeKeys', self
::$_dataTypeKeys);
294 // lets trim all the whitespace
295 $this->applyFilter('__ALL__', 'trim');
297 $attributes = CRM_Core_DAO
::getAttribute('CRM_Core_DAO_CustomField');
303 $attributes['label'],
307 $dt = &self
::$_dataTypeValues;
309 foreach ($dt as $key => $value) {
310 $it[$key] = self
::$_dataToLabels[$key];
312 $sel = &$this->addElement('hierselect',
314 ts('Data and Input Field Type'),
317 $sel->setOptions([$dt, $it]);
319 if (CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'is_multiple')) {
320 $this->add('checkbox', 'in_selector', ts('Display in Table?'));
323 $optionGroupParams = [
326 'options' => ['limit' => 0, 'sort' => "title ASC"],
327 'return' => ['title'],
330 $this->add('checkbox', 'serialize', ts('Multi-Select'));
332 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
333 $this->freeze('data_type');
334 if (!empty($this->_values
['option_group_id'])) {
335 // Before dev/core#155 we didn't set the is_reserved flag properly, which should be handled by the upgrade script...
336 // but it is still possible that existing installs may have optiongroups linked to custom fields that are marked reserved.
337 $optionGroupParams['id'] = $this->_values
['option_group_id'];
338 $optionGroupParams['options']['or'] = [["is_reserved", "id"]];
342 // Retrieve optiongroups for selection list
343 $optionGroupMetadata = civicrm_api3('OptionGroup', 'get', $optionGroupParams);
345 // OptionGroup selection
346 $optionTypes = ['1' => ts('Create a new set of options')];
348 if (!empty($optionGroupMetadata['values'])) {
349 $emptyOptGroup = FALSE;
350 $optionGroups = CRM_Utils_Array
::collect('title', $optionGroupMetadata['values']);
351 $optionTypes['2'] = ts('Reuse an existing set');
355 ts('Multiple Choice Option Sets'),
357 '' => ts('- select -'),
362 // No custom (non-reserved) option groups
363 $emptyOptGroup = TRUE;
366 $element = &$this->addRadio('option_type',
370 'onclick' => "showOptionSelect();",
373 // if empty option group freeze the option type.
374 if ($emptyOptGroup) {
378 $contactGroups = CRM_Core_PseudoConstant
::group();
379 asort($contactGroups);
383 ts('Limit List to Group'),
386 ['multiple' => 'multiple', 'class' => 'crm-select2']
391 ts('Advanced Filter'),
392 $attributes['filter']
395 $this->add('hidden', 'filter_selected', 'Group', ['id' => 'filter_selected']);
397 // form fields of Custom Option rows
399 $_showHide = new CRM_Core_ShowHideBlocks('', '');
400 for ($i = 1; $i <= self
::NUM_OPTION
; $i++
) {
402 //the show hide blocks
403 $showBlocks = 'optionField_' . $i;
405 $_showHide->addHide($showBlocks);
406 if ($i == self
::NUM_OPTION
) {
407 $_showHide->addHide('additionalOption');
411 $_showHide->addShow($showBlocks);
414 $optionAttributes = CRM_Core_DAO
::getAttribute('CRM_Core_DAO_OptionValue');
416 $this->add('text', 'option_label[' . $i . ']', ts('Label'),
417 $optionAttributes['label']
421 $this->add('text', 'option_value[' . $i . ']', ts('Value'),
422 $optionAttributes['value']
426 $this->add('number', "option_weight[$i]", ts('Order'),
427 $optionAttributes['weight']
431 $this->add('checkbox', "option_status[$i]", ts('Active?'));
433 $defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i);
435 //for checkbox handling of default option
436 $this->add('checkbox', "default_checkbox_option[$i]", NULL);
439 //default option selection
440 $this->addGroup($defaultOption, 'default_option');
442 $_showHide->addToTemplate();
444 // text length for alpha numeric data types
447 ts('Database field length'),
448 $attributes['text_length'] +
['min' => 1],
451 $this->addRule('text_length', ts('Value should be a positive number'), 'integer');
455 ts('Dates may be up to'),
456 $attributes['start_date_years'],
461 ts('Dates may be up to'),
462 $attributes['end_date_years'],
466 $this->addRule('start_date_years', ts('Value should be a positive number'), 'integer');
467 $this->addRule('end_date_years', ts('Value should be a positive number'), 'integer');
469 $this->add('select', 'date_format', ts('Date Format'),
470 ['' => ts('- select -')] + CRM_Core_SelectValues
::getDatePluginInputFormats()
473 $this->add('select', 'time_format', ts('Time'),
474 ['' => ts('- none -')] + CRM_Core_SelectValues
::getTimeFormats()
480 ts('Width (columns)') . ' ',
481 $attributes['note_columns'],
486 ts('Height (rows)') . ' ',
487 $attributes['note_rows'],
492 ts('Maximum length') . ' ',
493 // note_length is an alias for the text-length field
494 $attributes['text_length'],
498 $this->addRule('note_columns', ts('Value should be a positive number'), 'positiveInteger');
499 $this->addRule('note_rows', ts('Value should be a positive number'), 'positiveInteger');
500 $this->addRule('note_length', ts('Value should be a positive number'), 'positiveInteger');
503 $this->add('number', 'weight', ts('Order'),
504 $attributes['weight'],
507 $this->addRule('weight', ts('is a numeric field'), 'numeric');
510 $this->add('advcheckbox', 'is_required', ts('Required?'));
512 // checkbox / radio options per line
513 $this->add('number', 'options_per_line', ts('Options Per Line'), ['min' => 0]);
514 $this->addRule('options_per_line', ts('must be a numeric value'), 'numeric');
516 // default value, help pre, help post, mask, attributes, javascript ?
517 $this->add('text', 'default_value', ts('Default Value'),
518 $attributes['default_value']
520 $this->add('textarea', 'help_pre', ts('Field Pre Help'),
521 $attributes['help_pre']
523 $this->add('textarea', 'help_post', ts('Field Post Help'),
524 $attributes['help_post']
526 $this->add('text', 'mask', ts('Mask'),
531 $this->add('advcheckbox', 'is_active', ts('Active?'));
534 $this->add('advcheckbox', 'is_view', ts('View Only?'));
537 $this->addElement('advcheckbox',
539 ts('Is this Field Searchable?')
542 // is searchable by range?
544 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('Yes'), '1');
545 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('No'), '0');
547 $this->addGroup($searchRange, 'is_search_range', ts('Search by Range?'));
553 'name' => ts('Save'),
558 'name' => ts('Save and New'),
563 'name' => ts('Cancel'),
567 // add a form rule to check default value
568 $this->addFormRule(['CRM_Custom_Form_Field', 'formRule'], $this);
570 // if view mode pls freeze it with the done button.
571 if ($this->_action
& CRM_Core_Action
::VIEW
) {
573 $url = CRM_Utils_System
::url('civicrm/admin/custom/group/field', 'reset=1&action=browse&gid=' . $this->_gid
);
574 $this->addElement('button',
577 ['onclick' => "location.href='$url'"]
583 * Global validation rules for the form.
585 * @param array $fields
586 * Posted values of the form.
592 * if errors then list of errors to be posted back to the form,
595 public static function formRule($fields, $files, $self) {
596 $default = $fields['default_value'] ??
NULL;
600 self
::clearEmptyOptions($fields);
602 //validate field label as well as name.
603 $title = $fields['label'];
604 $name = CRM_Utils_String
::munge($title, '_', 64);
607 $query = 'select count(*) from civicrm_custom_field where ( name like %1 OR label like %2 ) and id != %3 and custom_group_id = %4';
608 $fldCnt = CRM_Core_DAO
::singleValueQuery($query, [
609 1 => [$name, 'String'],
610 2 => [$title, 'String'],
611 3 => [(int) $self->_id
, 'Integer'],
612 4 => [$gId, 'Integer'],
615 $errors['label'] = ts('Custom field \'%1\' already exists in Database.', [1 => $title]);
618 //checks the given custom field name doesnot start with digit
619 if (!empty($title)) {
620 // gives the ascii value
621 $asciiValue = ord($title{0});
622 if ($asciiValue >= 48 && $asciiValue <= 57) {
623 $errors['label'] = ts("Name cannot not start with a digit");
627 // ensure that the label is not 'id'
628 if (strtolower($title) == 'id') {
629 $errors['label'] = ts("You cannot use 'id' as a field label.");
632 if (!isset($fields['data_type'][0]) ||
!isset($fields['data_type'][1])) {
633 $errors['_qf_default'] = ts('Please enter valid - Data and Input Field Type.');
636 $dataType = self
::$_dataTypeKeys[$fields['data_type'][0]];
638 if ($default ||
$dataType == 'ContactReference') {
641 if (!CRM_Utils_Rule
::integer($default)) {
642 $errors['default_value'] = ts('Please enter a valid integer.');
647 if (!CRM_Utils_Rule
::numeric($default)) {
648 $errors['default_value'] = ts('Please enter a valid number.');
653 if (!CRM_Utils_Rule
::money($default)) {
654 $errors['default_value'] = ts('Please enter a valid number.');
659 if (!CRM_Utils_Rule
::url($default)) {
660 $errors['default_value'] = ts('Please enter a valid link.');
665 if (!CRM_Utils_Rule
::date($default)) {
666 $errors['default_value'] = ts('Please enter a valid date as default value using YYYY-MM-DD format. Example: 2004-12-31.');
671 if ($default != '1' && $default != '0') {
672 $errors['default_value'] = ts('Please enter 1 (for Yes) or 0 (for No) if you want to set a default value.');
677 if (!empty($default)) {
678 $query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
679 $params = [1 => [$fields['default_value'], 'String']];
680 if (CRM_Core_DAO
::singleValueQuery($query, $params) <= 0) {
681 $errors['default_value'] = ts('Invalid default value for country.');
686 case 'StateProvince':
687 if (!empty($default)) {
690 FROM civicrm_state_province
692 OR abbreviation = %1";
693 $params = [1 => [$fields['default_value'], 'String']];
694 if (CRM_Core_DAO
::singleValueQuery($query, $params) <= 0) {
695 $errors['default_value'] = ts('The invalid default value for State/Province data type');
700 case 'ContactReference':
701 if ($fields['filter_selected'] == 'Advance' && !empty($fields['filter'])) {
702 if (strpos($fields['filter'], 'entity=') !== FALSE) {
703 $errors['filter'] = ts("Please do not include entity parameter (entity is always 'contact')");
705 elseif (strpos($fields['filter'], 'action=get') === FALSE) {
706 $errors['filter'] = ts("Only 'get' action is supported.");
709 $self->setDefaults(['filter_selected', $fields['filter_selected']]);
714 if (self
::$_dataTypeKeys[$fields['data_type'][0]] == 'Date') {
715 if (!$fields['date_format']) {
716 $errors['date_format'] = ts('Please select a date format.');
720 /** Check the option values entered
721 * Appropriate values are required for the selected datatype
722 * Incomplete row checking is also required.
724 $_flagOption = $_rowError = 0;
725 $_showHide = new CRM_Core_ShowHideBlocks('', '');
726 $dataType = self
::$_dataTypeKeys[$fields['data_type'][0]];
727 if (isset($fields['data_type'][1])) {
728 $dataField = $fields['data_type'][1];
730 $optionFields = ['Select', 'CheckBox', 'Radio'];
732 if (isset($fields['option_type']) && $fields['option_type'] == 1) {
733 //capture duplicate Custom option values
734 if (!empty($fields['option_value'])) {
735 $countValue = count($fields['option_value']);
736 $uniqueCount = count(array_unique($fields['option_value']));
738 if ($countValue > $uniqueCount) {
741 while ($start < self
::NUM_OPTION
) {
742 $nextIndex = $start +
1;
743 while ($nextIndex <= self
::NUM_OPTION
) {
744 if ($fields['option_value'][$start] == $fields['option_value'][$nextIndex] &&
745 strlen($fields['option_value'][$nextIndex])
747 $errors['option_value[' . $start . ']'] = ts('Duplicate Option values');
748 $errors['option_value[' . $nextIndex . ']'] = ts('Duplicate Option values');
758 //capture duplicate Custom Option label
759 if (!empty($fields['option_label'])) {
760 $countValue = count($fields['option_label']);
761 $uniqueCount = count(array_unique($fields['option_label']));
763 if ($countValue > $uniqueCount) {
765 while ($start < self
::NUM_OPTION
) {
766 $nextIndex = $start +
1;
767 while ($nextIndex <= self
::NUM_OPTION
) {
768 if ($fields['option_label'][$start] == $fields['option_label'][$nextIndex] &&
769 !empty($fields['option_label'][$nextIndex])
771 $errors['option_label[' . $start . ']'] = ts('Duplicate Option label');
772 $errors['option_label[' . $nextIndex . ']'] = ts('Duplicate Option label');
782 for ($i = 1; $i <= self
::NUM_OPTION
; $i++
) {
783 if (!$fields['option_label'][$i]) {
784 if ($fields['option_value'][$i]) {
785 $errors['option_label[' . $i . ']'] = ts('Option label cannot be empty');
793 if (!strlen(trim($fields['option_value'][$i]))) {
794 if (!$fields['option_value'][$i]) {
795 $errors['option_value[' . $i . ']'] = ts('Option value cannot be empty');
801 if ($fields['option_value'][$i] && $dataType != 'String') {
802 if ($dataType == 'Int') {
803 if (!CRM_Utils_Rule
::integer($fields['option_value'][$i])) {
805 $errors['option_value[' . $i . ']'] = ts('Please enter a valid integer.');
808 elseif ($dataType == 'Money') {
809 if (!CRM_Utils_Rule
::money($fields['option_value'][$i])) {
811 $errors['option_value[' . $i . ']'] = ts('Please enter a valid money value.');
815 if (!CRM_Utils_Rule
::numeric($fields['option_value'][$i])) {
817 $errors['option_value[' . $i . ']'] = ts('Please enter a valid number.');
822 $showBlocks = 'optionField_' . $i;
824 $_showHide->addShow($showBlocks);
828 if (!empty($_emptyRow)) {
829 $_showHide->addHide($showBlocks);
832 $_showHide->addShow($showBlocks);
834 if ($i == self
::NUM_OPTION
) {
835 $hideBlock = 'additionalOption';
836 $_showHide->addHide($hideBlock);
839 $_flagOption = $_emptyRow = 0;
842 elseif (isset($dataField) &&
843 in_array($dataField, $optionFields) &&
844 !in_array($dataType, ['Boolean', 'Country', 'StateProvince'])
846 if (!$fields['option_group_id']) {
847 $errors['option_group_id'] = ts('You must select a Multiple Choice Option set if you chose Reuse an existing set.');
852 FROM civicrm_custom_field
853 WHERE data_type != %1
854 AND option_group_id = %2";
857 self
::$_dataTypeKeys[$fields['data_type'][0]],
860 2 => [$fields['option_group_id'], 'Integer'],
862 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
864 $errors['option_group_id'] = ts('The data type of the multiple choice option set you\'ve selected does not match the data type assigned to this field.');
869 $assignError = new CRM_Core_Page();
871 $_showHide->addToTemplate();
872 $assignError->assign('optionRowError', $_rowError);
875 if (isset($fields['data_type'][1])) {
876 switch (self
::$_dataToHTML[$fields['data_type'][0]][$fields['data_type'][1]]) {
879 $assignError->assign('fieldError', $_fieldError);
884 $assignError->assign('fieldError', $_fieldError);
889 $assignError->assign('fieldError', $_fieldError);
894 $assignError->assign('fieldError', $_fieldError);
898 for ($idx = 1; $idx <= self
::NUM_OPTION
; $idx++
) {
899 $showBlocks = 'optionField_' . $idx;
900 if (!empty($fields['option_label'][$idx])) {
901 $_showHide->addShow($showBlocks);
904 $_showHide->addHide($showBlocks);
907 $_showHide->addToTemplate();
910 // we can not set require and view at the same time.
911 if (!empty($fields['is_required']) && !empty($fields['is_view'])) {
912 $errors['is_view'] = ts('Can not set this field Required and View Only at the same time.');
915 return empty($errors) ?
TRUE : $errors;
923 public function postProcess() {
924 // store the submitted values in an array
925 $params = $this->controller
->exportValues($this->_name
);
926 self
::clearEmptyOptions($params);
927 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
928 $dataTypeKey = $this->_defaultDataType
[0];
929 $params['data_type'] = self
::$_dataTypeKeys[$this->_defaultDataType
[0]];
930 $params['html_type'] = self
::$_dataToHTML[$this->_defaultDataType
[0]][$this->_defaultDataType
[1]];
933 $dataTypeKey = $params['data_type'][0];
934 $params['html_type'] = self
::$_dataToHTML[$params['data_type'][0]][$params['data_type'][1]];
935 $params['data_type'] = self
::$_dataTypeKeys[$params['data_type'][0]];
938 //fix for 'is_search_range' field.
939 if (in_array($dataTypeKey, [
945 if (empty($params['is_searchable'])) {
946 $params['is_search_range'] = 0;
950 $params['is_search_range'] = 0;
953 // Serialization cannot be changed on update
955 unset($params['serialize']);
957 elseif (strpos($params['html_type'], 'Select') === 0) {
958 $params['serialize'] = $params['serialize'] ? CRM_Core_DAO
::SERIALIZE_SEPARATOR_BOOKEND
: 'null';
961 $params['serialize'] = $params['html_type'] == 'CheckBox' ? CRM_Core_DAO
::SERIALIZE_SEPARATOR_BOOKEND
: 'null';
965 if ($dataTypeKey == 11 && !empty($params['filter_selected'])) {
966 if ($params['filter_selected'] == 'Advance' && trim(CRM_Utils_Array
::value('filter', $params))) {
967 $filter = trim($params['filter']);
969 elseif ($params['filter_selected'] == 'Group' && !empty($params['group_id'])) {
971 $filter = 'action=lookup&group=' . implode(',', $params['group_id']);
974 $params['filter'] = $filter;
978 if ($this->_action
& (CRM_Core_Action
::UPDATE | CRM_Core_Action
::ADD
)) {
979 $fieldValues = ['custom_group_id' => $this->_gid
];
981 $oldWeight = $this->_values
['weight'];
983 $params['weight'] = CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomField', $oldWeight, $params['weight'], $fieldValues);
986 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
988 //store the primary key for State/Province or Country as default value.
989 if (strlen(trim($params['default_value']))) {
990 switch ($params['data_type']) {
991 case 'StateProvince':
992 $fieldStateProvince = $strtolower($params['default_value']);
994 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
997 FROM civicrm_state_province
998 WHERE LOWER(name) = '$fieldStateProvince'
999 OR abbreviation = '$fieldStateProvince'";
1000 $dao = CRM_Core_DAO
::executeQuery($query);
1001 if ($dao->fetch()) {
1002 $params['default_value'] = $dao->id
;
1007 $fieldCountry = $strtolower($params['default_value']);
1009 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
1012 FROM civicrm_country
1013 WHERE LOWER(name) = '$fieldCountry'
1014 OR iso_code = '$fieldCountry'";
1015 $dao = CRM_Core_DAO
::executeQuery($query);
1016 if ($dao->fetch()) {
1017 $params['default_value'] = $dao->id
;
1023 // The text_length attribute for Memo fields is in a different input as there
1024 // are different label, help text and default value than for other type fields
1025 if ($params['data_type'] == "Memo") {
1026 $params['text_length'] = $params['note_length'];
1029 // need the FKEY - custom group id
1030 $params['custom_group_id'] = $this->_gid
;
1032 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1033 $params['id'] = $this->_id
;
1035 $customField = CRM_Core_BAO_CustomField
::create($params);
1036 $this->_id
= $customField->id
;
1039 Civi
::cache('fields')->flush();
1041 $msg = '<p>' . ts("Custom field '%1' has been saved.", [1 => $customField->label
]) . '</p>';
1043 $buttonName = $this->controller
->getButtonName();
1044 $session = CRM_Core_Session
::singleton();
1045 if ($buttonName == $this->getButtonName('next', 'new')) {
1046 $msg .= '<p>' . ts("Ready to add another.") . '</p>';
1047 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/admin/custom/group/field/add',
1048 'reset=1&action=add&gid=' . $this->_gid
1052 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/admin/custom/group/field',
1053 'reset=1&action=browse&gid=' . $this->_gid
1056 $session->setStatus($msg, ts('Saved'), 'success');
1058 // Add data when in ajax contect
1059 $this->ajaxResponse
['customField'] = $customField->toArray();
1063 * Removes value from fields with no label.
1065 * This allows default values to be set in the form, but ignored in post-processing.
1067 * @param array $fields
1069 public static function clearEmptyOptions(&$fields) {
1070 foreach ($fields['option_label'] as $i => $label) {
1071 if (!strlen(trim($label))) {
1072 $fields['option_value'][$i] = '';