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 'Multi-Select' => 'Multi-Select',
80 'Autocomplete-Select' => 'Autocomplete-Select',
82 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
83 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
84 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
85 ['TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'],
86 ['Date' => 'Select Date'],
88 ['StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'],
89 ['Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'],
92 ['ContactReference' => 'Autocomplete-Select'],
96 * Set variables up before form is built.
100 public function preProcess() {
101 if (!(self
::$_dataTypeKeys)) {
102 self
::$_dataTypeKeys = array_keys(CRM_Core_BAO_CustomField
::dataType());
103 self
::$_dataTypeValues = array_values(CRM_Core_BAO_CustomField
::dataType());
107 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
110 //get the values form db if update.
112 $params = ['id' => $this->_id
];
113 CRM_Core_BAO_CustomField
::retrieve($params, $this->_values
);
114 // note_length is an alias for the text_length field
115 $this->_values
['note_length'] = $this->_values
['text_length'] ??
NULL;
117 $this->_gid
= $this->_values
['custom_group_id'];
121 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this);
124 if ($isReserved = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'is_reserved', 'id')) {
125 CRM_Core_Error
::fatal("You cannot add or edit fields in a reserved custom field-set.");
129 $url = CRM_Utils_System
::url('civicrm/admin/custom/group/field',
130 "reset=1&action=browse&gid={$this->_gid}"
133 $session = CRM_Core_Session
::singleton();
134 $session->pushUserContext($url);
137 if (self
::$_dataToLabels == NULL) {
138 self
::$_dataToLabels = [
140 'Text' => ts('Text'),
141 'Select' => ts('Select'),
142 'Radio' => ts('Radio'),
143 'CheckBox' => ts('CheckBox'),
144 'Multi-Select' => ts('Multi-Select'),
145 'Autocomplete-Select' => ts('Autocomplete-Select'),
148 'Text' => ts('Text'),
149 'Select' => ts('Select'),
150 'Radio' => ts('Radio'),
153 'Text' => ts('Text'),
154 'Select' => ts('Select'),
155 'Radio' => ts('Radio'),
158 'Text' => ts('Text'),
159 'Select' => ts('Select'),
160 'Radio' => ts('Radio'),
162 ['TextArea' => ts('TextArea'), 'RichTextEditor' => ts('Rich Text Editor')],
163 ['Date' => ts('Select Date')],
164 ['Radio' => ts('Radio')],
165 ['StateProvince' => ts('Select State/Province'), 'Multi-Select' => ts('Multi-Select State/Province')],
166 ['Country' => ts('Select Country'), 'Multi-Select' => ts('Multi-Select Country')],
167 ['File' => ts('Select File')],
168 ['Link' => ts('Link')],
169 ['ContactReference' => ts('Autocomplete-Select')],
175 * Set default values for the form. Note that in edit/view mode
176 * the default values are retrieved from the database
179 * array of default values
181 public function setDefaultValues() {
182 $defaults = $this->_values
;
185 $this->assign('id', $this->_id
);
186 $this->_gid
= $defaults['custom_group_id'];
188 //get the value for state or country
189 if ($defaults['data_type'] == 'StateProvince' &&
190 $stateId = CRM_Utils_Array
::value('default_value', $defaults)
192 $defaults['default_value'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_StateProvince', $stateId);
194 elseif ($defaults['data_type'] == 'Country' &&
195 $countryId = CRM_Utils_Array
::value('default_value', $defaults)
197 $defaults['default_value'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Country', $countryId);
200 if ($defaults['data_type'] == 'ContactReference' && !empty($defaults['filter'])) {
201 $contactRefFilter = 'Advance';
202 if (strpos($defaults['filter'], 'action=lookup') !== FALSE &&
203 strpos($defaults['filter'], 'group=') !== FALSE
205 $filterParts = explode('&', $defaults['filter']);
207 if (count($filterParts) == 2) {
208 $contactRefFilter = 'Group';
209 foreach ($filterParts as $part) {
210 if (strpos($part, 'group=') === FALSE) {
213 $groups = substr($part, strpos($part, '=') +
1);
214 foreach (explode(',', $groups) as $grp) {
215 if (CRM_Utils_Rule
::positiveInteger($grp)) {
216 $defaults['group_id'][] = $grp;
222 $defaults['filter_selected'] = $contactRefFilter;
225 if (!empty($defaults['data_type'])) {
226 $defaultDataType = array_search($defaults['data_type'],
229 $defaultHTMLType = array_search($defaults['html_type'],
230 self
::$_dataToHTML[$defaultDataType]
232 $defaults['data_type'] = [
233 '0' => $defaultDataType,
234 '1' => $defaultHTMLType,
236 $this->_defaultDataType
= $defaults['data_type'];
239 $defaults['option_type'] = 2;
241 $this->assign('changeFieldType', CRM_Custom_Form_ChangeFieldType
::fieldTypeTransitions($this->_values
['data_type'], $this->_values
['html_type']));
244 $defaults['is_active'] = 1;
245 $defaults['option_type'] = 1;
246 $defaults['is_search_range'] = 1;
249 // set defaults for weight.
250 for ($i = 1; $i <= self
::NUM_OPTION
; $i++
) {
251 $defaults['option_status[' . $i . ']'] = 1;
252 $defaults['option_weight[' . $i . ']'] = $i;
253 $defaults['option_value[' . $i . ']'] = $i;
256 if ($this->_action
& CRM_Core_Action
::ADD
) {
257 $fieldValues = ['custom_group_id' => $this->_gid
];
258 $defaults['weight'] = CRM_Utils_Weight
::getDefaultWeight('CRM_Core_DAO_CustomField', $fieldValues);
260 $defaults['text_length'] = 255;
261 $defaults['note_columns'] = 60;
262 $defaults['note_rows'] = 4;
263 $defaults['is_view'] = 0;
266 if (!empty($defaults['html_type'])) {
267 $dontShowLink = substr($defaults['html_type'], -14) == 'State/Province' ||
substr($defaults['html_type'], -7) == 'Country' ?
1 : 0;
270 if (isset($dontShowLink)) {
271 $this->assign('dontShowLink', $dontShowLink);
273 if ($this->_action
& CRM_Core_Action
::ADD
&&
274 CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'is_multiple', 'id')
276 $defaults['in_selector'] = 1;
283 * Build the form object.
287 public function buildQuickForm() {
289 $this->_title
= CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'title');
290 CRM_Utils_System
::setTitle($this->_title
. ' - ' . ($this->_id ?
ts('Edit Field') : ts('New Field')));
291 $this->assign('gid', $this->_gid
);
294 $this->assign('dataTypeKeys', self
::$_dataTypeKeys);
296 // lets trim all the whitespace
297 $this->applyFilter('__ALL__', 'trim');
299 $attributes = CRM_Core_DAO
::getAttribute('CRM_Core_DAO_CustomField');
305 $attributes['label'],
309 $dt = &self
::$_dataTypeValues;
311 foreach ($dt as $key => $value) {
312 $it[$key] = self
::$_dataToLabels[$key];
314 $sel = &$this->addElement('hierselect',
316 ts('Data and Input Field Type'),
319 $sel->setOptions([$dt, $it]);
321 if (CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'is_multiple')) {
322 $this->add('checkbox', 'in_selector', ts('Display in Table?'));
325 $optionGroupParams = [
328 'options' => ['limit' => 0, 'sort' => "title ASC"],
329 'return' => ['title'],
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', 'Multi-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;
954 if ($dataTypeKey == 11 && !empty($params['filter_selected'])) {
955 if ($params['filter_selected'] == 'Advance' && trim(CRM_Utils_Array
::value('filter', $params))) {
956 $filter = trim($params['filter']);
958 elseif ($params['filter_selected'] == 'Group' && !empty($params['group_id'])) {
960 $filter = 'action=lookup&group=' . implode(',', $params['group_id']);
963 $params['filter'] = $filter;
967 if ($this->_action
& (CRM_Core_Action
::UPDATE | CRM_Core_Action
::ADD
)) {
968 $fieldValues = ['custom_group_id' => $this->_gid
];
970 $oldWeight = $this->_values
['weight'];
972 $params['weight'] = CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomField', $oldWeight, $params['weight'], $fieldValues);
975 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
977 //store the primary key for State/Province or Country as default value.
978 if (strlen(trim($params['default_value']))) {
979 switch ($params['data_type']) {
980 case 'StateProvince':
981 $fieldStateProvince = $strtolower($params['default_value']);
983 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
986 FROM civicrm_state_province
987 WHERE LOWER(name) = '$fieldStateProvince'
988 OR abbreviation = '$fieldStateProvince'";
989 $dao = CRM_Core_DAO
::executeQuery($query);
991 $params['default_value'] = $dao->id
;
996 $fieldCountry = $strtolower($params['default_value']);
998 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
1001 FROM civicrm_country
1002 WHERE LOWER(name) = '$fieldCountry'
1003 OR iso_code = '$fieldCountry'";
1004 $dao = CRM_Core_DAO
::executeQuery($query);
1005 if ($dao->fetch()) {
1006 $params['default_value'] = $dao->id
;
1012 // The text_length attribute for Memo fields is in a different input as there
1013 // are different label, help text and default value than for other type fields
1014 if ($params['data_type'] == "Memo") {
1015 $params['text_length'] = $params['note_length'];
1018 // need the FKEY - custom group id
1019 $params['custom_group_id'] = $this->_gid
;
1021 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
1022 $params['id'] = $this->_id
;
1024 $customField = CRM_Core_BAO_CustomField
::create($params);
1025 $this->_id
= $customField->id
;
1028 Civi
::cache('fields')->flush();
1030 $msg = '<p>' . ts("Custom field '%1' has been saved.", [1 => $customField->label
]) . '</p>';
1032 $buttonName = $this->controller
->getButtonName();
1033 $session = CRM_Core_Session
::singleton();
1034 if ($buttonName == $this->getButtonName('next', 'new')) {
1035 $msg .= '<p>' . ts("Ready to add another.") . '</p>';
1036 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/admin/custom/group/field/add',
1037 'reset=1&action=add&gid=' . $this->_gid
1041 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/admin/custom/group/field',
1042 'reset=1&action=browse&gid=' . $this->_gid
1045 $session->setStatus($msg, ts('Saved'), 'success');
1047 // Add data when in ajax contect
1048 $this->ajaxResponse
['customField'] = $customField->toArray();
1052 * Removes value from fields with no label.
1054 * This allows default values to be set in the form, but ignored in post-processing.
1056 * @param array $fields
1058 public static function clearEmptyOptions(&$fields) {
1059 foreach ($fields['option_label'] as $i => $label) {
1060 if (!strlen(trim($label))) {
1061 $fields['option_value'][$i] = '';