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
37 * form to process actions on the field aspect of Custom
39 class CRM_Custom_Form_Field
extends CRM_Core_Form
{
42 * Constants for number of options for data types of multiple option.
44 const NUM_OPTION
= 11;
47 * The custom group id saved to the session for an update.
54 * The field id, used when editing the field
61 * The default custom data/input types, when editing the field
65 protected $_defaultDataType;
68 * Array of custom field values if update mode.
74 * Array for valid combinations of data_type & html_type
78 private static $_dataTypeValues = NULL;
79 private static $_dataTypeKeys = NULL;
81 private static $_dataToHTML = NULL;
83 private static $_dataToLabels = NULL;
86 * Set variables up before form is built.
90 public function preProcess() {
91 if (!(self
::$_dataTypeKeys)) {
92 self
::$_dataTypeKeys = array_keys(CRM_Core_BAO_CustomField
::dataType());
93 self
::$_dataTypeValues = array_values(CRM_Core_BAO_CustomField
::dataType());
96 if (!self
::$_dataToHTML) {
97 self
::$_dataToHTML = CRM_Core_BAO_CustomField
::dataToHtml();
101 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
104 //get the values form db if update.
106 $params = ['id' => $this->_id
];
107 CRM_Core_BAO_CustomField
::retrieve($params, $this->_values
);
108 // note_length is an alias for the text_length field
109 $this->_values
['note_length'] = CRM_Utils_Array
::value('text_length', $this->_values
);
111 $this->_gid
= $this->_values
['custom_group_id'];
115 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this);
118 if ($isReserved = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'is_reserved', 'id')) {
119 CRM_Core_Error
::fatal("You cannot add or edit fields in a reserved custom field-set.");
123 $url = CRM_Utils_System
::url('civicrm/admin/custom/group/field',
124 "reset=1&action=browse&gid={$this->_gid}"
127 $session = CRM_Core_Session
::singleton();
128 $session->pushUserContext($url);
131 if (self
::$_dataToLabels == NULL) {
132 self
::$_dataToLabels = [
134 'Text' => ts('Text'),
135 'Select' => ts('Select'),
136 'Radio' => ts('Radio'),
137 'CheckBox' => ts('CheckBox'),
138 'Multi-Select' => ts('Multi-Select'),
139 'Autocomplete-Select' => ts('Autocomplete-Select'),
142 'Text' => ts('Text'),
143 'Select' => ts('Select'),
144 'Radio' => ts('Radio'),
147 'Text' => ts('Text'),
148 'Select' => ts('Select'),
149 'Radio' => ts('Radio'),
152 'Text' => ts('Text'),
153 'Select' => ts('Select'),
154 'Radio' => ts('Radio'),
156 ['TextArea' => ts('TextArea'), 'RichTextEditor' => ts('Rich Text Editor')],
157 ['Date' => ts('Select Date')],
158 ['Radio' => ts('Radio')],
159 ['StateProvince' => ts('Select State/Province'), 'Multi-Select' => ts('Multi-Select State/Province')],
160 ['Country' => ts('Select Country'), 'Multi-Select' => ts('Multi-Select Country')],
161 ['File' => ts('Select File')],
162 ['Link' => ts('Link')],
163 ['ContactReference' => ts('Autocomplete-Select')],
169 * Set default values for the form. Note that in edit/view mode
170 * the default values are retrieved from the database
173 * array of default values
175 public function setDefaultValues() {
176 $defaults = $this->_values
;
179 $this->assign('id', $this->_id
);
180 $this->_gid
= $defaults['custom_group_id'];
182 //get the value for state or country
183 if ($defaults['data_type'] == 'StateProvince' &&
184 $stateId = CRM_Utils_Array
::value('default_value', $defaults)
186 $defaults['default_value'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_StateProvince', $stateId);
188 elseif ($defaults['data_type'] == 'Country' &&
189 $countryId = CRM_Utils_Array
::value('default_value', $defaults)
191 $defaults['default_value'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Country', $countryId);
194 if ($defaults['data_type'] == 'ContactReference' && !empty($defaults['filter'])) {
195 $contactRefFilter = 'Advance';
196 if (strpos($defaults['filter'], 'action=lookup') !== FALSE &&
197 strpos($defaults['filter'], 'group=') !== FALSE
199 $filterParts = explode('&', $defaults['filter']);
201 if (count($filterParts) == 2) {
202 $contactRefFilter = 'Group';
203 foreach ($filterParts as $part) {
204 if (strpos($part, 'group=') === FALSE) {
207 $groups = substr($part, strpos($part, '=') +
1);
208 foreach (explode(',', $groups) as $grp) {
209 if (CRM_Utils_Rule
::positiveInteger($grp)) {
210 $defaults['group_id'][] = $grp;
216 $defaults['filter_selected'] = $contactRefFilter;
219 if (!empty($defaults['data_type'])) {
220 $defaultDataType = array_search($defaults['data_type'],
223 $defaultHTMLType = array_search($defaults['html_type'],
224 self
::$_dataToHTML[$defaultDataType]
226 $defaults['data_type'] = [
227 '0' => $defaultDataType,
228 '1' => $defaultHTMLType,
230 $this->_defaultDataType
= $defaults['data_type'];
233 $defaults['option_type'] = 2;
235 $this->assign('changeFieldType', CRM_Custom_Form_ChangeFieldType
::fieldTypeTransitions($this->_values
['data_type'], $this->_values
['html_type']));
238 $defaults['is_active'] = 1;
239 $defaults['option_type'] = 1;
240 $defaults['is_search_range'] = 1;
243 // set defaults for weight.
244 for ($i = 1; $i <= self
::NUM_OPTION
; $i++
) {
245 $defaults['option_status[' . $i . ']'] = 1;
246 $defaults['option_weight[' . $i . ']'] = $i;
247 $defaults['option_value[' . $i . ']'] = $i;
250 if ($this->_action
& CRM_Core_Action
::ADD
) {
251 $fieldValues = ['custom_group_id' => $this->_gid
];
252 $defaults['weight'] = CRM_Utils_Weight
::getDefaultWeight('CRM_Core_DAO_CustomField', $fieldValues);
254 $defaults['text_length'] = 255;
255 $defaults['note_columns'] = 60;
256 $defaults['note_rows'] = 4;
257 $defaults['is_view'] = 0;
260 if (!empty($defaults['html_type'])) {
261 $dontShowLink = substr($defaults['html_type'], -14) == 'State/Province' ||
substr($defaults['html_type'], -7) == 'Country' ?
1 : 0;
264 if (isset($dontShowLink)) {
265 $this->assign('dontShowLink', $dontShowLink);
267 if ($this->_action
& CRM_Core_Action
::ADD
&&
268 CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'is_multiple', 'id')
270 $defaults['in_selector'] = 1;
277 * Build the form object.
281 public function buildQuickForm() {
283 $this->_title
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'title');
284 CRM_Utils_System
::setTitle($this->_title
. ' - ' . ($this->_id ?
ts('Edit Field') : ts('New Field')));
285 $this->assign('gid', $this->_gid
);
288 $this->assign('dataTypeKeys', self
::$_dataTypeKeys);
290 // lets trim all the whitespace
291 $this->applyFilter('__ALL__', 'trim');
293 $attributes = CRM_Core_DAO
::getAttribute('CRM_Core_DAO_CustomField');
299 $attributes['label'],
303 $dt = &self
::$_dataTypeValues;
305 foreach ($dt as $key => $value) {
306 $it[$key] = self
::$_dataToLabels[$key];
308 $sel = &$this->addElement('hierselect',
310 ts('Data and Input Field Type'),
313 $sel->setOptions([$dt, $it]);
315 if (CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'is_multiple')) {
316 $this->add('checkbox', 'in_selector', ts('Display in Table?'));
319 $optionGroupParams = [
322 'options' => ['limit' => 0, 'sort' => "title ASC"],
323 'return' => ['title'],
326 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
327 $this->freeze('data_type');
328 if (!empty($this->_values
['option_group_id'])) {
329 // Before dev/core#155 we didn't set the is_reserved flag properly, which should be handled by the upgrade script...
330 // but it is still possible that existing installs may have optiongroups linked to custom fields that are marked reserved.
331 $optionGroupParams['id'] = $this->_values
['option_group_id'];
332 $optionGroupParams['options']['or'] = [["is_reserved", "id"]];
336 // Retrieve optiongroups for selection list
337 $optionGroupMetadata = civicrm_api3('OptionGroup', 'get', $optionGroupParams);
339 // OptionGroup selection
340 $optionTypes = ['1' => ts('Create a new set of options')];
342 if (!empty($optionGroupMetadata['values'])) {
343 $emptyOptGroup = FALSE;
344 $optionGroups = CRM_Utils_Array
::collect('title', $optionGroupMetadata['values']);
345 $optionTypes['2'] = ts('Reuse an existing set');
349 ts('Multiple Choice Option Sets'),
351 '' => ts('- select -'),
356 // No custom (non-reserved) option groups
357 $emptyOptGroup = TRUE;
360 $element = &$this->addRadio('option_type',
364 'onclick' => "showOptionSelect();",
367 // if empty option group freeze the option type.
368 if ($emptyOptGroup) {
372 $contactGroups = CRM_Core_PseudoConstant
::group();
373 asort($contactGroups);
377 ts('Limit List to Group'),
380 ['multiple' => 'multiple', 'class' => 'crm-select2']
385 ts('Advanced Filter'),
386 $attributes['filter']
389 $this->add('hidden', 'filter_selected', 'Group', ['id' => 'filter_selected']);
391 // form fields of Custom Option rows
393 $_showHide = new CRM_Core_ShowHideBlocks('', '');
394 for ($i = 1; $i <= self
::NUM_OPTION
; $i++
) {
396 //the show hide blocks
397 $showBlocks = 'optionField_' . $i;
399 $_showHide->addHide($showBlocks);
400 if ($i == self
::NUM_OPTION
) {
401 $_showHide->addHide('additionalOption');
405 $_showHide->addShow($showBlocks);
408 $optionAttributes = CRM_Core_DAO
::getAttribute('CRM_Core_DAO_OptionValue');
410 $this->add('text', 'option_label[' . $i . ']', ts('Label'),
411 $optionAttributes['label']
415 $this->add('text', 'option_value[' . $i . ']', ts('Value'),
416 $optionAttributes['value']
420 $this->add('number', "option_weight[$i]", ts('Order'),
421 $optionAttributes['weight']
425 $this->add('checkbox', "option_status[$i]", ts('Active?'));
427 $defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i);
429 //for checkbox handling of default option
430 $this->add('checkbox', "default_checkbox_option[$i]", NULL);
433 //default option selection
434 $this->addGroup($defaultOption, 'default_option');
436 $_showHide->addToTemplate();
438 // text length for alpha numeric data types
441 ts('Database field length'),
442 $attributes['text_length'] +
['min' => 1],
445 $this->addRule('text_length', ts('Value should be a positive number'), 'integer');
449 ts('Dates may be up to'),
450 $attributes['start_date_years'],
455 ts('Dates may be up to'),
456 $attributes['end_date_years'],
460 $this->addRule('start_date_years', ts('Value should be a positive number'), 'integer');
461 $this->addRule('end_date_years', ts('Value should be a positive number'), 'integer');
463 $this->add('select', 'date_format', ts('Date Format'),
464 ['' => ts('- select -')] + CRM_Core_SelectValues
::getDatePluginInputFormats()
467 $this->add('select', 'time_format', ts('Time'),
468 ['' => ts('- none -')] + CRM_Core_SelectValues
::getTimeFormats()
474 ts('Width (columns)') . ' ',
475 $attributes['note_columns'],
480 ts('Height (rows)') . ' ',
481 $attributes['note_rows'],
486 ts('Maximum length') . ' ',
487 // note_length is an alias for the text-length field
488 $attributes['text_length'],
492 $this->addRule('note_columns', ts('Value should be a positive number'), 'positiveInteger');
493 $this->addRule('note_rows', ts('Value should be a positive number'), 'positiveInteger');
494 $this->addRule('note_length', ts('Value should be a positive number'), 'positiveInteger');
497 $this->add('number', 'weight', ts('Order'),
498 $attributes['weight'],
501 $this->addRule('weight', ts('is a numeric field'), 'numeric');
504 $this->add('advcheckbox', 'is_required', ts('Required?'));
506 // checkbox / radio options per line
507 $this->add('number', 'options_per_line', ts('Options Per Line'), ['min' => 0]);
508 $this->addRule('options_per_line', ts('must be a numeric value'), 'numeric');
510 // default value, help pre, help post, mask, attributes, javascript ?
511 $this->add('text', 'default_value', ts('Default Value'),
512 $attributes['default_value']
514 $this->add('textarea', 'help_pre', ts('Field Pre Help'),
515 $attributes['help_pre']
517 $this->add('textarea', 'help_post', ts('Field Post Help'),
518 $attributes['help_post']
520 $this->add('text', 'mask', ts('Mask'),
525 $this->add('advcheckbox', 'is_active', ts('Active?'));
528 $this->add('advcheckbox', 'is_view', ts('View Only?'));
531 $this->addElement('advcheckbox',
533 ts('Is this Field Searchable?')
536 // is searchable by range?
538 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('Yes'), '1');
539 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('No'), '0');
541 $this->addGroup($searchRange, 'is_search_range', ts('Search by Range?'));
547 'name' => ts('Save'),
552 'name' => ts('Save and New'),
557 'name' => ts('Cancel'),
561 // add a form rule to check default value
562 $this->addFormRule(['CRM_Custom_Form_Field', 'formRule'], $this);
564 // if view mode pls freeze it with the done button.
565 if ($this->_action
& CRM_Core_Action
::VIEW
) {
567 $url = CRM_Utils_System
::url('civicrm/admin/custom/group/field', 'reset=1&action=browse&gid=' . $this->_gid
);
568 $this->addElement('button',
571 ['onclick' => "location.href='$url'"]
577 * Global validation rules for the form.
579 * @param array $fields
580 * Posted values of the form.
586 * if errors then list of errors to be posted back to the form,
589 public static function formRule($fields, $files, $self) {
590 $default = CRM_Utils_Array
::value('default_value', $fields);
594 self
::clearEmptyOptions($fields);
596 //validate field label as well as name.
597 $title = $fields['label'];
598 $name = CRM_Utils_String
::munge($title, '_', 64);
601 $query = 'select count(*) from civicrm_custom_field where ( name like %1 OR label like %2 ) and id != %3 and custom_group_id = %4';
602 $fldCnt = CRM_Core_DAO
::singleValueQuery($query, [
603 1 => [$name, 'String'],
604 2 => [$title, 'String'],
605 3 => [(int) $self->_id
, 'Integer'],
606 4 => [$gId, 'Integer'],
609 $errors['label'] = ts('Custom field \'%1\' already exists in Database.', [1 => $title]);
612 //checks the given custom field name doesnot start with digit
613 if (!empty($title)) {
614 // gives the ascii value
615 $asciiValue = ord($title{0});
616 if ($asciiValue >= 48 && $asciiValue <= 57) {
617 $errors['label'] = ts("Name cannot not start with a digit");
621 // ensure that the label is not 'id'
622 if (strtolower($title) == 'id') {
623 $errors['label'] = ts("You cannot use 'id' as a field label.");
626 if (!isset($fields['data_type'][0]) ||
!isset($fields['data_type'][1])) {
627 $errors['_qf_default'] = ts('Please enter valid - Data and Input Field Type.');
630 $dataType = self
::$_dataTypeKeys[$fields['data_type'][0]];
632 if ($default ||
$dataType == 'ContactReference') {
635 if (!CRM_Utils_Rule
::integer($default)) {
636 $errors['default_value'] = ts('Please enter a valid integer.');
641 if (!CRM_Utils_Rule
::numeric($default)) {
642 $errors['default_value'] = ts('Please enter a valid number.');
647 if (!CRM_Utils_Rule
::money($default)) {
648 $errors['default_value'] = ts('Please enter a valid number.');
653 if (!CRM_Utils_Rule
::url($default)) {
654 $errors['default_value'] = ts('Please enter a valid link.');
659 if (!CRM_Utils_Rule
::date($default)) {
660 $errors['default_value'] = ts('Please enter a valid date as default value using YYYY-MM-DD format. Example: 2004-12-31.');
665 if ($default != '1' && $default != '0') {
666 $errors['default_value'] = ts('Please enter 1 (for Yes) or 0 (for No) if you want to set a default value.');
671 if (!empty($default)) {
672 $query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
673 $params = [1 => [$fields['default_value'], 'String']];
674 if (CRM_Core_DAO
::singleValueQuery($query, $params) <= 0) {
675 $errors['default_value'] = ts('Invalid default value for country.');
680 case 'StateProvince':
681 if (!empty($default)) {
684 FROM civicrm_state_province
686 OR abbreviation = %1";
687 $params = [1 => [$fields['default_value'], 'String']];
688 if (CRM_Core_DAO
::singleValueQuery($query, $params) <= 0) {
689 $errors['default_value'] = ts('The invalid default value for State/Province data type');
694 case 'ContactReference':
695 if ($fields['filter_selected'] == 'Advance' && !empty($fields['filter'])) {
696 if (strpos($fields['filter'], 'entity=') !== FALSE) {
697 $errors['filter'] = ts("Please do not include entity parameter (entity is always 'contact')");
699 elseif (strpos($fields['filter'], 'action=get') === FALSE) {
700 $errors['filter'] = ts("Only 'get' action is supported.");
703 $self->setDefaults(['filter_selected', $fields['filter_selected']]);
708 if (self
::$_dataTypeKeys[$fields['data_type'][0]] == 'Date') {
709 if (!$fields['date_format']) {
710 $errors['date_format'] = ts('Please select a date format.');
714 /** Check the option values entered
715 * Appropriate values are required for the selected datatype
716 * Incomplete row checking is also required.
718 $_flagOption = $_rowError = 0;
719 $_showHide = new CRM_Core_ShowHideBlocks('', '');
720 $dataType = self
::$_dataTypeKeys[$fields['data_type'][0]];
721 if (isset($fields['data_type'][1])) {
722 $dataField = $fields['data_type'][1];
724 $optionFields = ['Select', 'Multi-Select', 'CheckBox', 'Radio'];
726 if (isset($fields['option_type']) && $fields['option_type'] == 1) {
727 //capture duplicate Custom option values
728 if (!empty($fields['option_value'])) {
729 $countValue = count($fields['option_value']);
730 $uniqueCount = count(array_unique($fields['option_value']));
732 if ($countValue > $uniqueCount) {
735 while ($start < self
::NUM_OPTION
) {
736 $nextIndex = $start +
1;
737 while ($nextIndex <= self
::NUM_OPTION
) {
738 if ($fields['option_value'][$start] == $fields['option_value'][$nextIndex] &&
739 strlen($fields['option_value'][$nextIndex])
741 $errors['option_value[' . $start . ']'] = ts('Duplicate Option values');
742 $errors['option_value[' . $nextIndex . ']'] = ts('Duplicate Option values');
752 //capture duplicate Custom Option label
753 if (!empty($fields['option_label'])) {
754 $countValue = count($fields['option_label']);
755 $uniqueCount = count(array_unique($fields['option_label']));
757 if ($countValue > $uniqueCount) {
759 while ($start < self
::NUM_OPTION
) {
760 $nextIndex = $start +
1;
761 while ($nextIndex <= self
::NUM_OPTION
) {
762 if ($fields['option_label'][$start] == $fields['option_label'][$nextIndex] &&
763 !empty($fields['option_label'][$nextIndex])
765 $errors['option_label[' . $start . ']'] = ts('Duplicate Option label');
766 $errors['option_label[' . $nextIndex . ']'] = ts('Duplicate Option label');
776 for ($i = 1; $i <= self
::NUM_OPTION
; $i++
) {
777 if (!$fields['option_label'][$i]) {
778 if ($fields['option_value'][$i]) {
779 $errors['option_label[' . $i . ']'] = ts('Option label cannot be empty');
787 if (!strlen(trim($fields['option_value'][$i]))) {
788 if (!$fields['option_value'][$i]) {
789 $errors['option_value[' . $i . ']'] = ts('Option value cannot be empty');
795 if ($fields['option_value'][$i] && $dataType != 'String') {
796 if ($dataType == 'Int') {
797 if (!CRM_Utils_Rule
::integer($fields['option_value'][$i])) {
799 $errors['option_value[' . $i . ']'] = ts('Please enter a valid integer.');
802 elseif ($dataType == 'Money') {
803 if (!CRM_Utils_Rule
::money($fields['option_value'][$i])) {
805 $errors['option_value[' . $i . ']'] = ts('Please enter a valid money value.');
809 if (!CRM_Utils_Rule
::numeric($fields['option_value'][$i])) {
811 $errors['option_value[' . $i . ']'] = ts('Please enter a valid number.');
816 $showBlocks = 'optionField_' . $i;
818 $_showHide->addShow($showBlocks);
822 if (!empty($_emptyRow)) {
823 $_showHide->addHide($showBlocks);
826 $_showHide->addShow($showBlocks);
828 if ($i == self
::NUM_OPTION
) {
829 $hideBlock = 'additionalOption';
830 $_showHide->addHide($hideBlock);
833 $_flagOption = $_emptyRow = 0;
836 elseif (isset($dataField) &&
837 in_array($dataField, $optionFields) &&
838 !in_array($dataType, ['Boolean', 'Country', 'StateProvince'])
840 if (!$fields['option_group_id']) {
841 $errors['option_group_id'] = ts('You must select a Multiple Choice Option set if you chose Reuse an existing set.');
846 FROM civicrm_custom_field
847 WHERE data_type != %1
848 AND option_group_id = %2";
851 self
::$_dataTypeKeys[$fields['data_type'][0]],
854 2 => [$fields['option_group_id'], 'Integer'],
856 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
858 $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.');
863 $assignError = new CRM_Core_Page();
865 $_showHide->addToTemplate();
866 $assignError->assign('optionRowError', $_rowError);
869 if (isset($fields['data_type'][1])) {
870 switch (self
::$_dataToHTML[$fields['data_type'][0]][$fields['data_type'][1]]) {
873 $assignError->assign('fieldError', $_fieldError);
878 $assignError->assign('fieldError', $_fieldError);
883 $assignError->assign('fieldError', $_fieldError);
888 $assignError->assign('fieldError', $_fieldError);
892 for ($idx = 1; $idx <= self
::NUM_OPTION
; $idx++
) {
893 $showBlocks = 'optionField_' . $idx;
894 if (!empty($fields['option_label'][$idx])) {
895 $_showHide->addShow($showBlocks);
898 $_showHide->addHide($showBlocks);
901 $_showHide->addToTemplate();
904 // we can not set require and view at the same time.
905 if (!empty($fields['is_required']) && !empty($fields['is_view'])) {
906 $errors['is_view'] = ts('Can not set this field Required and View Only at the same time.');
909 return empty($errors) ?
TRUE : $errors;
917 public function postProcess() {
918 // store the submitted values in an array
919 $params = $this->controller
->exportValues($this->_name
);
920 self
::clearEmptyOptions($params);
921 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
922 $dataTypeKey = $this->_defaultDataType
[0];
923 $params['data_type'] = self
::$_dataTypeKeys[$this->_defaultDataType
[0]];
924 $params['html_type'] = self
::$_dataToHTML[$this->_defaultDataType
[0]][$this->_defaultDataType
[1]];
927 $dataTypeKey = $params['data_type'][0];
928 $params['html_type'] = self
::$_dataToHTML[$params['data_type'][0]][$params['data_type'][1]];
929 $params['data_type'] = self
::$_dataTypeKeys[$params['data_type'][0]];
932 //fix for 'is_search_range' field.
933 if (in_array($dataTypeKey, [
939 if (empty($params['is_searchable'])) {
940 $params['is_search_range'] = 0;
944 $params['is_search_range'] = 0;
948 if ($dataTypeKey == 11 && !empty($params['filter_selected'])) {
949 if ($params['filter_selected'] == 'Advance' && trim(CRM_Utils_Array
::value('filter', $params))) {
950 $filter = trim($params['filter']);
952 elseif ($params['filter_selected'] == 'Group' && !empty($params['group_id'])) {
954 $filter = 'action=lookup&group=' . implode(',', $params['group_id']);
957 $params['filter'] = $filter;
961 if ($this->_action
& (CRM_Core_Action
::UPDATE | CRM_Core_Action
::ADD
)) {
962 $fieldValues = ['custom_group_id' => $this->_gid
];
964 $oldWeight = $this->_values
['weight'];
966 $params['weight'] = CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomField', $oldWeight, $params['weight'], $fieldValues);
969 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
971 //store the primary key for State/Province or Country as default value.
972 if (strlen(trim($params['default_value']))) {
973 switch ($params['data_type']) {
974 case 'StateProvince':
975 $fieldStateProvince = $strtolower($params['default_value']);
977 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
980 FROM civicrm_state_province
981 WHERE LOWER(name) = '$fieldStateProvince'
982 OR abbreviation = '$fieldStateProvince'";
983 $dao = CRM_Core_DAO
::executeQuery($query);
985 $params['default_value'] = $dao->id
;
990 $fieldCountry = $strtolower($params['default_value']);
992 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
996 WHERE LOWER(name) = '$fieldCountry'
997 OR iso_code = '$fieldCountry'";
998 $dao = CRM_Core_DAO
::executeQuery($query);
1000 $params['default_value'] = $dao->id
;
1006 // The text_length attribute for Memo fields is in a different input as there
1007 // are different label, help text and default value than for other type fields
1008 if ($params['data_type'] == "Memo") {
1009 $params['text_length'] = $params['note_length'];
1012 // need the FKEY - custom group id
1013 $params['custom_group_id'] = $this->_gid
;
1015 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1016 $params['id'] = $this->_id
;
1018 $customField = CRM_Core_BAO_CustomField
::create($params);
1019 $this->_id
= $customField->id
;
1022 Civi
::cache('fields')->flush();
1024 $msg = '<p>' . ts("Custom field '%1' has been saved.", [1 => $customField->label
]) . '</p>';
1026 $buttonName = $this->controller
->getButtonName();
1027 $session = CRM_Core_Session
::singleton();
1028 if ($buttonName == $this->getButtonName('next', 'new')) {
1029 $msg .= '<p>' . ts("Ready to add another.") . '</p>';
1030 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/admin/custom/group/field/add',
1031 'reset=1&action=add&gid=' . $this->_gid
1035 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/admin/custom/group/field',
1036 'reset=1&action=browse&gid=' . $this->_gid
1039 $session->setStatus($msg, ts('Saved'), 'success');
1041 // Add data when in ajax contect
1042 $this->ajaxResponse
['customField'] = $customField->toArray();
1046 * Removes value from fields with no label.
1048 * This allows default values to be set in the form, but ignored in post-processing.
1050 * @param array $fields
1052 public static function clearEmptyOptions(&$fields) {
1053 foreach ($fields['option_label'] as $i => $label) {
1054 if (!strlen(trim($label))) {
1055 $fields['option_value'][$i] = '';