Merge pull request #18168 from twocs/patch-4
[civicrm-core.git] / CRM / Custom / Form / Option.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 */
17
18 /**
19 * form to process actions on the field aspect of Custom
20 */
21 class CRM_Custom_Form_Option extends CRM_Core_Form {
22
23 /**
24 * The custom field id saved to the session for an update
25 *
26 * @var int
27 */
28 protected $_fid;
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 option group ID
39 * @var int
40 */
41 protected $_optionGroupID = NULL;
42
43 /**
44 * The Option id, used when editing the Option
45 *
46 * @var int
47 */
48 protected $_id;
49
50 /**
51 * Set variables up before form is built.
52 *
53 * @return void
54 */
55 public function preProcess() {
56 $this->_fid = CRM_Utils_Request::retrieve('fid', 'Positive', $this);
57
58 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this);
59
60 if (!isset($this->_gid) && $this->_fid) {
61 $this->_gid = CRM_Core_DAO::getFieldValue(
62 'CRM_Core_DAO_CustomField',
63 $this->_fid,
64 'custom_group_id'
65 );
66 }
67
68 if ($this->_fid) {
69 $this->_optionGroupID = CRM_Core_DAO::getFieldValue(
70 'CRM_Core_DAO_CustomField',
71 $this->_fid,
72 'option_group_id'
73 );
74 }
75
76 if ($isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_reserved', 'id')) {
77 CRM_Core_Error::statusBounce("You cannot add or edit muliple choice options in a reserved custom field-set.");
78 }
79
80 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
81 }
82
83 /**
84 * Set default values for the form. Note that in edit/view mode
85 * the default values are retrieved from the database
86 *
87 * @return array
88 * array of default values
89 */
90 public function setDefaultValues() {
91 $defaults = $fieldDefaults = [];
92 if (isset($this->_id)) {
93 $params = ['id' => $this->_id];
94 CRM_Core_BAO_CustomOption::retrieve($params, $defaults);
95
96 $paramsField = ['id' => $this->_fid];
97 CRM_Core_BAO_CustomField::retrieve($paramsField, $fieldDefaults);
98
99 if ($fieldDefaults['html_type'] == 'CheckBox'
100 || $fieldDefaults['html_type'] == 'Multi-Select'
101 ) {
102 if (!empty($fieldDefaults['default_value'])) {
103 $defaultCheckValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
104 substr($fieldDefaults['default_value'], 1, -1)
105 );
106 if (in_array($defaults['value'], $defaultCheckValues)) {
107 $defaults['default_value'] = 1;
108 }
109 }
110 }
111 else {
112 if (CRM_Utils_Array::value('default_value', $fieldDefaults) == CRM_Utils_Array::value('value', $defaults)) {
113 $defaults['default_value'] = 1;
114 }
115 }
116 }
117 else {
118 $defaults['is_active'] = 1;
119 }
120
121 if ($this->_action & CRM_Core_Action::ADD) {
122 $fieldValues = ['option_group_id' => $this->_optionGroupID];
123 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
124 }
125
126 return $defaults;
127 }
128
129 /**
130 * Build the form object.
131 *
132 * @return void
133 */
134 public function buildQuickForm() {
135 if ($this->_action == CRM_Core_Action::DELETE) {
136 $option = civicrm_api3('option_value', 'getsingle', ['id' => $this->_id]);
137 $this->assign('label', $option['label']);
138 $this->addButtons([
139 [
140 'type' => 'next',
141 'name' => ts('Delete'),
142 'isDefault' => TRUE,
143 ],
144 [
145 'type' => 'cancel',
146 'name' => ts('Cancel'),
147 ],
148 ]);
149 }
150 else {
151 // lets trim all the whitespace
152 $this->applyFilter('__ALL__', 'trim');
153
154 // hidden Option Id for validation use
155 $this->add('hidden', 'optionId', $this->_id);
156
157 //hidden field ID for validation use
158 $this->add('hidden', 'fieldId', $this->_fid);
159
160 // label
161 $this->add('text', 'label', ts('Option Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'), TRUE);
162
163 $this->add('text', 'value', ts('Option Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'), TRUE);
164
165 $this->add('textarea', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'description'));
166 // weight
167 $this->add('number', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'weight'), TRUE);
168 $this->addRule('weight', ts('is a numeric field'), 'numeric');
169
170 // is active ?
171 $this->add('checkbox', 'is_active', ts('Active?'));
172
173 // Set the default value for Custom Field
174 $this->add('checkbox', 'default_value', ts('Default'));
175
176 // add a custom form rule
177 $this->addFormRule(['CRM_Custom_Form_Option', 'formRule'], $this);
178
179 // add buttons
180 $this->addButtons([
181 [
182 'type' => 'next',
183 'name' => ts('Save'),
184 'isDefault' => TRUE,
185 ],
186 [
187 'type' => 'next',
188 'name' => ts('Save and New'),
189 'subName' => 'new',
190 ],
191 [
192 'type' => 'cancel',
193 'name' => ts('Cancel'),
194 ],
195 ]);
196
197 // if view mode pls freeze it with the done button.
198 if ($this->_action & CRM_Core_Action::VIEW) {
199 $this->freeze();
200 $url = CRM_Utils_System::url('civicrm/admin/custom/group/field/option',
201 'reset=1&action=browse&fid=' . $this->_fid . '&gid=' . $this->_gid,
202 TRUE, NULL, FALSE
203 );
204 $this->addElement('button',
205 'done',
206 ts('Done'),
207 ['onclick' => "location.href='$url'", 'class' => 'crm-form-submit cancel', 'crm-icon' => 'fa-times']
208 );
209 }
210 }
211 $this->assign('id', $this->_id);
212 }
213
214 /**
215 * Global validation rules for the form.
216 *
217 * @param array $fields
218 * Posted values of the form.
219 *
220 * @param $files
221 * @param CRM_Core_Form $form
222 *
223 * @return array
224 * list of errors to be posted back to the form
225 */
226 public static function formRule($fields, $files, $form) {
227 $optionLabel = $fields['label'];
228 $optionValue = $fields['value'];
229 $fieldId = $form->_fid;
230 $optionGroupId = $form->_optionGroupID;
231
232 $temp = [];
233 if (empty($form->_id)) {
234 $query = "
235 SELECT count(*)
236 FROM civicrm_option_value
237 WHERE option_group_id = %1
238 AND label = %2";
239 $params = [
240 1 => [$optionGroupId, 'Integer'],
241 2 => [$optionLabel, 'String'],
242 ];
243 if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
244 $errors['label'] = ts('There is an entry with the same label.');
245 }
246
247 $query = "
248 SELECT count(*)
249 FROM civicrm_option_value
250 WHERE option_group_id = %1
251 AND value = %2";
252 $params = [
253 1 => [$optionGroupId, 'Integer'],
254 2 => [$optionValue, 'String'],
255 ];
256 if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
257 $errors['value'] = ts('There is an entry with the same value.');
258 }
259 }
260 else {
261 //capture duplicate entries while updating Custom Options
262 $optionId = CRM_Utils_Type::escape($fields['optionId'], 'Integer');
263
264 //check label duplicates within a custom field
265 $query = "
266 SELECT count(*)
267 FROM civicrm_option_value
268 WHERE option_group_id = %1
269 AND id != %2
270 AND label = %3";
271 $params = [
272 1 => [$optionGroupId, 'Integer'],
273 2 => [$optionId, 'Integer'],
274 3 => [$optionLabel, 'String'],
275 ];
276 if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
277 $errors['label'] = ts('There is an entry with the same label.');
278 }
279
280 //check value duplicates within a custom field
281 $query = "
282 SELECT count(*)
283 FROM civicrm_option_value
284 WHERE option_group_id = %1
285 AND id != %2
286 AND value = %3";
287 $params = [
288 1 => [$optionGroupId, 'Integer'],
289 2 => [$optionId, 'Integer'],
290 3 => [$optionValue, 'String'],
291 ];
292 if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
293 $errors['value'] = ts('There is an entry with the same value.');
294 }
295 }
296
297 $query = "
298 SELECT data_type
299 FROM civicrm_custom_field
300 WHERE id = %1";
301 $params = [1 => [$fieldId, 'Integer']];
302 $dao = CRM_Core_DAO::executeQuery($query, $params);
303 if ($dao->fetch()) {
304 switch ($dao->data_type) {
305 case 'Int':
306 if (!CRM_Utils_Rule::integer($fields["value"])) {
307 $errors['value'] = ts('Please enter a valid integer value.');
308 }
309 break;
310
311 case 'Float':
312 // case 'Money':
313 if (!CRM_Utils_Rule::numeric($fields["value"])) {
314 $errors['value'] = ts('Please enter a valid number.');
315 }
316 break;
317
318 case 'Money':
319 if (!CRM_Utils_Rule::money($fields["value"])) {
320 $errors['value'] = ts('Please enter a valid value.');
321 }
322 break;
323
324 case 'Date':
325 if (!CRM_Utils_Rule::date($fields["value"])) {
326 $errors['value'] = ts('Please enter a valid date using YYYY-MM-DD format. Example: 2004-12-31.');
327 }
328 break;
329
330 case 'Boolean':
331 if (!CRM_Utils_Rule::integer($fields["value"]) &&
332 ($fields["value"] != '1' || $fields["value"] != '0')
333 ) {
334 $errors['value'] = ts('Please enter 1 or 0 as value.');
335 }
336 break;
337
338 case 'Country':
339 if (!empty($fields["value"])) {
340 $params = [1 => [$fields['value'], 'String']];
341 $query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
342 if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
343 $errors['value'] = ts('Invalid default value for country.');
344 }
345 }
346 break;
347
348 case 'StateProvince':
349 if (!empty($fields["value"])) {
350 $params = [1 => [$fields['value'], 'String']];
351 $query = "
352 SELECT count(*)
353 FROM civicrm_state_province
354 WHERE name = %1
355 OR abbreviation = %1";
356 if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
357 $errors['value'] = ts('The invalid value for State/Province data type');
358 }
359 }
360 break;
361 }
362 }
363
364 return empty($errors) ? TRUE : $errors;
365 }
366
367 /**
368 * Process the form.
369 *
370 * @return void
371 */
372 public function postProcess() {
373 // store the submitted values in an array
374 $params = $this->controller->exportValues('Option');
375
376 if ($this->_action == CRM_Core_Action::DELETE) {
377 $option = civicrm_api3('option_value', 'getsingle', ['id' => $this->_id]);
378 $fieldValues = ['option_group_id' => $this->_optionGroupID];
379 CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
380 CRM_Core_BAO_CustomOption::del($this->_id);
381 CRM_Core_Session::setStatus(ts('Option "%1" has been deleted.', [1 => $option['label']]), ts('Deleted'), 'success');
382 return;
383 }
384
385 // set values for custom field properties and save
386 $customOption = new CRM_Core_DAO_OptionValue();
387 $customOption->label = $params['label'];
388 $customOption->weight = $params['weight'];
389 $customOption->description = $params['description'];
390 $customOption->value = $params['value'];
391 $customOption->is_active = $params['is_active'] ?? FALSE;
392
393 $oldWeight = NULL;
394 if ($this->_id) {
395 $customOption->id = $this->_id;
396 CRM_Core_BAO_CustomOption::updateCustomValues($params);
397 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'weight', 'id');
398 }
399 else {
400 $customOption->name = CRM_Utils_String::titleToVar($params['label']);
401 }
402
403 $fieldValues = ['option_group_id' => $this->_optionGroupID];
404 $customOption->weight
405 = CRM_Utils_Weight::updateOtherWeights(
406 'CRM_Core_DAO_OptionValue',
407 $oldWeight,
408 $params['weight'],
409 $fieldValues);
410
411 $customOption->option_group_id = $this->_optionGroupID;
412
413 $customField = new CRM_Core_DAO_CustomField();
414 $customField->id = $this->_fid;
415 if (
416 $customField->find(TRUE) &&
417 (
418 $customField->html_type == 'CheckBox' ||
419 $customField->html_type == 'Multi-Select'
420 )
421 ) {
422 $defVal = explode(
423 CRM_Core_DAO::VALUE_SEPARATOR,
424 substr($customField->default_value, 1, -1)
425 );
426 if (!empty($params['default_value'])) {
427 if (!in_array($customOption->value, $defVal)) {
428 if (empty($defVal[0])) {
429 $defVal = [$customOption->value];
430 }
431 else {
432 $defVal[] = $customOption->value;
433 }
434 $customField->default_value
435 = CRM_Core_DAO::VALUE_SEPARATOR .
436 implode(CRM_Core_DAO::VALUE_SEPARATOR, $defVal) .
437 CRM_Core_DAO::VALUE_SEPARATOR;
438 $customField->save();
439 }
440 }
441 elseif (in_array($customOption->value, $defVal)) {
442 $tempVal = [];
443 foreach ($defVal as $v) {
444 if ($v != $customOption->value) {
445 $tempVal[] = $v;
446 }
447 }
448
449 $customField->default_value
450 = CRM_Core_DAO::VALUE_SEPARATOR .
451 implode(CRM_Core_DAO::VALUE_SEPARATOR, $tempVal) .
452 CRM_Core_DAO::VALUE_SEPARATOR;
453 $customField->save();
454 }
455 }
456 else {
457 switch ($customField->data_type) {
458 case 'Money':
459 $customOption->value = CRM_Utils_Rule::cleanMoney($customOption->value);
460 break;
461
462 case 'Int':
463 $customOption->value = intval($customOption->value);
464 break;
465
466 case 'Float':
467 $customOption->value = floatval($customOption->value);
468 break;
469 }
470
471 if (!empty($params['default_value'])) {
472 $customField->default_value = $customOption->value;
473 $customField->save();
474 }
475 elseif ($customField->find(TRUE) && $customField->default_value == $customOption->value) {
476 // this is the case where this option is the current default value and we have been reset
477 $customField->default_value = 'null';
478 $customField->save();
479 }
480 }
481
482 $customOption->save();
483
484 $msg = ts('Your multiple choice option \'%1\' has been saved', [1 => $customOption->label]);
485 CRM_Core_Session::setStatus($msg, '', 'success');
486 $buttonName = $this->controller->getButtonName();
487 $session = CRM_Core_Session::singleton();
488 if ($buttonName == $this->getButtonName('next', 'new')) {
489 CRM_Core_Session::setStatus(ts('You can add another option.'), '', 'info');
490 $session->replaceUserContext(
491 CRM_Utils_System::url(
492 'civicrm/admin/custom/group/field/option',
493 'reset=1&action=add&fid=' . $this->_fid . '&gid=' . $this->_gid
494 )
495 );
496 }
497 }
498
499 }