[REF] Refactor to use the standard CRM_Core_Form::addRadio function for a number...
[civicrm-core.git] / CRM / Custom / Form / Field.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
19 * form to process actions on the field aspect of Custom
20 */
21class CRM_Custom_Form_Field extends CRM_Core_Form {
22
23 /**
24 * Constants for number of options for data types of multiple option.
25 */
7da04cde 26 const NUM_OPTION = 11;
6a488035
TO
27
28 /**
fe482240 29 * The custom group id saved to the session for an update.
6a488035
TO
30 *
31 * @var int
6a488035
TO
32 */
33 protected $_gid;
34
35 /**
36 * The field id, used when editing the field
37 *
38 * @var int
6a488035
TO
39 */
40 protected $_id;
41
42 /**
43 * The default custom data/input types, when editing the field
44 *
45 * @var array
6a488035
TO
46 */
47 protected $_defaultDataType;
48
49 /**
fe482240 50 * Array of custom field values if update mode.
518fa0ee 51 * @var array
6a488035
TO
52 */
53 protected $_values;
54
55 /**
56 * Array for valid combinations of data_type & html_type
57 *
58 * @var array
6a488035
TO
59 */
60 private static $_dataTypeValues = NULL;
61 private static $_dataTypeKeys = NULL;
62
6a488035
TO
63 private static $_dataToLabels = NULL;
64
5d2f1ed6
CW
65 /**
66 * Used for mapping data types to html type options.
67 *
68 * Each item in this array corresponds to the same index in the dataType array
69 * @var array
70 */
71 public static $_dataToHTML = [
72 [
73 'Text' => 'Text',
74 'Select' => 'Select',
75 'Radio' => 'Radio',
76 'CheckBox' => 'CheckBox',
5d2f1ed6
CW
77 'Autocomplete-Select' => 'Autocomplete-Select',
78 ],
79 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
80 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
81 ['Text' => 'Text', 'Select' => 'Select', 'Radio' => 'Radio'],
82 ['TextArea' => 'TextArea', 'RichTextEditor' => 'RichTextEditor'],
83 ['Date' => 'Select Date'],
84 ['Radio' => 'Radio'],
3221e413
CW
85 ['StateProvince' => 'Select State/Province'],
86 ['Country' => 'Select Country'],
5d2f1ed6
CW
87 ['File' => 'File'],
88 ['Link' => 'Link'],
89 ['ContactReference' => 'Autocomplete-Select'],
90 ];
91
6a488035 92 /**
fe482240 93 * Set variables up before form is built.
6a488035 94 *
6a488035 95 * @return void
6a488035
TO
96 */
97 public function preProcess() {
98 if (!(self::$_dataTypeKeys)) {
99 self::$_dataTypeKeys = array_keys(CRM_Core_BAO_CustomField::dataType());
100 self::$_dataTypeValues = array_values(CRM_Core_BAO_CustomField::dataType());
101 }
102
2b83aa0d
CW
103 //custom field id
104 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
105
be2fb01f 106 $this->_values = [];
2b83aa0d
CW
107 //get the values form db if update.
108 if ($this->_id) {
be2fb01f 109 $params = ['id' => $this->_id];
2b83aa0d
CW
110 CRM_Core_BAO_CustomField::retrieve($params, $this->_values);
111 // note_length is an alias for the text_length field
9c1bc317 112 $this->_values['note_length'] = $this->_values['text_length'] ?? NULL;
2b83aa0d
CW
113 // custom group id
114 $this->_gid = $this->_values['custom_group_id'];
115 }
116 else {
117 // custom group id
118 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this);
119 }
6a488035 120
d06700a7 121 if ($isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_reserved', 'id')) {
79e11805 122 CRM_Core_Error::statusBounce("You cannot add or edit fields in a reserved custom field-set.");
d06700a7
RN
123 }
124
6a488035
TO
125 if ($this->_gid) {
126 $url = CRM_Utils_System::url('civicrm/admin/custom/group/field',
127 "reset=1&action=browse&gid={$this->_gid}"
128 );
129
130 $session = CRM_Core_Session::singleton();
131 $session->pushUserContext($url);
132 }
133
6a488035 134 if (self::$_dataToLabels == NULL) {
be2fb01f
CW
135 self::$_dataToLabels = [
136 [
353ffa53
TO
137 'Text' => ts('Text'),
138 'Select' => ts('Select'),
e8646905 139 'Radio' => ts('Radio'),
353ffa53 140 'CheckBox' => ts('CheckBox'),
79dc94e4 141 'Autocomplete-Select' => ts('Autocomplete-Select'),
be2fb01f
CW
142 ],
143 [
353ffa53
TO
144 'Text' => ts('Text'),
145 'Select' => ts('Select'),
6a488035 146 'Radio' => ts('Radio'),
be2fb01f
CW
147 ],
148 [
353ffa53
TO
149 'Text' => ts('Text'),
150 'Select' => ts('Select'),
6a488035 151 'Radio' => ts('Radio'),
be2fb01f
CW
152 ],
153 [
353ffa53
TO
154 'Text' => ts('Text'),
155 'Select' => ts('Select'),
6a488035 156 'Radio' => ts('Radio'),
be2fb01f
CW
157 ],
158 ['TextArea' => ts('TextArea'), 'RichTextEditor' => ts('Rich Text Editor')],
159 ['Date' => ts('Select Date')],
160 ['Radio' => ts('Radio')],
3221e413
CW
161 ['StateProvince' => ts('Select State/Province')],
162 ['Country' => ts('Select Country')],
be2fb01f
CW
163 ['File' => ts('Select File')],
164 ['Link' => ts('Link')],
165 ['ContactReference' => ts('Autocomplete-Select')],
166 ];
6a488035
TO
167 }
168 }
169
170 /**
c490a46a 171 * Set default values for the form. Note that in edit/view mode
6a488035
TO
172 * the default values are retrieved from the database
173 *
a6c01b45
CW
174 * @return array
175 * array of default values
6a488035 176 */
00be9182 177 public function setDefaultValues() {
6a488035
TO
178 $defaults = $this->_values;
179
180 if ($this->_id) {
181 $this->assign('id', $this->_id);
182 $this->_gid = $defaults['custom_group_id'];
183
184 //get the value for state or country
185 if ($defaults['data_type'] == 'StateProvince' &&
186 $stateId = CRM_Utils_Array::value('default_value', $defaults)
187 ) {
188 $defaults['default_value'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_StateProvince', $stateId);
189 }
190 elseif ($defaults['data_type'] == 'Country' &&
191 $countryId = CRM_Utils_Array::value('default_value', $defaults)
192 ) {
193 $defaults['default_value'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Country', $countryId);
194 }
195
8cc574cf 196 if ($defaults['data_type'] == 'ContactReference' && !empty($defaults['filter'])) {
6a488035
TO
197 $contactRefFilter = 'Advance';
198 if (strpos($defaults['filter'], 'action=lookup') !== FALSE &&
199 strpos($defaults['filter'], 'group=') !== FALSE
200 ) {
201 $filterParts = explode('&', $defaults['filter']);
202
203 if (count($filterParts) == 2) {
204 $contactRefFilter = 'Group';
205 foreach ($filterParts as $part) {
206 if (strpos($part, 'group=') === FALSE) {
207 continue;
208 }
209 $groups = substr($part, strpos($part, '=') + 1);
210 foreach (explode(',', $groups) as $grp) {
211 if (CRM_Utils_Rule::positiveInteger($grp)) {
212 $defaults['group_id'][] = $grp;
213 }
214 }
215 }
216 }
217 }
218 $defaults['filter_selected'] = $contactRefFilter;
219 }
220
a7488080 221 if (!empty($defaults['data_type'])) {
6a488035
TO
222 $defaultDataType = array_search($defaults['data_type'],
223 self::$_dataTypeKeys
224 );
225 $defaultHTMLType = array_search($defaults['html_type'],
226 self::$_dataToHTML[$defaultDataType]
227 );
be2fb01f 228 $defaults['data_type'] = [
6a488035
TO
229 '0' => $defaultDataType,
230 '1' => $defaultHTMLType,
be2fb01f 231 ];
6a488035
TO
232 $this->_defaultDataType = $defaults['data_type'];
233 }
234
235 $defaults['option_type'] = 2;
236
237 $this->assign('changeFieldType', CRM_Custom_Form_ChangeFieldType::fieldTypeTransitions($this->_values['data_type'], $this->_values['html_type']));
238 }
239 else {
240 $defaults['is_active'] = 1;
241 $defaults['option_type'] = 1;
9edef7c7 242 $defaults['is_search_range'] = 1;
6a488035
TO
243 }
244
245 // set defaults for weight.
246 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
247 $defaults['option_status[' . $i . ']'] = 1;
248 $defaults['option_weight[' . $i . ']'] = $i;
f3631c02 249 $defaults['option_value[' . $i . ']'] = $i;
6a488035
TO
250 }
251
252 if ($this->_action & CRM_Core_Action::ADD) {
be2fb01f 253 $fieldValues = ['custom_group_id' => $this->_gid];
6a488035
TO
254 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_CustomField', $fieldValues);
255
256 $defaults['text_length'] = 255;
257 $defaults['note_columns'] = 60;
258 $defaults['note_rows'] = 4;
259 $defaults['is_view'] = 0;
260 }
261
a7488080 262 if (!empty($defaults['html_type'])) {
6a488035
TO
263 $dontShowLink = substr($defaults['html_type'], -14) == 'State/Province' || substr($defaults['html_type'], -7) == 'Country' ? 1 : 0;
264 }
265
266 if (isset($dontShowLink)) {
267 $this->assign('dontShowLink', $dontShowLink);
268 }
e41f4660 269 if ($this->_action & CRM_Core_Action::ADD &&
353ffa53
TO
270 CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_multiple', 'id')
271 ) {
5a205b89
PJ
272 $defaults['in_selector'] = 1;
273 }
274
6a488035
TO
275 return $defaults;
276 }
277
278 /**
fe482240 279 * Build the form object.
6a488035 280 *
6a488035 281 * @return void
6a488035
TO
282 */
283 public function buildQuickForm() {
284 if ($this->_gid) {
285 $this->_title = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'title');
e2046b33 286 CRM_Utils_System::setTitle($this->_title . ' - ' . ($this->_id ? ts('Edit Field') : ts('New Field')));
fa3a5fe2 287 $this->assign('gid', $this->_gid);
6a488035
TO
288 }
289
9edef7c7
CW
290 $this->assign('dataTypeKeys', self::$_dataTypeKeys);
291
6a488035
TO
292 // lets trim all the whitespace
293 $this->applyFilter('__ALL__', 'trim');
294
295 $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_CustomField');
296
297 // label
298 $this->add('text',
299 'label',
300 ts('Field Label'),
301 $attributes['label'],
302 TRUE
303 );
304
305 $dt = &self::$_dataTypeValues;
be2fb01f 306 $it = [];
6a488035
TO
307 foreach ($dt as $key => $value) {
308 $it[$key] = self::$_dataToLabels[$key];
309 }
310 $sel = &$this->addElement('hierselect',
311 'data_type',
312 ts('Data and Input Field Type'),
6a488035
TO
313 '&nbsp;&nbsp;&nbsp;'
314 );
be2fb01f 315 $sel->setOptions([$dt, $it]);
5a205b89
PJ
316
317 if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_multiple')) {
318 $this->add('checkbox', 'in_selector', ts('Display in Table?'));
319 }
320
064d8685
MWMC
321 $optionGroupParams = [
322 'is_reserved' => 0,
323 'is_active' => 1,
324 'options' => ['limit' => 0, 'sort' => "title ASC"],
325 'return' => ['title'],
326 ];
c0fce6be 327
fdd11b39
CW
328 $this->add('checkbox', 'serialize', ts('Multi-Select'));
329
6a488035 330 if ($this->_action == CRM_Core_Action::UPDATE) {
064d8685 331 $this->freeze('data_type');
8ec434ed
MWMC
332 if (!empty($this->_values['option_group_id'])) {
333 // Before dev/core#155 we didn't set the is_reserved flag properly, which should be handled by the upgrade script...
334 // but it is still possible that existing installs may have optiongroups linked to custom fields that are marked reserved.
335 $optionGroupParams['id'] = $this->_values['option_group_id'];
336 $optionGroupParams['options']['or'] = [["is_reserved", "id"]];
337 }
f46ffe84
MWMC
338 }
339
064d8685 340 // Retrieve optiongroups for selection list
c0fce6be
MW
341 $optionGroupMetadata = civicrm_api3('OptionGroup', 'get', $optionGroupParams);
342
343 // OptionGroup selection
be2fb01f 344 $optionTypes = ['1' => ts('Create a new set of options')];
c0fce6be
MW
345
346 if (!empty($optionGroupMetadata['values'])) {
347 $emptyOptGroup = FALSE;
348 $optionGroups = CRM_Utils_Array::collect('title', $optionGroupMetadata['values']);
349 $optionTypes['2'] = ts('Reuse an existing set');
6a488035
TO
350
351 $this->add('select',
352 'option_group_id',
353 ts('Multiple Choice Option Sets'),
be2fb01f 354 [
7c550ca0 355 '' => ts('- select -'),
be2fb01f 356 ] + $optionGroups
6a488035
TO
357 );
358 }
c0fce6be
MW
359 else {
360 // No custom (non-reserved) option groups
361 $emptyOptGroup = TRUE;
362 }
6a488035
TO
363
364 $element = &$this->addRadio('option_type',
365 ts('Option Type'),
366 $optionTypes,
be2fb01f 367 [
7c550ca0 368 'onclick' => "showOptionSelect();",
be2fb01f 369 ], '<br/>'
6a488035 370 );
c0fce6be
MW
371 // if empty option group freeze the option type.
372 if ($emptyOptGroup) {
373 $element->freeze();
374 }
6a488035 375
6a488035
TO
376 $contactGroups = CRM_Core_PseudoConstant::group();
377 asort($contactGroups);
378
379 $this->add('select',
380 'group_id',
381 ts('Limit List to Group'),
382 $contactGroups,
383 FALSE,
be2fb01f 384 ['multiple' => 'multiple', 'class' => 'crm-select2']
6a488035
TO
385 );
386
387 $this->add('text',
388 'filter',
389 ts('Advanced Filter'),
390 $attributes['filter']
391 );
392
be2fb01f 393 $this->add('hidden', 'filter_selected', 'Group', ['id' => 'filter_selected']);
6a488035 394
6a488035 395 // form fields of Custom Option rows
be2fb01f 396 $defaultOption = [];
6a488035
TO
397 $_showHide = new CRM_Core_ShowHideBlocks('', '');
398 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
399
400 //the show hide blocks
401 $showBlocks = 'optionField_' . $i;
402 if ($i > 2) {
403 $_showHide->addHide($showBlocks);
404 if ($i == self::NUM_OPTION) {
405 $_showHide->addHide('additionalOption');
406 }
407 }
408 else {
409 $_showHide->addShow($showBlocks);
410 }
411
412 $optionAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue');
413 // label
414 $this->add('text', 'option_label[' . $i . ']', ts('Label'),
415 $optionAttributes['label']
416 );
417
418 // value
419 $this->add('text', 'option_value[' . $i . ']', ts('Value'),
420 $optionAttributes['value']
421 );
422
423 // weight
f20d2b0d 424 $this->add('number', "option_weight[$i]", ts('Order'),
6a488035
TO
425 $optionAttributes['weight']
426 );
427
428 // is active ?
429 $this->add('checkbox', "option_status[$i]", ts('Active?'));
430
431 $defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i);
432
433 //for checkbox handling of default option
434 $this->add('checkbox', "default_checkbox_option[$i]", NULL);
435 }
436
437 //default option selection
438 $this->addGroup($defaultOption, 'default_option');
439
440 $_showHide->addToTemplate();
441
442 // text length for alpha numeric data types
8fab1e25 443 $this->add('number',
6a488035
TO
444 'text_length',
445 ts('Database field length'),
be2fb01f 446 $attributes['text_length'] + ['min' => 1],
6a488035
TO
447 FALSE
448 );
449 $this->addRule('text_length', ts('Value should be a positive number'), 'integer');
450
451 $this->add('text',
452 'start_date_years',
453 ts('Dates may be up to'),
454 $attributes['start_date_years'],
455 FALSE
456 );
457 $this->add('text',
458 'end_date_years',
459 ts('Dates may be up to'),
460 $attributes['end_date_years'],
461 FALSE
462 );
463
464 $this->addRule('start_date_years', ts('Value should be a positive number'), 'integer');
465 $this->addRule('end_date_years', ts('Value should be a positive number'), 'integer');
466
467 $this->add('select', 'date_format', ts('Date Format'),
be2fb01f 468 ['' => ts('- select -')] + CRM_Core_SelectValues::getDatePluginInputFormats()
6a488035
TO
469 );
470
471 $this->add('select', 'time_format', ts('Time'),
be2fb01f 472 ['' => ts('- none -')] + CRM_Core_SelectValues::getTimeFormats()
6a488035
TO
473 );
474
475 // for Note field
8fab1e25 476 $this->add('number',
6a488035
TO
477 'note_columns',
478 ts('Width (columns)') . ' ',
479 $attributes['note_columns'],
480 FALSE
481 );
8fab1e25 482 $this->add('number',
6a488035
TO
483 'note_rows',
484 ts('Height (rows)') . ' ',
485 $attributes['note_rows'],
486 FALSE
487 );
8fab1e25 488 $this->add('number',
2f940a36
NG
489 'note_length',
490 ts('Maximum length') . ' ',
518fa0ee
SL
491 // note_length is an alias for the text-length field
492 $attributes['text_length'],
2f940a36
NG
493 FALSE
494 );
6a488035
TO
495
496 $this->addRule('note_columns', ts('Value should be a positive number'), 'positiveInteger');
497 $this->addRule('note_rows', ts('Value should be a positive number'), 'positiveInteger');
2f940a36 498 $this->addRule('note_length', ts('Value should be a positive number'), 'positiveInteger');
6a488035
TO
499
500 // weight
8fab1e25 501 $this->add('number', 'weight', ts('Order'),
6a488035
TO
502 $attributes['weight'],
503 TRUE
504 );
505 $this->addRule('weight', ts('is a numeric field'), 'numeric');
506
507 // is required ?
ccbeed45 508 $this->add('advcheckbox', 'is_required', ts('Required?'));
6a488035
TO
509
510 // checkbox / radio options per line
be2fb01f 511 $this->add('number', 'options_per_line', ts('Options Per Line'), ['min' => 0]);
6a488035
TO
512 $this->addRule('options_per_line', ts('must be a numeric value'), 'numeric');
513
514 // default value, help pre, help post, mask, attributes, javascript ?
515 $this->add('text', 'default_value', ts('Default Value'),
516 $attributes['default_value']
517 );
518 $this->add('textarea', 'help_pre', ts('Field Pre Help'),
519 $attributes['help_pre']
520 );
521 $this->add('textarea', 'help_post', ts('Field Post Help'),
522 $attributes['help_post']
523 );
524 $this->add('text', 'mask', ts('Mask'),
525 $attributes['mask']
526 );
527
528 // is active ?
1ed38c40 529 $this->add('advcheckbox', 'is_active', ts('Active?'));
6a488035
TO
530
531 // is active ?
ccbeed45 532 $this->add('advcheckbox', 'is_view', ts('View Only?'));
6a488035
TO
533
534 // is searchable ?
ccbeed45 535 $this->addElement('advcheckbox',
6a488035 536 'is_searchable',
9edef7c7 537 ts('Is this Field Searchable?')
6a488035
TO
538 );
539
540 // is searchable by range?
39405208 541 $this->addRadio('is_search_range', ts('Search by Range?'), [ts('No'), ts('Yes')]);
6a488035
TO
542
543 // add buttons
be2fb01f 544 $this->addButtons([
518fa0ee
SL
545 [
546 'type' => 'done',
547 'name' => ts('Save'),
548 'isDefault' => TRUE,
549 ],
550 [
551 'type' => 'next',
552 'name' => ts('Save and New'),
553 'subName' => 'new',
554 ],
555 [
556 'type' => 'cancel',
557 'name' => ts('Cancel'),
558 ],
559 ]);
6a488035
TO
560
561 // add a form rule to check default value
be2fb01f 562 $this->addFormRule(['CRM_Custom_Form_Field', 'formRule'], $this);
6a488035
TO
563
564 // if view mode pls freeze it with the done button.
565 if ($this->_action & CRM_Core_Action::VIEW) {
566 $this->freeze();
567 $url = CRM_Utils_System::url('civicrm/admin/custom/group/field', 'reset=1&action=browse&gid=' . $this->_gid);
568 $this->addElement('button',
569 'done',
570 ts('Done'),
be2fb01f 571 ['onclick' => "location.href='$url'"]
6a488035
TO
572 );
573 }
574 }
575
576 /**
fe482240 577 * Global validation rules for the form.
6a488035 578 *
c4ca4892
TO
579 * @param array $fields
580 * Posted values of the form.
77b97be7
EM
581 *
582 * @param $files
583 * @param $self
6a488035 584 *
a6c01b45
CW
585 * @return array
586 * if errors then list of errors to be posted back to the form,
6a488035 587 * true otherwise
6a488035 588 */
00be9182 589 public static function formRule($fields, $files, $self) {
9c1bc317 590 $default = $fields['default_value'] ?? NULL;
6a488035 591
be2fb01f 592 $errors = [];
6a488035 593
f3631c02
CW
594 self::clearEmptyOptions($fields);
595
6a488035 596 //validate field label as well as name.
353ffa53
TO
597 $title = $fields['label'];
598 $name = CRM_Utils_String::munge($title, '_', 64);
518fa0ee
SL
599 // CRM-7564
600 $gId = $self->_gid;
353ffa53 601 $query = 'select count(*) from civicrm_custom_field where ( name like %1 OR label like %2 ) and id != %3 and custom_group_id = %4';
be2fb01f
CW
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'],
607 ]);
6a488035 608 if ($fldCnt) {
be2fb01f 609 $errors['label'] = ts('Custom field \'%1\' already exists in Database.', [1 => $title]);
6a488035
TO
610 }
611
612 //checks the given custom field name doesnot start with digit
613 if (!empty($title)) {
614 // gives the ascii value
84ce59b1 615 $asciiValue = ord($title[0]);
6a488035 616 if ($asciiValue >= 48 && $asciiValue <= 57) {
5ab78070 617 $errors['label'] = ts("Name cannot not start with a digit");
6a488035
TO
618 }
619 }
620
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.");
624 }
625
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.');
628 }
629
630 $dataType = self::$_dataTypeKeys[$fields['data_type'][0]];
631
632 if ($default || $dataType == 'ContactReference') {
633 switch ($dataType) {
634 case 'Int':
635 if (!CRM_Utils_Rule::integer($default)) {
5ab78070 636 $errors['default_value'] = ts('Please enter a valid integer.');
6a488035
TO
637 }
638 break;
639
640 case 'Float':
641 if (!CRM_Utils_Rule::numeric($default)) {
5ab78070 642 $errors['default_value'] = ts('Please enter a valid number.');
6a488035
TO
643 }
644 break;
645
646 case 'Money':
647 if (!CRM_Utils_Rule::money($default)) {
5ab78070 648 $errors['default_value'] = ts('Please enter a valid number.');
6a488035
TO
649 }
650 break;
651
652 case 'Link':
653 if (!CRM_Utils_Rule::url($default)) {
654 $errors['default_value'] = ts('Please enter a valid link.');
655 }
656 break;
657
658 case 'Date':
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.');
661 }
662 break;
663
664 case 'Boolean':
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.');
667 }
668 break;
669
670 case 'Country':
671 if (!empty($default)) {
672 $query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
be2fb01f 673 $params = [1 => [$fields['default_value'], 'String']];
6a488035
TO
674 if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
675 $errors['default_value'] = ts('Invalid default value for country.');
676 }
677 }
678 break;
679
680 case 'StateProvince':
681 if (!empty($default)) {
682 $query = "
8ef12e64 683SELECT count(*)
6a488035
TO
684 FROM civicrm_state_province
685 WHERE name = %1
686 OR abbreviation = %1";
be2fb01f 687 $params = [1 => [$fields['default_value'], 'String']];
6a488035
TO
688 if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
689 $errors['default_value'] = ts('The invalid default value for State/Province data type');
690 }
691 }
692 break;
693
694 case 'ContactReference':
8cc574cf 695 if ($fields['filter_selected'] == 'Advance' && !empty($fields['filter'])) {
6a488035
TO
696 if (strpos($fields['filter'], 'entity=') !== FALSE) {
697 $errors['filter'] = ts("Please do not include entity parameter (entity is always 'contact')");
698 }
06508628
CW
699 elseif (strpos($fields['filter'], 'action=get') === FALSE) {
700 $errors['filter'] = ts("Only 'get' action is supported.");
6a488035
TO
701 }
702 }
be2fb01f 703 $self->setDefaults(['filter_selected', $fields['filter_selected']]);
6a488035
TO
704 break;
705 }
706 }
707
708 if (self::$_dataTypeKeys[$fields['data_type'][0]] == 'Date') {
709 if (!$fields['date_format']) {
710 $errors['date_format'] = ts('Please select a date format.');
711 }
712 }
713
714 /** Check the option values entered
715 * Appropriate values are required for the selected datatype
716 * Incomplete row checking is also required.
717 */
718 $_flagOption = $_rowError = 0;
353ffa53
TO
719 $_showHide = new CRM_Core_ShowHideBlocks('', '');
720 $dataType = self::$_dataTypeKeys[$fields['data_type'][0]];
6a488035
TO
721 if (isset($fields['data_type'][1])) {
722 $dataField = $fields['data_type'][1];
723 }
3221e413 724 $optionFields = ['Select', 'CheckBox', 'Radio'];
6a488035 725
36d1ff7f 726 if (isset($fields['option_type']) && $fields['option_type'] == 1) {
6a488035
TO
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']));
731
732 if ($countValue > $uniqueCount) {
733
734 $start = 1;
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] &&
f3631c02 739 strlen($fields['option_value'][$nextIndex])
6a488035
TO
740 ) {
741 $errors['option_value[' . $start . ']'] = ts('Duplicate Option values');
742 $errors['option_value[' . $nextIndex . ']'] = ts('Duplicate Option values');
743 $_flagOption = 1;
744 }
745 $nextIndex++;
746 }
747 $start++;
748 }
749 }
750 }
751
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']));
756
757 if ($countValue > $uniqueCount) {
758 $start = 1;
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])
764 ) {
765 $errors['option_label[' . $start . ']'] = ts('Duplicate Option label');
766 $errors['option_label[' . $nextIndex . ']'] = ts('Duplicate Option label');
767 $_flagOption = 1;
768 }
769 $nextIndex++;
770 }
771 $start++;
772 }
773 }
774 }
775
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');
780 $_flagOption = 1;
781 }
782 else {
783 $_emptyRow = 1;
784 }
785 }
786 else {
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');
790 $_flagOption = 1;
791 }
792 }
793 }
794
795 if ($fields['option_value'][$i] && $dataType != 'String') {
796 if ($dataType == 'Int') {
797 if (!CRM_Utils_Rule::integer($fields['option_value'][$i])) {
798 $_flagOption = 1;
799 $errors['option_value[' . $i . ']'] = ts('Please enter a valid integer.');
800 }
801 }
802 elseif ($dataType == 'Money') {
803 if (!CRM_Utils_Rule::money($fields['option_value'][$i])) {
804 $_flagOption = 1;
805 $errors['option_value[' . $i . ']'] = ts('Please enter a valid money value.');
806 }
807 }
808 else {
809 if (!CRM_Utils_Rule::numeric($fields['option_value'][$i])) {
810 $_flagOption = 1;
811 $errors['option_value[' . $i . ']'] = ts('Please enter a valid number.');
812 }
813 }
814 }
815
816 $showBlocks = 'optionField_' . $i;
817 if ($_flagOption) {
818 $_showHide->addShow($showBlocks);
819 $_rowError = 1;
820 }
821
822 if (!empty($_emptyRow)) {
823 $_showHide->addHide($showBlocks);
824 }
825 else {
826 $_showHide->addShow($showBlocks);
827 }
828 if ($i == self::NUM_OPTION) {
829 $hideBlock = 'additionalOption';
830 $_showHide->addHide($hideBlock);
831 }
832
833 $_flagOption = $_emptyRow = 0;
834 }
835 }
836 elseif (isset($dataField) &&
837 in_array($dataField, $optionFields) &&
be2fb01f 838 !in_array($dataType, ['Boolean', 'Country', 'StateProvince'])
6a488035
TO
839 ) {
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.');
842 }
843 else {
844 $query = "
845SELECT count(*)
846FROM civicrm_custom_field
847WHERE data_type != %1
848AND option_group_id = %2";
be2fb01f
CW
849 $params = [
850 1 => [
353ffa53 851 self::$_dataTypeKeys[$fields['data_type'][0]],
6a488035 852 'String',
be2fb01f
CW
853 ],
854 2 => [$fields['option_group_id'], 'Integer'],
855 ];
6a488035
TO
856 $count = CRM_Core_DAO::singleValueQuery($query, $params);
857 if ($count > 0) {
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.');
859 }
860 }
861 }
862
863 $assignError = new CRM_Core_Page();
864 if ($_rowError) {
865 $_showHide->addToTemplate();
866 $assignError->assign('optionRowError', $_rowError);
867 }
868 else {
869 if (isset($fields['data_type'][1])) {
870 switch (self::$_dataToHTML[$fields['data_type'][0]][$fields['data_type'][1]]) {
871 case 'Radio':
872 $_fieldError = 1;
873 $assignError->assign('fieldError', $_fieldError);
874 break;
875
876 case 'Checkbox':
877 $_fieldError = 1;
878 $assignError->assign('fieldError', $_fieldError);
879 break;
880
881 case 'Select':
882 $_fieldError = 1;
883 $assignError->assign('fieldError', $_fieldError);
884 break;
885
886 default:
887 $_fieldError = 0;
888 $assignError->assign('fieldError', $_fieldError);
889 }
890 }
891
892 for ($idx = 1; $idx <= self::NUM_OPTION; $idx++) {
893 $showBlocks = 'optionField_' . $idx;
894 if (!empty($fields['option_label'][$idx])) {
895 $_showHide->addShow($showBlocks);
896 }
897 else {
898 $_showHide->addHide($showBlocks);
899 }
900 }
901 $_showHide->addToTemplate();
902 }
903
904 // we can not set require and view at the same time.
8cc574cf 905 if (!empty($fields['is_required']) && !empty($fields['is_view'])) {
6a488035
TO
906 $errors['is_view'] = ts('Can not set this field Required and View Only at the same time.');
907 }
908
909 return empty($errors) ? TRUE : $errors;
910 }
911
912 /**
fe482240 913 * Process the form.
6a488035 914 *
6a488035 915 * @return void
6a488035
TO
916 */
917 public function postProcess() {
918 // store the submitted values in an array
919 $params = $this->controller->exportValues($this->_name);
f3631c02 920 self::clearEmptyOptions($params);
6a488035 921 if ($this->_action == CRM_Core_Action::UPDATE) {
353ffa53 922 $dataTypeKey = $this->_defaultDataType[0];
6a488035
TO
923 $params['data_type'] = self::$_dataTypeKeys[$this->_defaultDataType[0]];
924 $params['html_type'] = self::$_dataToHTML[$this->_defaultDataType[0]][$this->_defaultDataType[1]];
925 }
926 else {
353ffa53 927 $dataTypeKey = $params['data_type'][0];
6a488035
TO
928 $params['html_type'] = self::$_dataToHTML[$params['data_type'][0]][$params['data_type'][1]];
929 $params['data_type'] = self::$_dataTypeKeys[$params['data_type'][0]];
930 }
931
932 //fix for 'is_search_range' field.
be2fb01f 933 if (in_array($dataTypeKey, [
353ffa53
TO
934 1,
935 2,
936 3,
7c550ca0 937 5,
be2fb01f 938 ])) {
a7488080 939 if (empty($params['is_searchable'])) {
6a488035
TO
940 $params['is_search_range'] = 0;
941 }
942 }
943 else {
944 $params['is_search_range'] = 0;
945 }
946
fdd11b39
CW
947 // Serialization cannot be changed on update
948 if ($this->_id) {
949 unset($params['serialize']);
950 }
951 elseif (strpos($params['html_type'], 'Select') === 0) {
952 $params['serialize'] = $params['serialize'] ? CRM_Core_DAO::SERIALIZE_SEPARATOR_BOOKEND : 'null';
953 }
954 else {
955 $params['serialize'] = $params['html_type'] == 'CheckBox' ? CRM_Core_DAO::SERIALIZE_SEPARATOR_BOOKEND : 'null';
956 }
957
6a488035 958 $filter = 'null';
8cc574cf 959 if ($dataTypeKey == 11 && !empty($params['filter_selected'])) {
6a488035
TO
960 if ($params['filter_selected'] == 'Advance' && trim(CRM_Utils_Array::value('filter', $params))) {
961 $filter = trim($params['filter']);
962 }
8cc574cf 963 elseif ($params['filter_selected'] == 'Group' && !empty($params['group_id'])) {
6a488035
TO
964
965 $filter = 'action=lookup&group=' . implode(',', $params['group_id']);
966 }
967 }
968 $params['filter'] = $filter;
969
970 // fix for CRM-316
971 $oldWeight = NULL;
972 if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
be2fb01f 973 $fieldValues = ['custom_group_id' => $this->_gid];
6a488035
TO
974 if ($this->_id) {
975 $oldWeight = $this->_values['weight'];
976 }
977 $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_CustomField', $oldWeight, $params['weight'], $fieldValues);
978 }
979
980 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
981
982 //store the primary key for State/Province or Country as default value.
983 if (strlen(trim($params['default_value']))) {
984 switch ($params['data_type']) {
985 case 'StateProvince':
986 $fieldStateProvince = $strtolower($params['default_value']);
b27d1855 987
988 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
6a488035
TO
989 $query = "
990SELECT id
8ef12e64 991 FROM civicrm_state_province
992 WHERE LOWER(name) = '$fieldStateProvince'
6a488035 993 OR abbreviation = '$fieldStateProvince'";
33621c4f 994 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
995 if ($dao->fetch()) {
996 $params['default_value'] = $dao->id;
997 }
998 break;
999
1000 case 'Country':
1001 $fieldCountry = $strtolower($params['default_value']);
b27d1855 1002
1003 // LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
6a488035
TO
1004 $query = "
1005SELECT id
1006 FROM civicrm_country
8ef12e64 1007 WHERE LOWER(name) = '$fieldCountry'
6a488035 1008 OR iso_code = '$fieldCountry'";
33621c4f 1009 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
1010 if ($dao->fetch()) {
1011 $params['default_value'] = $dao->id;
1012 }
1013 break;
1014 }
1015 }
1016
2f940a36
NG
1017 // The text_length attribute for Memo fields is in a different input as there
1018 // are different label, help text and default value than for other type fields
1019 if ($params['data_type'] == "Memo") {
1020 $params['text_length'] = $params['note_length'];
1021 }
1022
6a488035
TO
1023 // need the FKEY - custom group id
1024 $params['custom_group_id'] = $this->_gid;
1025
1026 if ($this->_action & CRM_Core_Action::UPDATE) {
1027 $params['id'] = $this->_id;
1028 }
6a488035 1029 $customField = CRM_Core_BAO_CustomField::create($params);
f84151fd 1030 $this->_id = $customField->id;
6a488035
TO
1031
1032 // reset the cache
9cdf85c1 1033 Civi::cache('fields')->flush();
6a488035 1034
be2fb01f 1035 $msg = '<p>' . ts("Custom field '%1' has been saved.", [1 => $customField->label]) . '</p>';
6a488035
TO
1036
1037 $buttonName = $this->controller->getButtonName();
1038 $session = CRM_Core_Session::singleton();
1039 if ($buttonName == $this->getButtonName('next', 'new')) {
40084681 1040 $msg .= '<p>' . ts("Ready to add another.") . '</p>';
6a488035 1041 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field/add',
353ffa53
TO
1042 'reset=1&action=add&gid=' . $this->_gid
1043 ));
6a488035
TO
1044 }
1045 else {
1046 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field',
353ffa53
TO
1047 'reset=1&action=browse&gid=' . $this->_gid
1048 ));
6a488035 1049 }
0b1bae4a
CW
1050 $session->setStatus($msg, ts('Saved'), 'success');
1051
1052 // Add data when in ajax contect
1053 $this->ajaxResponse['customField'] = $customField->toArray();
6a488035 1054 }
96025800 1055
f3631c02
CW
1056 /**
1057 * Removes value from fields with no label.
1058 *
1059 * This allows default values to be set in the form, but ignored in post-processing.
1060 *
1061 * @param array $fields
1062 */
1063 public static function clearEmptyOptions(&$fields) {
1064 foreach ($fields['option_label'] as $i => $label) {
1065 if (!strlen(trim($label))) {
1066 $fields['option_value'][$i] = '';
1067 }
1068 }
1069 }
1070
6a488035 1071}