571ab77be16ee7158efc542d658b88fa9d98a4c6
[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('button',
380 'done',
381 ts('Done'),
382 ['onclick' => "location.href='$url'"]
383 );
384 }
385 }
386
387 /**
388 * Global validation rules for the form.
389 *
390 * @param array $fields
391 * Posted values of the form.
392 *
393 * @param array $files
394 * @param self $form
395 *
396 * @return array
397 * if errors then list of errors to be posted back to the form,
398 * true otherwise
399 */
400 public static function formRule($fields, $files, $form) {
401
402 // all option fields are of type "money"
403 $errors = [];
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) &&
410 $fields['html_type'] === 'Text'
411 ) {
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 }
418 }
419
420 //avoid the same price field label in Within PriceSet
421 $priceFieldLabel = new CRM_Price_DAO_PriceField();
422 $priceFieldLabel->label = $fields['label'];
423 $priceFieldLabel->price_set_id = $form->_sid;
424
425 $dupeLabel = FALSE;
426 if ($priceFieldLabel->find(TRUE) && $form->getEntityId() != $priceFieldLabel->id) {
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)) &&
435 empty($fields['count'])
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;
445 $publicOptionCount = $_flagOption = $_rowError = 0;
446
447 $_showHide = new CRM_Core_ShowHideBlocks('', '');
448 $visibilityOptions = CRM_Price_BAO_PriceFieldValue::buildOptions('visibility_id', 'validate');
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 }
492 if (!$noLabel && !$noAmount && !empty($fields['option_financial_type_id']) && $fields['option_financial_type_id'][$index] == '' && $fields['html_type'] != 'Text') {
493 $errors["option_financial_type_id[{$index}]"] = ts('Financial Type is a Required field.');
494 }
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
534 if (!empty($fields['option_visibility_id'][$index]) && (!$noLabel || !$noAmount)) {
535 if ($visibilityOptions[$fields['option_visibility_id'][$index]] == 'public') {
536 $publicOptionCount++;
537 }
538 }
539
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') {
546 $foundDuplicate = FALSE;
547 $orgIds = [];
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];
555
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 }
560 }
561
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);
567 if (!empty($memTypeDetails['auto_renew'])) {
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
575 $otherFieldAutorenew = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($form->_sid);
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
583 if ($countemptyrows == 15) {
584 $errors['option_label[1]'] = $errors['option_amount[1]'] = ts('Label and value cannot be empty.');
585 $_flagOption = 1;
586 }
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]);
603 $currentOptionVisibility = $visibilityOptions[$fields['option_visibility_id'][$index]] ?? NULL;
604
605 if ($isOptionSet && $currentOptionVisibility == 'public') {
606 $errors["option_visibility_id[{$index}]"] = ts('\'Admin\' field should only have \'Admin\' visibility options.');
607 }
608 }
609 }
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'])) {
624 $fields['option_amount'] = [];
625 }
626
627 if (empty($fields['option_label'])) {
628 $fields['option_label'] = [];
629 }
630 }
631
632 return empty($errors) ? TRUE : $errors;
633 }
634
635 /**
636 * Process the form.
637 *
638 * @throws \CRM_Core_Exception
639 * @throws \CiviCRM_API3_Exception
640 */
641 public function postProcess() {
642 // store the submitted values in an array
643 $params = $this->controller->exportValues('Field');
644 $params['price'] = CRM_Utils_Rule::cleanMoney($params['price']);
645
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);
649 $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params, FALSE);
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)) {
657 $fieldValues = ['price_set_id' => $this->_sid];
658 $oldWeight = NULL;
659 if ($this->getEntityId()) {
660 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $this->getEntityId(), 'weight', 'id');
661 }
662 $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceField', $oldWeight, $params['weight'], $fieldValues);
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
671 if ($params['html_type'] === 'Text') {
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
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)];
680 //$params['option_description'] = array( 1 => $params['description'] );
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)];
684 }
685
686 $params['id'] = $this->getEntityId();
687
688 $params['membership_num_terms'] = (!empty($params['membership_type_id'])) ? CRM_Utils_Array::value('membership_num_terms', $params, 1) : NULL;
689
690 $priceField = CRM_Price_BAO_PriceField::create($params);
691
692 if (!is_a($priceField, 'CRM_Core_Error')) {
693 // Required by extensions implementing the postProcess hook (to get the ID of new entities)
694 $this->setEntityId($priceField->id);
695 CRM_Core_Session::setStatus(ts('Price Field \'%1\' has been saved.', [1 => $priceField->label]), ts('Saved'), 'success');
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 }
707
708 }