Merge pull request #18117 from mattwire/529_master
[civicrm-core.git] / CRM / Price / 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 */
17
18 /**
19 * form to process actions on the field aspect of Price
20 */
21 class CRM_Price_Form_Field extends CRM_Core_Form {
22
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
48 /**
49 * Constants for number of options for data types of multiple option.
50 */
51 const NUM_OPTION = 15;
52
53 /**
54 * The custom set id saved to the session for an update.
55 *
56 * @var int
57 */
58 protected $_sid;
59
60 /**
61 * The field id, used when editing the field
62 *
63 * @var int
64 */
65 protected $_fid;
66
67 /**
68 * The extended component Id.
69 *
70 * @var array
71 */
72 protected $_extendComponentId;
73
74 /**
75 * Variable is set if price set is used for membership.
76 * @var bool
77 */
78 protected $_useForMember;
79
80 /**
81 * Set variables up before form is built.
82 */
83 public function preProcess() {
84
85 $this->_sid = CRM_Utils_Request::retrieve('sid', 'Positive', $this);
86 $this->_fid = CRM_Utils_Request::retrieve('fid', 'Positive', $this);
87 $url = CRM_Utils_System::url('civicrm/admin/price/field', "reset=1&action=browse&sid={$this->_sid}");
88 $breadCrumb = [['title' => ts('Price Set Fields'), 'url' => $url]];
89
90 $this->_extendComponentId = [];
91 $extendComponentId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'extends', 'id');
92 if ($extendComponentId) {
93 $this->_extendComponentId = explode(CRM_Core_DAO::VALUE_SEPARATOR, $extendComponentId);
94 }
95
96 CRM_Utils_System::appendBreadCrumb($breadCrumb);
97
98 $this->setPageTitle(ts('Price Field'));
99 }
100
101 /**
102 * Set default values for the form.
103 *
104 * @return array
105 * array of default values
106 * @throws \CRM_Core_Exception
107 */
108 public function setDefaultValues() {
109 $defaults = [];
110 // is it an edit operation ?
111 if ($this->getEntityId()) {
112 $params = ['id' => $this->getEntityId()];
113 $this->assign('fid', $this->getEntityId());
114 CRM_Price_BAO_PriceField::retrieve($params, $defaults);
115 $this->_sid = $defaults['price_set_id'];
116
117 // if text, retrieve price
118 if ($defaults['html_type'] == 'Text') {
119 $isActive = $defaults['is_active'];
120 $valueParams = ['price_field_id' => $this->getEntityId()];
121
122 CRM_Price_BAO_PriceFieldValue::retrieve($valueParams, $defaults);
123
124 // fix the display of the monetary value, CRM-4038
125 $defaults['price'] = CRM_Utils_Money::format($defaults['amount'], NULL, '%a');
126 $defaults['is_active'] = $isActive;
127 }
128
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;
135 $defaults['option_visibility_id[' . $i . ']'] = 1;
136 }
137 }
138
139 if ($this->_action & CRM_Core_Action::ADD) {
140 $fieldValues = ['price_set_id' => $this->_sid];
141 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Price_DAO_PriceField', $fieldValues);
142 $defaults['options_per_line'] = 1;
143 $defaults['is_display_amounts'] = 1;
144 }
145 $enabledComponents = CRM_Core_Component::getEnabledComponents();
146 $eventComponentId = NULL;
147 if (array_key_exists('CiviEvent', $enabledComponents)) {
148 $eventComponentId = CRM_Core_Component::getComponentID('CiviEvent');
149 }
150
151 if (isset($this->_sid) && $this->_action == CRM_Core_Action::ADD) {
152 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'financial_type_id');
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 /**
162 * Build the form object.
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);
171 $this->add('hidden', 'fid', $this->getEntityId());
172
173 // label
174 $this->add('text', 'label', ts('Field Label'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'label'), TRUE);
175
176 // html_type
177 $javascript = 'onchange="option_html_type(this.form)";';
178
179 $htmlTypes = CRM_Price_BAO_PriceField::htmlTypes();
180
181 // Text box for Participant Count for a field
182
183 // Financial Type
184 $financialType = CRM_Financial_BAO_FinancialType::getIncomeFinancialType();
185 foreach ($financialType as $finTypeId => $type) {
186 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
187 && !CRM_Core_Permission::check('add contributions of type ' . $type)
188 ) {
189 unset($financialType[$finTypeId]);
190 }
191 }
192 if (count($financialType)) {
193 $this->assign('financialType', $financialType);
194 }
195
196 //Visibility Type Options
197 $visibilityType = CRM_Core_PseudoConstant::visibility();
198 $this->assign('visibilityType', $visibilityType);
199
200 $enabledComponents = CRM_Core_Component::getEnabledComponents();
201 $eventComponentId = $memberComponentId = NULL;
202 if (array_key_exists('CiviEvent', $enabledComponents)) {
203 $eventComponentId = CRM_Core_Component::getComponentID('CiviEvent');
204 }
205 if (array_key_exists('CiviMember', $enabledComponents)) {
206 $memberComponentId = CRM_Core_Component::getComponentID('CiviMember');
207 }
208
209 $attributes = CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceFieldValue');
210
211 $this->add('select', 'financial_type_id',
212 ts('Financial Type'),
213 [' ' => ts('- select -')] + $financialType
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
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
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(
278 'select',
279 'option_financial_type_id[' . $i . ']',
280 ts('Financial Type'),
281 ['' => ts('- select -')] + $financialType
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();
297 $js = ['onchange' => "calculateRowValues( $i );"];
298
299 $this->add('select', 'membership_type_id[' . $i . ']', ts('Membership Type'),
300 ['' => ' '] + $membershipTypes, FALSE, $js
301 );
302 $this->add('text', 'membership_num_terms[' . $i . ']', ts('Number of Terms'), CRM_Utils_Array::value('membership_num_terms', $attributes));
303 }
304
305 // weight
306 $this->add('number', 'option_weight[' . $i . ']', ts('Order'), $attributes['weight']);
307
308 // is active ?
309 $this->add('checkbox', 'option_status[' . $i . ']', ts('Active?'));
310
311 $this->add('select', 'option_visibility_id[' . $i . ']', ts('Visibility'), $visibilityType);
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
325 $this->add('number', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'weight'), TRUE);
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
332 $this->add('textarea', 'help_pre', ts('Pre Field Help'),
333 CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'help_post')
334 );
335
336 // help post, mask, attributes, javascript ?
337 $this->add('textarea', 'help_post', ts('Post Field Help'),
338 CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceField', 'help_post')
339 );
340
341 $this->add('datepicker', 'active_on', ts('Active On'), [], FALSE, ['time' => TRUE]);
342
343 // expire_on
344 $this->add('datepicker', 'expire_on', ts('Expire On'), [], FALSE, ['time' => TRUE]);
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
353 $this->addButtons([
354 [
355 'type' => 'next',
356 'name' => ts('Save'),
357 'isDefault' => TRUE,
358 ],
359 [
360 'type' => 'next',
361 'name' => ts('Save and New'),
362 'subName' => 'new',
363 ],
364 [
365 'type' => 'cancel',
366 'name' => ts('Cancel'),
367 ],
368 ]);
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
373 $this->addFormRule(['CRM_Price_Form_Field', 'formRule'], $this);
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('xbutton',
380 'done',
381 ts('Done'),
382 [
383 'type' => 'button',
384 'onclick' => "location.href='$url'",
385 ]
386 );
387 }
388 }
389
390 /**
391 * Global validation rules for the form.
392 *
393 * @param array $fields
394 * Posted values of the form.
395 *
396 * @param array $files
397 * @param self $form
398 *
399 * @return array
400 * if errors then list of errors to be posted back to the form,
401 * true otherwise
402 */
403 public static function formRule($fields, $files, $form) {
404
405 // all option fields are of type "money"
406 $errors = [];
407
408 /** Check the option values entered
409 * Appropriate values are required for the selected datatype
410 * Incomplete row checking is also required.
411 */
412 if (($form->_action & CRM_Core_Action::ADD || $form->_action & CRM_Core_Action::UPDATE) &&
413 $fields['html_type'] === 'Text'
414 ) {
415 if ($fields['price'] == NULL) {
416 $errors['price'] = ts('Price is a required field');
417 }
418 if ($fields['financial_type_id'] == '') {
419 $errors['financial_type_id'] = ts('Financial Type is a required field');
420 }
421 }
422
423 //avoid the same price field label in Within PriceSet
424 $priceFieldLabel = new CRM_Price_DAO_PriceField();
425 $priceFieldLabel->label = $fields['label'];
426 $priceFieldLabel->price_set_id = $form->_sid;
427
428 $dupeLabel = FALSE;
429 if ($priceFieldLabel->find(TRUE) && $form->getEntityId() != $priceFieldLabel->id) {
430 $dupeLabel = TRUE;
431 }
432
433 if ($dupeLabel) {
434 $errors['label'] = ts('Name already exists in Database.');
435 }
436
437 if ((is_numeric(CRM_Utils_Array::value('count', $fields)) &&
438 empty($fields['count'])
439 ) &&
440 (CRM_Utils_Array::value('html_type', $fields) == 'Text')
441 ) {
442 $errors['count'] = ts('Participant Count must be greater than zero.');
443 }
444
445 if ($form->_action & CRM_Core_Action::ADD) {
446 if ($fields['html_type'] != 'Text') {
447 $countemptyrows = 0;
448 $publicOptionCount = $_flagOption = $_rowError = 0;
449
450 $_showHide = new CRM_Core_ShowHideBlocks('', '');
451 $visibilityOptions = CRM_Price_BAO_PriceFieldValue::buildOptions('visibility_id', 'validate');
452
453 for ($index = 1; $index <= self::NUM_OPTION; $index++) {
454
455 $noLabel = $noAmount = $noWeight = 1;
456 if (!empty($fields['option_label'][$index])) {
457 $noLabel = 0;
458 $duplicateIndex = CRM_Utils_Array::key($fields['option_label'][$index],
459 $fields['option_label']
460 );
461
462 if ((!($duplicateIndex === FALSE)) &&
463 (!($duplicateIndex == $index))
464 ) {
465 $errors["option_label[{$index}]"] = ts('Duplicate label value');
466 $_flagOption = 1;
467 }
468 }
469 if ($form->_useForMember) {
470 if (!empty($fields['membership_type_id'][$index])) {
471 $memTypesIDS[] = $fields['membership_type_id'][$index];
472 }
473 }
474
475 // allow for 0 value.
476 if (!empty($fields['option_amount'][$index]) ||
477 strlen($fields['option_amount'][$index]) > 0
478 ) {
479 $noAmount = 0;
480 }
481
482 if (!empty($fields['option_weight'][$index])) {
483 $noWeight = 0;
484 $duplicateIndex = CRM_Utils_Array::key($fields['option_weight'][$index],
485 $fields['option_weight']
486 );
487
488 if ((!($duplicateIndex === FALSE)) &&
489 (!($duplicateIndex == $index))
490 ) {
491 $errors["option_weight[{$index}]"] = ts('Duplicate weight value');
492 $_flagOption = 1;
493 }
494 }
495 if (!$noLabel && !$noAmount && !empty($fields['option_financial_type_id']) && $fields['option_financial_type_id'][$index] == '' && $fields['html_type'] != 'Text') {
496 $errors["option_financial_type_id[{$index}]"] = ts('Financial Type is a Required field.');
497 }
498 if ($noLabel && !$noAmount) {
499 $errors["option_label[{$index}]"] = ts('Label cannot be empty.');
500 $_flagOption = 1;
501 }
502
503 if (!$noLabel && $noAmount) {
504 $errors["option_amount[{$index}]"] = ts('Amount cannot be empty.');
505 $_flagOption = 1;
506 }
507
508 if ($noLabel && $noAmount) {
509 $countemptyrows++;
510 $_emptyRow = 1;
511 }
512 elseif (!empty($fields['option_max_value'][$index]) &&
513 !empty($fields['option_count'][$index]) &&
514 ($fields['option_count'][$index] > $fields['option_max_value'][$index])
515 ) {
516 $errors["option_max_value[{$index}]"] = ts('Participant count can not be greater than max participants.');
517 $_flagOption = 1;
518 }
519
520 $showBlocks = 'optionField_' . $index;
521 if ($_flagOption) {
522 $_showHide->addShow($showBlocks);
523 $_rowError = 1;
524 }
525
526 if (!empty($_emptyRow)) {
527 $_showHide->addHide($showBlocks);
528 }
529 else {
530 $_showHide->addShow($showBlocks);
531 }
532 if ($index == self::NUM_OPTION) {
533 $hideBlock = 'additionalOption';
534 $_showHide->addHide($hideBlock);
535 }
536
537 if (!empty($fields['option_visibility_id'][$index]) && (!$noLabel || !$noAmount)) {
538 if ($visibilityOptions[$fields['option_visibility_id'][$index]] == 'public') {
539 $publicOptionCount++;
540 }
541 }
542
543 $_flagOption = $_emptyRow = 0;
544 }
545
546 if (!empty($memTypesIDS)) {
547 // check for checkboxes allowing user to select multiple memberships from same membership organization
548 if ($fields['html_type'] == 'CheckBox') {
549 $foundDuplicate = FALSE;
550 $orgIds = [];
551 foreach ($memTypesIDS as $key => $val) {
552 $org = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization($val);
553 if (in_array($org[$val], $orgIds)) {
554 $foundDuplicate = TRUE;
555 break;
556 }
557 $orgIds[$val] = $org[$val];
558
559 }
560 if ($foundDuplicate) {
561 $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.');
562 }
563 }
564
565 // CRM-10390 - Only one price field in a set can include auto-renew membership options
566 $foundAutorenew = FALSE;
567 foreach ($memTypesIDS as $key => $val) {
568 // see if any price field option values in this price field are for memberships with autorenew
569 $memTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($val);
570 if (!empty($memTypeDetails['auto_renew'])) {
571 $foundAutorenew = TRUE;
572 break;
573 }
574 }
575
576 if ($foundAutorenew) {
577 // if so, check for other fields in this price set which also have auto-renew membership options
578 $otherFieldAutorenew = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($form->_sid);
579 if ($otherFieldAutorenew) {
580 $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.');
581 }
582 }
583 }
584 $_showHide->addToTemplate();
585
586 if ($countemptyrows == 15) {
587 $errors['option_label[1]'] = $errors['option_amount[1]'] = ts('Label and value cannot be empty.');
588 $_flagOption = 1;
589 }
590
591 if ($visibilityOptions[$fields['visibility_id']] == 'public' && $publicOptionCount == 0) {
592 $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.');
593 for ($index = 1; $index <= self::NUM_OPTION; $index++) {
594 if (!empty($fields['option_label'][$index]) || !empty($fields['option_amount'][$index])) {
595 $errors["option_visibility_id[{$index}]"] = ts('Public field should at least have one public option.');
596 }
597 }
598 }
599
600 if ($visibilityOptions[$fields['visibility_id']] == 'admin' && $publicOptionCount > 0) {
601 $errors['visibility_id'] = ts('Field with \'Admin\' visibility should only contain \'Admin\' options.');
602
603 for ($index = 1; $index <= self::NUM_OPTION; $index++) {
604
605 $isOptionSet = !empty($fields['option_label'][$index]) || !empty($fields['option_amount'][$index]);
606 $currentOptionVisibility = $visibilityOptions[$fields['option_visibility_id'][$index]] ?? NULL;
607
608 if ($isOptionSet && $currentOptionVisibility == 'public') {
609 $errors["option_visibility_id[{$index}]"] = ts('\'Admin\' field should only have \'Admin\' visibility options.');
610 }
611 }
612 }
613 }
614 elseif (!empty($fields['max_value']) &&
615 !empty($fields['count']) &&
616 ($fields['count'] > $fields['max_value'])
617 ) {
618 $errors['max_value'] = ts('Participant count can not be greater than max participants.');
619 }
620
621 // do not process if no option rows were submitted
622 if (empty($fields['option_amount']) && empty($fields['option_label'])) {
623 return TRUE;
624 }
625
626 if (empty($fields['option_name'])) {
627 $fields['option_amount'] = [];
628 }
629
630 if (empty($fields['option_label'])) {
631 $fields['option_label'] = [];
632 }
633 }
634
635 return empty($errors) ? TRUE : $errors;
636 }
637
638 /**
639 * Process the form.
640 *
641 * @throws \CRM_Core_Exception
642 * @throws \CiviCRM_API3_Exception
643 */
644 public function postProcess() {
645 // store the submitted values in an array
646 $params = $this->controller->exportValues('Field');
647 $params['price'] = CRM_Utils_Rule::cleanMoney($params['price']);
648
649 $params['is_display_amounts'] = CRM_Utils_Array::value('is_display_amounts', $params, FALSE);
650 $params['is_required'] = CRM_Utils_Array::value('is_required', $params, FALSE);
651 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
652 $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params, FALSE);
653 $params['visibility_id'] = CRM_Utils_Array::value('visibility_id', $params, FALSE);
654 $params['count'] = CRM_Utils_Array::value('count', $params, FALSE);
655
656 // need the FKEY - price set id
657 $params['price_set_id'] = $this->_sid;
658
659 if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
660 $fieldValues = ['price_set_id' => $this->_sid];
661 $oldWeight = NULL;
662 if ($this->getEntityId()) {
663 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $this->getEntityId(), 'weight', 'id');
664 }
665 $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceField', $oldWeight, $params['weight'], $fieldValues);
666 }
667
668 // make value <=> name consistency.
669 if (isset($params['option_name'])) {
670 $params['option_value'] = $params['option_name'];
671 }
672 $params['is_enter_qty'] = CRM_Utils_Array::value('is_enter_qty', $params, FALSE);
673
674 if ($params['html_type'] === 'Text') {
675 // if html type is Text, force is_enter_qty on
676 $params['is_enter_qty'] = 1;
677 // modify params values as per the option group and option
678 // value
679 $params['option_amount'] = [1 => $params['price']];
680 $params['option_label'] = [1 => $params['label']];
681 $params['option_count'] = [1 => $params['count']];
682 $params['option_max_value'] = [1 => CRM_Utils_Array::value('max_value', $params)];
683 //$params['option_description'] = array( 1 => $params['description'] );
684 $params['option_weight'] = [1 => $params['weight']];
685 $params['option_financial_type_id'] = [1 => $params['financial_type_id']];
686 $params['option_visibility_id'] = [1 => CRM_Utils_Array::value('visibility_id', $params)];
687 }
688
689 $params['id'] = $this->getEntityId();
690
691 $params['membership_num_terms'] = (!empty($params['membership_type_id'])) ? CRM_Utils_Array::value('membership_num_terms', $params, 1) : NULL;
692
693 $priceField = CRM_Price_BAO_PriceField::create($params);
694
695 if (!is_a($priceField, 'CRM_Core_Error')) {
696 // Required by extensions implementing the postProcess hook (to get the ID of new entities)
697 $this->setEntityId($priceField->id);
698 CRM_Core_Session::setStatus(ts('Price Field \'%1\' has been saved.', [1 => $priceField->label]), ts('Saved'), 'success');
699 }
700 $buttonName = $this->controller->getButtonName();
701 $session = CRM_Core_Session::singleton();
702 if ($buttonName == $this->getButtonName('next', 'new')) {
703 CRM_Core_Session::setStatus(ts(' You can add another price set field.'), '', 'info');
704 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/price/field', 'reset=1&action=add&sid=' . $this->_sid));
705 }
706 else {
707 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/price/field', 'reset=1&action=browse&sid=' . $this->_sid));
708 }
709 }
710
711 }