Merge pull request #17095 from civicrm/5.25
[civicrm-core.git] / CRM / Custom / Form / Field.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 * $Id$
17 *
18 */
19
20 /**
21 * form to process actions on the field aspect of Custom
22 */
23 class CRM_Custom_Form_Field extends CRM_Core_Form {
24
25 /**
26 * Constants for number of options for data types of multiple option.
27 */
28 const NUM_OPTION = 11;
29
30 /**
31 * The custom group id saved to the session for an update.
32 *
33 * @var int
34 */
35 protected $_gid;
36
37 /**
38 * The field id, used when editing the field
39 *
40 * @var int
41 */
42 protected $_id;
43
44 /**
45 * The default custom data/input types, when editing the field
46 *
47 * @var array
48 */
49 protected $_defaultDataType;
50
51 /**
52 * Array of custom field values if update mode.
53 * @var array
54 */
55 protected $_values;
56
57 /**
58 * Array for valid combinations of data_type & html_type
59 *
60 * @var array
61 */
62 private static $_dataTypeValues = NULL;
63 private static $_dataTypeKeys = NULL;
64
65 private static $_dataToLabels = NULL;
66
67 /**
68 * Used for mapping data types to html type options.
69 *
70 * Each item in this array corresponds to the same index in the dataType array
71 * @var array
72 */
73 public static $_dataToHTML = [
74 [
75 'Text' => 'Text',
76 'Select' => 'Select',
77 'Radio' => 'Radio',
78 'CheckBox' => 'CheckBox',
79 'Multi-Select' => 'Multi-Select',
80 'Autocomplete-Select' => 'Autocomplete-Select',
81 ],
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'],
87 ['Radio' => 'Radio'],
88 ['StateProvince' => 'Select State/Province', 'Multi-Select' => 'Multi-Select State/Province'],
89 ['Country' => 'Select Country', 'Multi-Select' => 'Multi-Select Country'],
90 ['File' => 'File'],
91 ['Link' => 'Link'],
92 ['ContactReference' => 'Autocomplete-Select'],
93 ];
94
95 /**
96 * Set variables up before form is built.
97 *
98 * @return void
99 */
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());
104 }
105
106 //custom field id
107 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
108
109 $this->_values = [];
110 //get the values form db if update.
111 if ($this->_id) {
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;
116 // custom group id
117 $this->_gid = $this->_values['custom_group_id'];
118 }
119 else {
120 // custom group id
121 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this);
122 }
123
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.");
126 }
127
128 if ($this->_gid) {
129 $url = CRM_Utils_System::url('civicrm/admin/custom/group/field',
130 "reset=1&action=browse&gid={$this->_gid}"
131 );
132
133 $session = CRM_Core_Session::singleton();
134 $session->pushUserContext($url);
135 }
136
137 if (self::$_dataToLabels == NULL) {
138 self::$_dataToLabels = [
139 [
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'),
146 ],
147 [
148 'Text' => ts('Text'),
149 'Select' => ts('Select'),
150 'Radio' => ts('Radio'),
151 ],
152 [
153 'Text' => ts('Text'),
154 'Select' => ts('Select'),
155 'Radio' => ts('Radio'),
156 ],
157 [
158 'Text' => ts('Text'),
159 'Select' => ts('Select'),
160 'Radio' => ts('Radio'),
161 ],
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')],
170 ];
171 }
172 }
173
174 /**
175 * Set default values for the form. Note that in edit/view mode
176 * the default values are retrieved from the database
177 *
178 * @return array
179 * array of default values
180 */
181 public function setDefaultValues() {
182 $defaults = $this->_values;
183
184 if ($this->_id) {
185 $this->assign('id', $this->_id);
186 $this->_gid = $defaults['custom_group_id'];
187
188 //get the value for state or country
189 if ($defaults['data_type'] == 'StateProvince' &&
190 $stateId = CRM_Utils_Array::value('default_value', $defaults)
191 ) {
192 $defaults['default_value'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_StateProvince', $stateId);
193 }
194 elseif ($defaults['data_type'] == 'Country' &&
195 $countryId = CRM_Utils_Array::value('default_value', $defaults)
196 ) {
197 $defaults['default_value'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Country', $countryId);
198 }
199
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
204 ) {
205 $filterParts = explode('&', $defaults['filter']);
206
207 if (count($filterParts) == 2) {
208 $contactRefFilter = 'Group';
209 foreach ($filterParts as $part) {
210 if (strpos($part, 'group=') === FALSE) {
211 continue;
212 }
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;
217 }
218 }
219 }
220 }
221 }
222 $defaults['filter_selected'] = $contactRefFilter;
223 }
224
225 if (!empty($defaults['data_type'])) {
226 $defaultDataType = array_search($defaults['data_type'],
227 self::$_dataTypeKeys
228 );
229 $defaultHTMLType = array_search($defaults['html_type'],
230 self::$_dataToHTML[$defaultDataType]
231 );
232 $defaults['data_type'] = [
233 '0' => $defaultDataType,
234 '1' => $defaultHTMLType,
235 ];
236 $this->_defaultDataType = $defaults['data_type'];
237 }
238
239 $defaults['option_type'] = 2;
240
241 $this->assign('changeFieldType', CRM_Custom_Form_ChangeFieldType::fieldTypeTransitions($this->_values['data_type'], $this->_values['html_type']));
242 }
243 else {
244 $defaults['is_active'] = 1;
245 $defaults['option_type'] = 1;
246 $defaults['is_search_range'] = 1;
247 }
248
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;
254 }
255
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);
259
260 $defaults['text_length'] = 255;
261 $defaults['note_columns'] = 60;
262 $defaults['note_rows'] = 4;
263 $defaults['is_view'] = 0;
264 }
265
266 if (!empty($defaults['html_type'])) {
267 $dontShowLink = substr($defaults['html_type'], -14) == 'State/Province' || substr($defaults['html_type'], -7) == 'Country' ? 1 : 0;
268 }
269
270 if (isset($dontShowLink)) {
271 $this->assign('dontShowLink', $dontShowLink);
272 }
273 if ($this->_action & CRM_Core_Action::ADD &&
274 CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_multiple', 'id')
275 ) {
276 $defaults['in_selector'] = 1;
277 }
278
279 return $defaults;
280 }
281
282 /**
283 * Build the form object.
284 *
285 * @return void
286 */
287 public function buildQuickForm() {
288 if ($this->_gid) {
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);
292 }
293
294 $this->assign('dataTypeKeys', self::$_dataTypeKeys);
295
296 // lets trim all the whitespace
297 $this->applyFilter('__ALL__', 'trim');
298
299 $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_CustomField');
300
301 // label
302 $this->add('text',
303 'label',
304 ts('Field Label'),
305 $attributes['label'],
306 TRUE
307 );
308
309 $dt = &self::$_dataTypeValues;
310 $it = [];
311 foreach ($dt as $key => $value) {
312 $it[$key] = self::$_dataToLabels[$key];
313 }
314 $sel = &$this->addElement('hierselect',
315 'data_type',
316 ts('Data and Input Field Type'),
317 '&nbsp;&nbsp;&nbsp;'
318 );
319 $sel->setOptions([$dt, $it]);
320
321 if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_multiple')) {
322 $this->add('checkbox', 'in_selector', ts('Display in Table?'));
323 }
324
325 $optionGroupParams = [
326 'is_reserved' => 0,
327 'is_active' => 1,
328 'options' => ['limit' => 0, 'sort' => "title ASC"],
329 'return' => ['title'],
330 ];
331
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"]];
339 }
340 }
341
342 // Retrieve optiongroups for selection list
343 $optionGroupMetadata = civicrm_api3('OptionGroup', 'get', $optionGroupParams);
344
345 // OptionGroup selection
346 $optionTypes = ['1' => ts('Create a new set of options')];
347
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');
352
353 $this->add('select',
354 'option_group_id',
355 ts('Multiple Choice Option Sets'),
356 [
357 '' => ts('- select -'),
358 ] + $optionGroups
359 );
360 }
361 else {
362 // No custom (non-reserved) option groups
363 $emptyOptGroup = TRUE;
364 }
365
366 $element = &$this->addRadio('option_type',
367 ts('Option Type'),
368 $optionTypes,
369 [
370 'onclick' => "showOptionSelect();",
371 ], '<br/>'
372 );
373 // if empty option group freeze the option type.
374 if ($emptyOptGroup) {
375 $element->freeze();
376 }
377
378 $contactGroups = CRM_Core_PseudoConstant::group();
379 asort($contactGroups);
380
381 $this->add('select',
382 'group_id',
383 ts('Limit List to Group'),
384 $contactGroups,
385 FALSE,
386 ['multiple' => 'multiple', 'class' => 'crm-select2']
387 );
388
389 $this->add('text',
390 'filter',
391 ts('Advanced Filter'),
392 $attributes['filter']
393 );
394
395 $this->add('hidden', 'filter_selected', 'Group', ['id' => 'filter_selected']);
396
397 // form fields of Custom Option rows
398 $defaultOption = [];
399 $_showHide = new CRM_Core_ShowHideBlocks('', '');
400 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
401
402 //the show hide blocks
403 $showBlocks = 'optionField_' . $i;
404 if ($i > 2) {
405 $_showHide->addHide($showBlocks);
406 if ($i == self::NUM_OPTION) {
407 $_showHide->addHide('additionalOption');
408 }
409 }
410 else {
411 $_showHide->addShow($showBlocks);
412 }
413
414 $optionAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue');
415 // label
416 $this->add('text', 'option_label[' . $i . ']', ts('Label'),
417 $optionAttributes['label']
418 );
419
420 // value
421 $this->add('text', 'option_value[' . $i . ']', ts('Value'),
422 $optionAttributes['value']
423 );
424
425 // weight
426 $this->add('number', "option_weight[$i]", ts('Order'),
427 $optionAttributes['weight']
428 );
429
430 // is active ?
431 $this->add('checkbox', "option_status[$i]", ts('Active?'));
432
433 $defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i);
434
435 //for checkbox handling of default option
436 $this->add('checkbox', "default_checkbox_option[$i]", NULL);
437 }
438
439 //default option selection
440 $this->addGroup($defaultOption, 'default_option');
441
442 $_showHide->addToTemplate();
443
444 // text length for alpha numeric data types
445 $this->add('number',
446 'text_length',
447 ts('Database field length'),
448 $attributes['text_length'] + ['min' => 1],
449 FALSE
450 );
451 $this->addRule('text_length', ts('Value should be a positive number'), 'integer');
452
453 $this->add('text',
454 'start_date_years',
455 ts('Dates may be up to'),
456 $attributes['start_date_years'],
457 FALSE
458 );
459 $this->add('text',
460 'end_date_years',
461 ts('Dates may be up to'),
462 $attributes['end_date_years'],
463 FALSE
464 );
465
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');
468
469 $this->add('select', 'date_format', ts('Date Format'),
470 ['' => ts('- select -')] + CRM_Core_SelectValues::getDatePluginInputFormats()
471 );
472
473 $this->add('select', 'time_format', ts('Time'),
474 ['' => ts('- none -')] + CRM_Core_SelectValues::getTimeFormats()
475 );
476
477 // for Note field
478 $this->add('number',
479 'note_columns',
480 ts('Width (columns)') . ' ',
481 $attributes['note_columns'],
482 FALSE
483 );
484 $this->add('number',
485 'note_rows',
486 ts('Height (rows)') . ' ',
487 $attributes['note_rows'],
488 FALSE
489 );
490 $this->add('number',
491 'note_length',
492 ts('Maximum length') . ' ',
493 // note_length is an alias for the text-length field
494 $attributes['text_length'],
495 FALSE
496 );
497
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');
501
502 // weight
503 $this->add('number', 'weight', ts('Order'),
504 $attributes['weight'],
505 TRUE
506 );
507 $this->addRule('weight', ts('is a numeric field'), 'numeric');
508
509 // is required ?
510 $this->add('advcheckbox', 'is_required', ts('Required?'));
511
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');
515
516 // default value, help pre, help post, mask, attributes, javascript ?
517 $this->add('text', 'default_value', ts('Default Value'),
518 $attributes['default_value']
519 );
520 $this->add('textarea', 'help_pre', ts('Field Pre Help'),
521 $attributes['help_pre']
522 );
523 $this->add('textarea', 'help_post', ts('Field Post Help'),
524 $attributes['help_post']
525 );
526 $this->add('text', 'mask', ts('Mask'),
527 $attributes['mask']
528 );
529
530 // is active ?
531 $this->add('advcheckbox', 'is_active', ts('Active?'));
532
533 // is active ?
534 $this->add('advcheckbox', 'is_view', ts('View Only?'));
535
536 // is searchable ?
537 $this->addElement('advcheckbox',
538 'is_searchable',
539 ts('Is this Field Searchable?')
540 );
541
542 // is searchable by range?
543 $searchRange = [];
544 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('Yes'), '1');
545 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('No'), '0');
546
547 $this->addGroup($searchRange, 'is_search_range', ts('Search by Range?'));
548
549 // add buttons
550 $this->addButtons([
551 [
552 'type' => 'done',
553 'name' => ts('Save'),
554 'isDefault' => TRUE,
555 ],
556 [
557 'type' => 'next',
558 'name' => ts('Save and New'),
559 'subName' => 'new',
560 ],
561 [
562 'type' => 'cancel',
563 'name' => ts('Cancel'),
564 ],
565 ]);
566
567 // add a form rule to check default value
568 $this->addFormRule(['CRM_Custom_Form_Field', 'formRule'], $this);
569
570 // if view mode pls freeze it with the done button.
571 if ($this->_action & CRM_Core_Action::VIEW) {
572 $this->freeze();
573 $url = CRM_Utils_System::url('civicrm/admin/custom/group/field', 'reset=1&action=browse&gid=' . $this->_gid);
574 $this->addElement('button',
575 'done',
576 ts('Done'),
577 ['onclick' => "location.href='$url'"]
578 );
579 }
580 }
581
582 /**
583 * Global validation rules for the form.
584 *
585 * @param array $fields
586 * Posted values of the form.
587 *
588 * @param $files
589 * @param $self
590 *
591 * @return array
592 * if errors then list of errors to be posted back to the form,
593 * true otherwise
594 */
595 public static function formRule($fields, $files, $self) {
596 $default = $fields['default_value'] ?? NULL;
597
598 $errors = [];
599
600 self::clearEmptyOptions($fields);
601
602 //validate field label as well as name.
603 $title = $fields['label'];
604 $name = CRM_Utils_String::munge($title, '_', 64);
605 // CRM-7564
606 $gId = $self->_gid;
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'],
613 ]);
614 if ($fldCnt) {
615 $errors['label'] = ts('Custom field \'%1\' already exists in Database.', [1 => $title]);
616 }
617
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");
624 }
625 }
626
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.");
630 }
631
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.');
634 }
635
636 $dataType = self::$_dataTypeKeys[$fields['data_type'][0]];
637
638 if ($default || $dataType == 'ContactReference') {
639 switch ($dataType) {
640 case 'Int':
641 if (!CRM_Utils_Rule::integer($default)) {
642 $errors['default_value'] = ts('Please enter a valid integer.');
643 }
644 break;
645
646 case 'Float':
647 if (!CRM_Utils_Rule::numeric($default)) {
648 $errors['default_value'] = ts('Please enter a valid number.');
649 }
650 break;
651
652 case 'Money':
653 if (!CRM_Utils_Rule::money($default)) {
654 $errors['default_value'] = ts('Please enter a valid number.');
655 }
656 break;
657
658 case 'Link':
659 if (!CRM_Utils_Rule::url($default)) {
660 $errors['default_value'] = ts('Please enter a valid link.');
661 }
662 break;
663
664 case 'Date':
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.');
667 }
668 break;
669
670 case 'Boolean':
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.');
673 }
674 break;
675
676 case 'Country':
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.');
682 }
683 }
684 break;
685
686 case 'StateProvince':
687 if (!empty($default)) {
688 $query = "
689 SELECT count(*)
690 FROM civicrm_state_province
691 WHERE name = %1
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');
696 }
697 }
698 break;
699
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')");
704 }
705 elseif (strpos($fields['filter'], 'action=get') === FALSE) {
706 $errors['filter'] = ts("Only 'get' action is supported.");
707 }
708 }
709 $self->setDefaults(['filter_selected', $fields['filter_selected']]);
710 break;
711 }
712 }
713
714 if (self::$_dataTypeKeys[$fields['data_type'][0]] == 'Date') {
715 if (!$fields['date_format']) {
716 $errors['date_format'] = ts('Please select a date format.');
717 }
718 }
719
720 /** Check the option values entered
721 * Appropriate values are required for the selected datatype
722 * Incomplete row checking is also required.
723 */
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];
729 }
730 $optionFields = ['Select', 'Multi-Select', 'CheckBox', 'Radio'];
731
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']));
737
738 if ($countValue > $uniqueCount) {
739
740 $start = 1;
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])
746 ) {
747 $errors['option_value[' . $start . ']'] = ts('Duplicate Option values');
748 $errors['option_value[' . $nextIndex . ']'] = ts('Duplicate Option values');
749 $_flagOption = 1;
750 }
751 $nextIndex++;
752 }
753 $start++;
754 }
755 }
756 }
757
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']));
762
763 if ($countValue > $uniqueCount) {
764 $start = 1;
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])
770 ) {
771 $errors['option_label[' . $start . ']'] = ts('Duplicate Option label');
772 $errors['option_label[' . $nextIndex . ']'] = ts('Duplicate Option label');
773 $_flagOption = 1;
774 }
775 $nextIndex++;
776 }
777 $start++;
778 }
779 }
780 }
781
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');
786 $_flagOption = 1;
787 }
788 else {
789 $_emptyRow = 1;
790 }
791 }
792 else {
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');
796 $_flagOption = 1;
797 }
798 }
799 }
800
801 if ($fields['option_value'][$i] && $dataType != 'String') {
802 if ($dataType == 'Int') {
803 if (!CRM_Utils_Rule::integer($fields['option_value'][$i])) {
804 $_flagOption = 1;
805 $errors['option_value[' . $i . ']'] = ts('Please enter a valid integer.');
806 }
807 }
808 elseif ($dataType == 'Money') {
809 if (!CRM_Utils_Rule::money($fields['option_value'][$i])) {
810 $_flagOption = 1;
811 $errors['option_value[' . $i . ']'] = ts('Please enter a valid money value.');
812 }
813 }
814 else {
815 if (!CRM_Utils_Rule::numeric($fields['option_value'][$i])) {
816 $_flagOption = 1;
817 $errors['option_value[' . $i . ']'] = ts('Please enter a valid number.');
818 }
819 }
820 }
821
822 $showBlocks = 'optionField_' . $i;
823 if ($_flagOption) {
824 $_showHide->addShow($showBlocks);
825 $_rowError = 1;
826 }
827
828 if (!empty($_emptyRow)) {
829 $_showHide->addHide($showBlocks);
830 }
831 else {
832 $_showHide->addShow($showBlocks);
833 }
834 if ($i == self::NUM_OPTION) {
835 $hideBlock = 'additionalOption';
836 $_showHide->addHide($hideBlock);
837 }
838
839 $_flagOption = $_emptyRow = 0;
840 }
841 }
842 elseif (isset($dataField) &&
843 in_array($dataField, $optionFields) &&
844 !in_array($dataType, ['Boolean', 'Country', 'StateProvince'])
845 ) {
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.');
848 }
849 else {
850 $query = "
851 SELECT count(*)
852 FROM civicrm_custom_field
853 WHERE data_type != %1
854 AND option_group_id = %2";
855 $params = [
856 1 => [
857 self::$_dataTypeKeys[$fields['data_type'][0]],
858 'String',
859 ],
860 2 => [$fields['option_group_id'], 'Integer'],
861 ];
862 $count = CRM_Core_DAO::singleValueQuery($query, $params);
863 if ($count > 0) {
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.');
865 }
866 }
867 }
868
869 $assignError = new CRM_Core_Page();
870 if ($_rowError) {
871 $_showHide->addToTemplate();
872 $assignError->assign('optionRowError', $_rowError);
873 }
874 else {
875 if (isset($fields['data_type'][1])) {
876 switch (self::$_dataToHTML[$fields['data_type'][0]][$fields['data_type'][1]]) {
877 case 'Radio':
878 $_fieldError = 1;
879 $assignError->assign('fieldError', $_fieldError);
880 break;
881
882 case 'Checkbox':
883 $_fieldError = 1;
884 $assignError->assign('fieldError', $_fieldError);
885 break;
886
887 case 'Select':
888 $_fieldError = 1;
889 $assignError->assign('fieldError', $_fieldError);
890 break;
891
892 default:
893 $_fieldError = 0;
894 $assignError->assign('fieldError', $_fieldError);
895 }
896 }
897
898 for ($idx = 1; $idx <= self::NUM_OPTION; $idx++) {
899 $showBlocks = 'optionField_' . $idx;
900 if (!empty($fields['option_label'][$idx])) {
901 $_showHide->addShow($showBlocks);
902 }
903 else {
904 $_showHide->addHide($showBlocks);
905 }
906 }
907 $_showHide->addToTemplate();
908 }
909
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.');
913 }
914
915 return empty($errors) ? TRUE : $errors;
916 }
917
918 /**
919 * Process the form.
920 *
921 * @return void
922 */
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]];
931 }
932 else {
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]];
936 }
937
938 //fix for 'is_search_range' field.
939 if (in_array($dataTypeKey, [
940 1,
941 2,
942 3,
943 5,
944 ])) {
945 if (empty($params['is_searchable'])) {
946 $params['is_search_range'] = 0;
947 }
948 }
949 else {
950 $params['is_search_range'] = 0;
951 }
952
953 $filter = 'null';
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']);
957 }
958 elseif ($params['filter_selected'] == 'Group' && !empty($params['group_id'])) {
959
960 $filter = 'action=lookup&group=' . implode(',', $params['group_id']);
961 }
962 }
963 $params['filter'] = $filter;
964
965 // fix for CRM-316
966 $oldWeight = NULL;
967 if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
968 $fieldValues = ['custom_group_id' => $this->_gid];
969 if ($this->_id) {
970 $oldWeight = $this->_values['weight'];
971 }
972 $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_CustomField', $oldWeight, $params['weight'], $fieldValues);
973 }
974
975 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
976
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']);
982
983 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
984 $query = "
985 SELECT id
986 FROM civicrm_state_province
987 WHERE LOWER(name) = '$fieldStateProvince'
988 OR abbreviation = '$fieldStateProvince'";
989 $dao = CRM_Core_DAO::executeQuery($query);
990 if ($dao->fetch()) {
991 $params['default_value'] = $dao->id;
992 }
993 break;
994
995 case 'Country':
996 $fieldCountry = $strtolower($params['default_value']);
997
998 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
999 $query = "
1000 SELECT id
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;
1007 }
1008 break;
1009 }
1010 }
1011
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'];
1016 }
1017
1018 // need the FKEY - custom group id
1019 $params['custom_group_id'] = $this->_gid;
1020
1021 if ($this->_action & CRM_Core_Action::UPDATE) {
1022 $params['id'] = $this->_id;
1023 }
1024 $customField = CRM_Core_BAO_CustomField::create($params);
1025 $this->_id = $customField->id;
1026
1027 // reset the cache
1028 Civi::cache('fields')->flush();
1029
1030 $msg = '<p>' . ts("Custom field '%1' has been saved.", [1 => $customField->label]) . '</p>';
1031
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
1038 ));
1039 }
1040 else {
1041 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field',
1042 'reset=1&action=browse&gid=' . $this->_gid
1043 ));
1044 }
1045 $session->setStatus($msg, ts('Saved'), 'success');
1046
1047 // Add data when in ajax contect
1048 $this->ajaxResponse['customField'] = $customField->toArray();
1049 }
1050
1051 /**
1052 * Removes value from fields with no label.
1053 *
1054 * This allows default values to be set in the form, but ignored in post-processing.
1055 *
1056 * @param array $fields
1057 */
1058 public static function clearEmptyOptions(&$fields) {
1059 foreach ($fields['option_label'] as $i => $label) {
1060 if (!strlen(trim($label))) {
1061 $fields['option_value'][$i] = '';
1062 }
1063 }
1064 }
1065
1066 }