Merge pull request #17580 from samuelsov/dev/core#1670
[civicrm-core.git] / CRM / Price / 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 Price
20 */
21class CRM_Price_Form_Field extends CRM_Core_Form {
22
44374cbe 23 use CRM_Core_Form_EntityFormTrait;
24
25 /**
26 * Explicitly declare the entity api name.
27 */
28 public function getDefaultEntity() {
29 return 'PriceField';
30 }
31
32 /**
33 * Explicitly declare the form context.
34 */
35 public function getDefaultContext() {
36 return 'create';
37 }
38
39 /**
40 * Get the entity id being edited.
41 *
42 * @return int|null
43 */
44 public function getEntityId() {
45 return $this->_fid;
46 }
47
6a488035
TO
48 /**
49 * Constants for number of options for data types of multiple option.
50 */
7da04cde 51 const NUM_OPTION = 15;
6a488035
TO
52
53 /**
fe482240 54 * The custom set id saved to the session for an update.
6a488035
TO
55 *
56 * @var int
6a488035
TO
57 */
58 protected $_sid;
59
60 /**
61 * The field id, used when editing the field
62 *
63 * @var int
6a488035
TO
64 */
65 protected $_fid;
66
67 /**
fe482240 68 * The extended component Id.
6a488035
TO
69 *
70 * @var array
6a488035
TO
71 */
72 protected $_extendComponentId;
73
74 /**
fe482240 75 * Variable is set if price set is used for membership.
971e129b 76 * @var bool
6a488035
TO
77 */
78 protected $_useForMember;
79
80 /**
fe482240 81 * Set variables up before form is built.
6a488035
TO
82 */
83 public function preProcess() {
84
44374cbe 85 $this->_sid = CRM_Utils_Request::retrieve('sid', 'Positive', $this);
86 $this->_fid = CRM_Utils_Request::retrieve('fid', 'Positive', $this);
353ffa53 87 $url = CRM_Utils_System::url('civicrm/admin/price/field', "reset=1&action=browse&sid={$this->_sid}");
be2fb01f 88 $breadCrumb = [['title' => ts('Price Set Fields'), 'url' => $url]];
6a488035 89
be2fb01f 90 $this->_extendComponentId = [];
9da8dc8c 91 $extendComponentId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'extends', 'id');
6a488035
TO
92 if ($extendComponentId) {
93 $this->_extendComponentId = explode(CRM_Core_DAO::VALUE_SEPARATOR, $extendComponentId);
94 }
95
96 CRM_Utils_System::appendBreadCrumb($breadCrumb);
704f21c0 97
e2046b33 98 $this->setPageTitle(ts('Price Field'));
6a488035
TO
99 }
100
101 /**
bf15c191 102 * Set default values for the form.
6a488035 103 *
a6c01b45
CW
104 * @return array
105 * array of default values
44374cbe 106 * @throws \CRM_Core_Exception
6a488035 107 */
00be9182 108 public function setDefaultValues() {
be2fb01f 109 $defaults = [];
6a488035 110 // is it an edit operation ?
44374cbe 111 if ($this->getEntityId()) {
112 $params = ['id' => $this->getEntityId()];
113 $this->assign('fid', $this->getEntityId());
9da8dc8c 114 CRM_Price_BAO_PriceField::retrieve($params, $defaults);
6a488035
TO
115 $this->_sid = $defaults['price_set_id'];
116
117 // if text, retrieve price
118 if ($defaults['html_type'] == 'Text') {
fc8edfbf 119 $isActive = $defaults['is_active'];
44374cbe 120 $valueParams = ['price_field_id' => $this->getEntityId()];
6a488035 121
9da8dc8c 122 CRM_Price_BAO_PriceFieldValue::retrieve($valueParams, $defaults);
6a488035
TO
123
124 // fix the display of the monetary value, CRM-4038
125 $defaults['price'] = CRM_Utils_Money::format($defaults['amount'], NULL, '%a');
ff33ddc8 126 $defaults['is_active'] = $isActive;
6a488035
TO
127 }
128
6a488035
TO
129 }
130 else {
131 $defaults['is_active'] = 1;
132 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
133 $defaults['option_status[' . $i . ']'] = 1;
134 $defaults['option_weight[' . $i . ']'] = $i;
2db35bf6 135 $defaults['option_visibility_id[' . $i . ']'] = 1;
6a488035
TO
136 }
137 }
138
139 if ($this->_action & CRM_Core_Action::ADD) {
be2fb01f 140 $fieldValues = ['price_set_id' => $this->_sid];
9da8dc8c 141 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Price_DAO_PriceField', $fieldValues);
6a488035
TO
142 $defaults['options_per_line'] = 1;
143 $defaults['is_display_amounts'] = 1;
144 }
0495a6a4 145 $enabledComponents = CRM_Core_Component::getEnabledComponents();
146 $eventComponentId = NULL;
ba1dcfda 147 if (array_key_exists('CiviEvent', $enabledComponents)) {
353ffa53 148 $eventComponentId = CRM_Core_Component::getComponentID('CiviEvent');
0495a6a4 149 }
6a488035
TO
150
151 if (isset($this->_sid) && $this->_action == CRM_Core_Action::ADD) {
9da8dc8c 152 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'financial_type_id');
6a488035
TO
153 $defaults['financial_type_id'] = $financialTypeId;
154 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
155 $defaults['option_financial_type_id[' . $i . ']'] = $financialTypeId;
156 }
157 }
158 return $defaults;
159 }
160
161 /**
fe482240 162 * Build the form object.
6a488035
TO
163 */
164 public function buildQuickForm() {
165 // lets trim all the whitespace
166 $this->applyFilter('__ALL__', 'trim');
167
168 // add a hidden field to remember the price set id
169 // this get around the browser tab issue
170 $this->add('hidden', 'sid', $this->_sid);
44374cbe 171 $this->add('hidden', 'fid', $this->getEntityId());
6a488035
TO
172
173 // label
9da8dc8c 174 $this->add('text', 'label', ts('Field Label'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'label'), TRUE);
6a488035
TO
175
176 // html_type
177 $javascript = 'onchange="option_html_type(this.form)";';
178
9da8dc8c 179 $htmlTypes = CRM_Price_BAO_PriceField::htmlTypes();
6a488035
TO
180
181 // Text box for Participant Count for a field
182
183 // Financial Type
184 $financialType = CRM_Financial_BAO_FinancialType::getIncomeFinancialType();
53df1142 185 foreach ($financialType as $finTypeId => $type) {
40c655aa 186 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
66af7c48
PN
187 && !CRM_Core_Permission::check('add contributions of type ' . $type)
188 ) {
53df1142
E
189 unset($financialType[$finTypeId]);
190 }
191 }
6a488035
TO
192 if (count($financialType)) {
193 $this->assign('financialType', $financialType);
194 }
2db35bf6
AF
195
196 //Visibility Type Options
197 $visibilityType = CRM_Core_PseudoConstant::visibility();
198 $this->assign('visibilityType', $visibilityType);
199
0495a6a4 200 $enabledComponents = CRM_Core_Component::getEnabledComponents();
201 $eventComponentId = $memberComponentId = NULL;
ba1dcfda 202 if (array_key_exists('CiviEvent', $enabledComponents)) {
353ffa53 203 $eventComponentId = CRM_Core_Component::getComponentID('CiviEvent');
0495a6a4 204 }
ba1dcfda 205 if (array_key_exists('CiviMember', $enabledComponents)) {
0495a6a4 206 $memberComponentId = CRM_Core_Component::getComponentID('CiviMember');
207 }
366fe2a3 208
353ffa53 209 $attributes = CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceFieldValue');
366fe2a3 210
211 $this->add('select', 'financial_type_id',
212 ts('Financial Type'),
be2fb01f 213 [' ' => ts('- select -')] + $financialType
6a488035
TO
214 );
215
216 $this->assign('useForMember', FALSE);
217 if (in_array($eventComponentId, $this->_extendComponentId)) {
218 $this->add('text', 'count', ts('Participant Count'), $attributes['count']);
219
220 $this->addRule('count', ts('Participant Count should be a positive number'), 'positiveInteger');
221
222 $this->add('text', 'max_value', ts('Max Participants'), $attributes['max_value']);
223 $this->addRule('max_value', ts('Please enter a valid Max Participants.'), 'positiveInteger');
224
225 $this->assign('useForEvent', TRUE);
226 }
227 else {
228 if (in_array($memberComponentId, $this->_extendComponentId)) {
229 $this->_useForMember = 1;
230 $this->assign('useForMember', $this->_useForMember);
231 }
232 $this->assign('useForEvent', FALSE);
233 }
234
235 $sel = $this->add('select', 'html_type', ts('Input Field Type'),
236 $htmlTypes, TRUE, $javascript
237 );
238
239 // price (for text inputs)
240 $this->add('text', 'price', ts('Price'));
241 $this->registerRule('price', 'callback', 'money', 'CRM_Utils_Rule');
242 $this->addRule('price', ts('must be a monetary value'), 'money');
243
5afce5ad 244 $this->add('text', 'non_deductible_amount', ts('Non-deductible Amount'), NULL);
245 $this->registerRule('non_deductible_amount', 'callback', 'money', 'CRM_Utils_Rule');
246 $this->addRule('non_deductible_amount', ts('Please enter a monetary value for this field.'), 'money');
247
6a488035
TO
248 if ($this->_action == CRM_Core_Action::UPDATE) {
249 $this->freeze('html_type');
250 }
251
252 // form fields of Custom Option rows
253 $_showHide = new CRM_Core_ShowHideBlocks('', '');
254
255 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
256
257 //the show hide blocks
258 $showBlocks = 'optionField_' . $i;
259 if ($i > 2) {
260 $_showHide->addHide($showBlocks);
261 if ($i == self::NUM_OPTION) {
262 $_showHide->addHide('additionalOption');
263 }
264 }
265 else {
266 $_showHide->addShow($showBlocks);
267 }
268 // label
269 $attributes['label']['size'] = 25;
270 $this->add('text', 'option_label[' . $i . ']', ts('Label'), $attributes['label']);
271
272 // amount
273 $this->add('text', 'option_amount[' . $i . ']', ts('Amount'), $attributes['amount']);
274 $this->addRule('option_amount[' . $i . ']', ts('Please enter a valid amount for this field.'), 'money');
275
276 //Financial Type
277 $this->add(
366fe2a3 278 'select',
92fcb95f 279 'option_financial_type_id[' . $i . ']',
366fe2a3 280 ts('Financial Type'),
be2fb01f 281 ['' => ts('- select -')] + $financialType
6a488035
TO
282 );
283 if (in_array($eventComponentId, $this->_extendComponentId)) {
284 // count
285 $this->add('text', 'option_count[' . $i . ']', ts('Participant Count'), $attributes['count']);
286 $this->addRule('option_count[' . $i . ']', ts('Please enter a valid Participants Count.'), 'positiveInteger');
287
288 // max_value
289 $this->add('text', 'option_max_value[' . $i . ']', ts('Max Participants'), $attributes['max_value']);
290 $this->addRule('option_max_value[' . $i . ']', ts('Please enter a valid Max Participants.'), 'positiveInteger');
291
292 // description
293 //$this->add('textArea', 'option_description['.$i.']', ts('Description'), array('rows' => 1, 'cols' => 40 ));
294 }
295 elseif (in_array($memberComponentId, $this->_extendComponentId)) {
296 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
be2fb01f 297 $js = ['onchange' => "calculateRowValues( $i );"];
6a488035
TO
298
299 $this->add('select', 'membership_type_id[' . $i . ']', ts('Membership Type'),
be2fb01f 300 ['' => ' '] + $membershipTypes, FALSE, $js
353ffa53 301 );
896bd22c 302 $this->add('text', 'membership_num_terms[' . $i . ']', ts('Number of Terms'), CRM_Utils_Array::value('membership_num_terms', $attributes));
6a488035
TO
303 }
304
305 // weight
f20d2b0d 306 $this->add('number', 'option_weight[' . $i . ']', ts('Order'), $attributes['weight']);
6a488035
TO
307
308 // is active ?
309 $this->add('checkbox', 'option_status[' . $i . ']', ts('Active?'));
310
2bc7601f 311 $this->add('select', 'option_visibility_id[' . $i . ']', ts('Visibility'), $visibilityType);
6a488035
TO
312 $defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i);
313
314 //for checkbox handling of default option
315 $this->add('checkbox', "default_checkbox_option[$i]", NULL);
316 }
317 //default option selection
318 $this->addGroup($defaultOption, 'default_option');
319 $_showHide->addToTemplate();
320
321 // is_display_amounts
322 $this->add('checkbox', 'is_display_amounts', ts('Display Amount?'));
323
324 // weight
f20d2b0d 325 $this->add('number', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'weight'), TRUE);
6a488035
TO
326 $this->addRule('weight', ts('is a numeric field'), 'numeric');
327
328 // checkbox / radio options per line
329 $this->add('text', 'options_per_line', ts('Options Per Line'));
330 $this->addRule('options_per_line', ts('must be a numeric value'), 'numeric');
331
139f5f76
JP
332 $this->add('textarea', 'help_pre', ts('Pre Field Help'),
333 CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'help_post')
334 );
335
6a488035 336 // help post, mask, attributes, javascript ?
139f5f76 337 $this->add('textarea', 'help_post', ts('Post Field Help'),
9da8dc8c 338 CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'help_post')
6a488035
TO
339 );
340
be2fb01f 341 $this->add('datepicker', 'active_on', ts('Active On'), [], FALSE, ['time' => TRUE]);
6a488035
TO
342
343 // expire_on
be2fb01f 344 $this->add('datepicker', 'expire_on', ts('Expire On'), [], FALSE, ['time' => TRUE]);
6a488035
TO
345
346 // is required ?
347 $this->add('checkbox', 'is_required', ts('Required?'));
348
349 // is active ?
350 $this->add('checkbox', 'is_active', ts('Active?'));
351
352 // add buttons
be2fb01f
CW
353 $this->addButtons([
354 [
c5c263ca
AH
355 'type' => 'next',
356 'name' => ts('Save'),
357 'isDefault' => TRUE,
be2fb01f
CW
358 ],
359 [
c5c263ca
AH
360 'type' => 'next',
361 'name' => ts('Save and New'),
362 'subName' => 'new',
be2fb01f
CW
363 ],
364 [
c5c263ca
AH
365 'type' => 'cancel',
366 'name' => ts('Cancel'),
be2fb01f
CW
367 ],
368 ]);
6a488035
TO
369 // is public?
370 $this->add('select', 'visibility_id', ts('Visibility'), CRM_Core_PseudoConstant::visibility());
371
372 // add a form rule to check default value
be2fb01f 373 $this->addFormRule(['CRM_Price_Form_Field', 'formRule'], $this);
6a488035
TO
374
375 // if view mode pls freeze it with the done button.
376 if ($this->_action & CRM_Core_Action::VIEW) {
377 $this->freeze();
378 $url = CRM_Utils_System::url('civicrm/admin/price/field', 'reset=1&action=browse&sid=' . $this->_sid);
379 $this->addElement('button',
380 'done',
381 ts('Done'),
be2fb01f 382 ['onclick' => "location.href='$url'"]
6a488035
TO
383 );
384 }
385 }
386
387 /**
fe482240 388 * Global validation rules for the form.
6a488035 389 *
414c1420
TO
390 * @param array $fields
391 * Posted values of the form.
77b97be7 392 *
44374cbe 393 * @param array $files
394 * @param self $form
6a488035 395 *
a6c01b45
CW
396 * @return array
397 * if errors then list of errors to be posted back to the form,
6a488035 398 * true otherwise
6a488035 399 */
00be9182 400 public static function formRule($fields, $files, $form) {
6a488035
TO
401
402 // all option fields are of type "money"
be2fb01f 403 $errors = [];
6a488035
TO
404
405 /** Check the option values entered
406 * Appropriate values are required for the selected datatype
407 * Incomplete row checking is also required.
408 */
409 if (($form->_action & CRM_Core_Action::ADD || $form->_action & CRM_Core_Action::UPDATE) &&
44374cbe 410 $fields['html_type'] === 'Text'
6a488035 411 ) {
e68e1c9a
PN
412 if ($fields['price'] == NULL) {
413 $errors['price'] = ts('Price is a required field');
414 }
415 if ($fields['financial_type_id'] == '') {
416 $errors['financial_type_id'] = ts('Financial Type is a required field');
417 }
6a488035 418 }
366fe2a3 419
6a488035 420 //avoid the same price field label in Within PriceSet
9da8dc8c 421 $priceFieldLabel = new CRM_Price_DAO_PriceField();
6a488035
TO
422 $priceFieldLabel->label = $fields['label'];
423 $priceFieldLabel->price_set_id = $form->_sid;
424
425 $dupeLabel = FALSE;
44374cbe 426 if ($priceFieldLabel->find(TRUE) && $form->getEntityId() != $priceFieldLabel->id) {
6a488035
TO
427 $dupeLabel = TRUE;
428 }
429
430 if ($dupeLabel) {
431 $errors['label'] = ts('Name already exists in Database.');
432 }
433
434 if ((is_numeric(CRM_Utils_Array::value('count', $fields)) &&
de6c59ca 435 empty($fields['count'])
6a488035
TO
436 ) &&
437 (CRM_Utils_Array::value('html_type', $fields) == 'Text')
438 ) {
439 $errors['count'] = ts('Participant Count must be greater than zero.');
440 }
441
442 if ($form->_action & CRM_Core_Action::ADD) {
443 if ($fields['html_type'] != 'Text') {
444 $countemptyrows = 0;
a13c171d 445 $publicOptionCount = $_flagOption = $_rowError = 0;
6a488035
TO
446
447 $_showHide = new CRM_Core_ShowHideBlocks('', '');
39868387 448 $visibilityOptions = CRM_Price_BAO_PriceFieldValue::buildOptions('visibility_id', 'validate');
6a488035
TO
449
450 for ($index = 1; $index <= self::NUM_OPTION; $index++) {
451
452 $noLabel = $noAmount = $noWeight = 1;
453 if (!empty($fields['option_label'][$index])) {
454 $noLabel = 0;
455 $duplicateIndex = CRM_Utils_Array::key($fields['option_label'][$index],
456 $fields['option_label']
457 );
458
459 if ((!($duplicateIndex === FALSE)) &&
460 (!($duplicateIndex == $index))
461 ) {
462 $errors["option_label[{$index}]"] = ts('Duplicate label value');
463 $_flagOption = 1;
464 }
465 }
466 if ($form->_useForMember) {
467 if (!empty($fields['membership_type_id'][$index])) {
468 $memTypesIDS[] = $fields['membership_type_id'][$index];
469 }
470 }
471
472 // allow for 0 value.
473 if (!empty($fields['option_amount'][$index]) ||
474 strlen($fields['option_amount'][$index]) > 0
475 ) {
476 $noAmount = 0;
477 }
478
479 if (!empty($fields['option_weight'][$index])) {
480 $noWeight = 0;
481 $duplicateIndex = CRM_Utils_Array::key($fields['option_weight'][$index],
482 $fields['option_weight']
483 );
484
485 if ((!($duplicateIndex === FALSE)) &&
486 (!($duplicateIndex == $index))
487 ) {
488 $errors["option_weight[{$index}]"] = ts('Duplicate weight value');
489 $_flagOption = 1;
490 }
491 }
8cc574cf 492 if (!$noLabel && !$noAmount && !empty($fields['option_financial_type_id']) && $fields['option_financial_type_id'][$index] == '' && $fields['html_type'] != 'Text') {
6a488035 493 $errors["option_financial_type_id[{$index}]"] = ts('Financial Type is a Required field.');
366fe2a3 494 }
6a488035
TO
495 if ($noLabel && !$noAmount) {
496 $errors["option_label[{$index}]"] = ts('Label cannot be empty.');
497 $_flagOption = 1;
498 }
499
500 if (!$noLabel && $noAmount) {
501 $errors["option_amount[{$index}]"] = ts('Amount cannot be empty.');
502 $_flagOption = 1;
503 }
504
505 if ($noLabel && $noAmount) {
506 $countemptyrows++;
507 $_emptyRow = 1;
508 }
509 elseif (!empty($fields['option_max_value'][$index]) &&
510 !empty($fields['option_count'][$index]) &&
511 ($fields['option_count'][$index] > $fields['option_max_value'][$index])
512 ) {
513 $errors["option_max_value[{$index}]"] = ts('Participant count can not be greater than max participants.');
514 $_flagOption = 1;
515 }
516
517 $showBlocks = 'optionField_' . $index;
518 if ($_flagOption) {
519 $_showHide->addShow($showBlocks);
520 $_rowError = 1;
521 }
522
523 if (!empty($_emptyRow)) {
524 $_showHide->addHide($showBlocks);
525 }
526 else {
527 $_showHide->addShow($showBlocks);
528 }
529 if ($index == self::NUM_OPTION) {
530 $hideBlock = 'additionalOption';
531 $_showHide->addHide($hideBlock);
532 }
533
a13c171d
CR
534 if (!empty($fields['option_visibility_id'][$index]) && (!$noLabel || !$noAmount)) {
535 if ($visibilityOptions[$fields['option_visibility_id'][$index]] == 'public') {
536 $publicOptionCount++;
537 }
538 }
539
6a488035
TO
540 $_flagOption = $_emptyRow = 0;
541 }
542
543 if (!empty($memTypesIDS)) {
544 // check for checkboxes allowing user to select multiple memberships from same membership organization
545 if ($fields['html_type'] == 'CheckBox') {
ba1dcfda 546 $foundDuplicate = FALSE;
be2fb01f 547 $orgIds = [];
ba1dcfda
TO
548 foreach ($memTypesIDS as $key => $val) {
549 $org = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization($val);
550 if (in_array($org[$val], $orgIds)) {
551 $foundDuplicate = TRUE;
552 break;
553 }
554 $orgIds[$val] = $org[$val];
6a488035 555
ba1dcfda
TO
556 }
557 if ($foundDuplicate) {
558 $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity.');
559 }
6a488035 560 }
366fe2a3 561
6a488035
TO
562 // CRM-10390 - Only one price field in a set can include auto-renew membership options
563 $foundAutorenew = FALSE;
564 foreach ($memTypesIDS as $key => $val) {
565 // see if any price field option values in this price field are for memberships with autorenew
566 $memTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($val);
a7488080 567 if (!empty($memTypeDetails['auto_renew'])) {
6a488035
TO
568 $foundAutorenew = TRUE;
569 break;
570 }
571 }
572
573 if ($foundAutorenew) {
574 // if so, check for other fields in this price set which also have auto-renew membership options
9da8dc8c 575 $otherFieldAutorenew = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($form->_sid);
6a488035
TO
576 if ($otherFieldAutorenew) {
577 $errors['_qf_default'] = ts('You can include auto-renew membership choices for only one price field in a price set. Another field in this set already contains one or more auto-renew membership options.');
578 }
579 }
580 }
581 $_showHide->addToTemplate();
582
831e0fa5 583 if ($countemptyrows == 15) {
6a488035
TO
584 $errors['option_label[1]'] = $errors['option_amount[1]'] = ts('Label and value cannot be empty.');
585 $_flagOption = 1;
586 }
a13c171d
CR
587
588 if ($visibilityOptions[$fields['visibility_id']] == 'public' && $publicOptionCount == 0) {
589 $errors['visibility_id'] = ts('You have selected to make this field public but have not enabled any public price options. Please update your selections to include a public price option, or make this field admin visibility only.');
590 for ($index = 1; $index <= self::NUM_OPTION; $index++) {
591 if (!empty($fields['option_label'][$index]) || !empty($fields['option_amount'][$index])) {
592 $errors["option_visibility_id[{$index}]"] = ts('Public field should at least have one public option.');
593 }
594 }
595 }
596
597 if ($visibilityOptions[$fields['visibility_id']] == 'admin' && $publicOptionCount > 0) {
598 $errors['visibility_id'] = ts('Field with \'Admin\' visibility should only contain \'Admin\' options.');
599
600 for ($index = 1; $index <= self::NUM_OPTION; $index++) {
601
602 $isOptionSet = !empty($fields['option_label'][$index]) || !empty($fields['option_amount'][$index]);
9c1bc317 603 $currentOptionVisibility = $visibilityOptions[$fields['option_visibility_id'][$index]] ?? NULL;
a13c171d
CR
604
605 if ($isOptionSet && $currentOptionVisibility == 'public') {
606 $errors["option_visibility_id[{$index}]"] = ts('\'Admin\' field should only have \'Admin\' visibility options.');
607 }
608 }
609 }
6a488035
TO
610 }
611 elseif (!empty($fields['max_value']) &&
612 !empty($fields['count']) &&
613 ($fields['count'] > $fields['max_value'])
614 ) {
615 $errors['max_value'] = ts('Participant count can not be greater than max participants.');
616 }
617
618 // do not process if no option rows were submitted
619 if (empty($fields['option_amount']) && empty($fields['option_label'])) {
620 return TRUE;
621 }
622
623 if (empty($fields['option_name'])) {
be2fb01f 624 $fields['option_amount'] = [];
6a488035
TO
625 }
626
627 if (empty($fields['option_label'])) {
be2fb01f 628 $fields['option_label'] = [];
6a488035
TO
629 }
630 }
631
632 return empty($errors) ? TRUE : $errors;
633 }
634
635 /**
fe482240 636 * Process the form.
a72a9544 637 *
638 * @throws \CRM_Core_Exception
431c56b2 639 * @throws \CiviCRM_API3_Exception
6a488035
TO
640 */
641 public function postProcess() {
642 // store the submitted values in an array
643 $params = $this->controller->exportValues('Field');
431c56b2 644 $params['price'] = CRM_Utils_Rule::cleanMoney($params['price']);
6a488035 645
6a488035
TO
646 $params['is_display_amounts'] = CRM_Utils_Array::value('is_display_amounts', $params, FALSE);
647 $params['is_required'] = CRM_Utils_Array::value('is_required', $params, FALSE);
648 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
353ffa53 649 $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params, FALSE);
6a488035
TO
650 $params['visibility_id'] = CRM_Utils_Array::value('visibility_id', $params, FALSE);
651 $params['count'] = CRM_Utils_Array::value('count', $params, FALSE);
652
653 // need the FKEY - price set id
654 $params['price_set_id'] = $this->_sid;
655
656 if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
be2fb01f 657 $fieldValues = ['price_set_id' => $this->_sid];
6a488035 658 $oldWeight = NULL;
44374cbe 659 if ($this->getEntityId()) {
660 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $this->getEntityId(), 'weight', 'id');
6a488035 661 }
9da8dc8c 662 $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceField', $oldWeight, $params['weight'], $fieldValues);
6a488035
TO
663 }
664
665 // make value <=> name consistency.
666 if (isset($params['option_name'])) {
667 $params['option_value'] = $params['option_name'];
668 }
669 $params['is_enter_qty'] = CRM_Utils_Array::value('is_enter_qty', $params, FALSE);
670
a72a9544 671 if ($params['html_type'] === 'Text') {
6a488035
TO
672 // if html type is Text, force is_enter_qty on
673 $params['is_enter_qty'] = 1;
674 // modify params values as per the option group and option
675 // value
be2fb01f
CW
676 $params['option_amount'] = [1 => $params['price']];
677 $params['option_label'] = [1 => $params['label']];
678 $params['option_count'] = [1 => $params['count']];
679 $params['option_max_value'] = [1 => CRM_Utils_Array::value('max_value', $params)];
6a488035 680 //$params['option_description'] = array( 1 => $params['description'] );
be2fb01f
CW
681 $params['option_weight'] = [1 => $params['weight']];
682 $params['option_financial_type_id'] = [1 => $params['financial_type_id']];
683 $params['option_visibility_id'] = [1 => CRM_Utils_Array::value('visibility_id', $params)];
6a488035
TO
684 }
685
44374cbe 686 $params['id'] = $this->getEntityId();
366fe2a3 687
6a488035
TO
688 $params['membership_num_terms'] = (!empty($params['membership_type_id'])) ? CRM_Utils_Array::value('membership_num_terms', $params, 1) : NULL;
689
9da8dc8c 690 $priceField = CRM_Price_BAO_PriceField::create($params);
6a488035
TO
691
692 if (!is_a($priceField, 'CRM_Core_Error')) {
0582ba7f
ML
693 // Required by extensions implementing the postProcess hook (to get the ID of new entities)
694 $this->setEntityId($priceField->id);
be2fb01f 695 CRM_Core_Session::setStatus(ts('Price Field \'%1\' has been saved.', [1 => $priceField->label]), ts('Saved'), 'success');
6a488035
TO
696 }
697 $buttonName = $this->controller->getButtonName();
698 $session = CRM_Core_Session::singleton();
699 if ($buttonName == $this->getButtonName('next', 'new')) {
700 CRM_Core_Session::setStatus(ts(' You can add another price set field.'), '', 'info');
701 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/price/field', 'reset=1&action=add&sid=' . $this->_sid));
702 }
703 else {
704 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/price/field', 'reset=1&action=browse&sid=' . $this->_sid));
705 }
706 }
96025800 707
6a488035 708}