3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * form to process actions on the field aspect of Price
21 class CRM_Price_Form_Field
extends CRM_Core_Form
{
23 use CRM_Core_Form_EntityFormTrait
;
26 * Explicitly declare the entity api name.
28 public function getDefaultEntity() {
33 * Explicitly declare the form context.
35 public function getDefaultContext() {
40 * Get the entity id being edited.
44 public function getEntityId() {
49 * Constants for number of options for data types of multiple option.
51 const NUM_OPTION
= 15;
54 * The custom set id saved to the session for an update.
61 * The field id, used when editing the field
68 * The extended component Id.
72 protected $_extendComponentId;
75 * Variable is set if price set is used for membership.
78 protected $_useForMember;
81 * Set the price Set Id (only used in tests)
83 public function setPriceSetId($priceSetId) {
84 $this->_sid
= $priceSetId;
88 * Set variables up before form is built.
90 public function preProcess() {
92 $this->_sid
= CRM_Utils_Request
::retrieve('sid', 'Positive', $this);
93 $this->_fid
= CRM_Utils_Request
::retrieve('fid', 'Positive', $this);
94 $url = CRM_Utils_System
::url('civicrm/admin/price/field', "reset=1&action=browse&sid={$this->_sid}");
95 $breadCrumb = [['title' => ts('Price Set Fields'), 'url' => $url]];
97 $this->_extendComponentId
= [];
98 $extendComponentId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid
, 'extends', 'id');
99 if ($extendComponentId) {
100 $this->_extendComponentId
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $extendComponentId);
103 CRM_Utils_System
::appendBreadCrumb($breadCrumb);
105 $this->setPageTitle(ts('Price Field'));
109 * Set default values for the form.
112 * array of default values
113 * @throws \CRM_Core_Exception
115 public function setDefaultValues() {
117 // is it an edit operation ?
118 if ($this->getEntityId()) {
119 $params = ['id' => $this->getEntityId()];
120 $this->assign('fid', $this->getEntityId());
121 CRM_Price_BAO_PriceField
::retrieve($params, $defaults);
122 $this->_sid
= $defaults['price_set_id'];
124 // if text, retrieve price
125 if ($defaults['html_type'] == 'Text') {
126 $isActive = $defaults['is_active'];
127 $valueParams = ['price_field_id' => $this->getEntityId()];
129 CRM_Price_BAO_PriceFieldValue
::retrieve($valueParams, $defaults);
131 // fix the display of the monetary value, CRM-4038
132 $defaults['price'] = CRM_Utils_Money
::formatLocaleNumericRoundedForDefaultCurrency($defaults['amount']);
133 $defaults['is_active'] = $isActive;
138 $defaults['is_active'] = 1;
139 for ($i = 1; $i <= self
::NUM_OPTION
; $i++
) {
140 $defaults['option_status[' . $i . ']'] = 1;
141 $defaults['option_weight[' . $i . ']'] = $i;
142 $defaults['option_visibility_id[' . $i . ']'] = 1;
146 if ($this->_action
& CRM_Core_Action
::ADD
) {
147 $fieldValues = ['price_set_id' => $this->_sid
];
148 $defaults['weight'] = CRM_Utils_Weight
::getDefaultWeight('CRM_Price_DAO_PriceField', $fieldValues);
149 $defaults['options_per_line'] = 1;
150 $defaults['is_display_amounts'] = 1;
152 $enabledComponents = CRM_Core_Component
::getEnabledComponents();
153 $eventComponentId = NULL;
154 if (array_key_exists('CiviEvent', $enabledComponents)) {
155 $eventComponentId = CRM_Core_Component
::getComponentID('CiviEvent');
158 if (isset($this->_sid
) && $this->_action
== CRM_Core_Action
::ADD
) {
159 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid
, 'financial_type_id');
160 $defaults['financial_type_id'] = $financialTypeId;
161 for ($i = 1; $i <= self
::NUM_OPTION
; $i++
) {
162 $defaults['option_financial_type_id[' . $i . ']'] = $financialTypeId;
169 * Build the form object.
171 public function buildQuickForm() {
172 // lets trim all the whitespace
173 $this->applyFilter('__ALL__', 'trim');
175 // add a hidden field to remember the price set id
176 // this get around the browser tab issue
177 $this->add('hidden', 'sid', $this->_sid
);
178 $this->add('hidden', 'fid', $this->getEntityId());
181 $this->add('text', 'label', ts('Field Label'), CRM_Core_DAO
::getAttribute('CRM_Price_DAO_PriceField', 'label'), TRUE);
184 $javascript = ['onchange' => 'option_html_type(this.form);'];
186 $htmlTypes = CRM_Price_BAO_PriceField
::htmlTypes();
188 // Text box for Participant Count for a field
191 $financialType = CRM_Financial_BAO_FinancialType
::getIncomeFinancialType();
192 foreach ($financialType as $finTypeId => $type) {
193 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
194 && !CRM_Core_Permission
::check('add contributions of type ' . $type)
196 unset($financialType[$finTypeId]);
199 if (count($financialType)) {
200 $this->assign('financialType', $financialType);
203 //Visibility Type Options
204 $visibilityType = CRM_Core_PseudoConstant
::visibility();
205 $this->assign('visibilityType', $visibilityType);
207 $enabledComponents = CRM_Core_Component
::getEnabledComponents();
208 $eventComponentId = $memberComponentId = NULL;
209 if (array_key_exists('CiviEvent', $enabledComponents)) {
210 $eventComponentId = CRM_Core_Component
::getComponentID('CiviEvent');
212 if (array_key_exists('CiviMember', $enabledComponents)) {
213 $memberComponentId = CRM_Core_Component
::getComponentID('CiviMember');
216 $attributes = CRM_Core_DAO
::getAttribute('CRM_Price_DAO_PriceFieldValue');
218 $this->add('select', 'financial_type_id',
219 ts('Financial Type'),
220 [' ' => ts('- select -')] +
$financialType
223 $this->assign('useForMember', FALSE);
224 if (in_array($eventComponentId, $this->_extendComponentId
)) {
225 $this->add('text', 'count', ts('Participant Count'), $attributes['count']);
227 $this->addRule('count', ts('Participant Count should be a positive number'), 'positiveInteger');
229 $this->add('text', 'max_value', ts('Max Participants'), $attributes['max_value']);
230 $this->addRule('max_value', ts('Please enter a valid Max Participants.'), 'positiveInteger');
232 $this->assign('useForEvent', TRUE);
235 if (in_array($memberComponentId, $this->_extendComponentId
)) {
236 $this->_useForMember
= 1;
237 $this->assign('useForMember', $this->_useForMember
);
239 $this->assign('useForEvent', FALSE);
242 $sel = $this->add('select', 'html_type', ts('Input Field Type'),
243 $htmlTypes, TRUE, $javascript
246 // price (for text inputs)
247 $this->add('text', 'price', ts('Price'));
248 $this->registerRule('price', 'callback', 'money', 'CRM_Utils_Rule');
249 $this->addRule('price', ts('must be a monetary value'), 'money');
251 $this->add('text', 'non_deductible_amount', ts('Non-deductible Amount'), NULL);
252 $this->registerRule('non_deductible_amount', 'callback', 'money', 'CRM_Utils_Rule');
253 $this->addRule('non_deductible_amount', ts('Please enter a monetary value for this field.'), 'money');
255 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
256 $this->freeze('html_type');
259 // form fields of Custom Option rows
260 $_showHide = new CRM_Core_ShowHideBlocks('', '');
262 for ($i = 1; $i <= self
::NUM_OPTION
; $i++
) {
264 //the show hide blocks
265 $showBlocks = 'optionField_' . $i;
267 $_showHide->addHide($showBlocks);
268 if ($i == self
::NUM_OPTION
) {
269 $_showHide->addHide('additionalOption');
273 $_showHide->addShow($showBlocks);
276 $attributes['label']['size'] = 25;
277 $this->add('text', 'option_label[' . $i . ']', ts('Label'), $attributes['label']);
280 $this->add('text', 'option_amount[' . $i . ']', ts('Amount'), $attributes['amount']);
281 $this->addRule('option_amount[' . $i . ']', ts('Please enter a valid amount for this field.'), 'money');
286 'option_financial_type_id[' . $i . ']',
287 ts('Financial Type'),
288 ['' => ts('- select -')] +
$financialType
290 if (in_array($eventComponentId, $this->_extendComponentId
)) {
292 $this->add('text', 'option_count[' . $i . ']', ts('Participant Count'), $attributes['count']);
293 $this->addRule('option_count[' . $i . ']', ts('Please enter a valid Participants Count.'), 'positiveInteger');
296 $this->add('text', 'option_max_value[' . $i . ']', ts('Max Participants'), $attributes['max_value']);
297 $this->addRule('option_max_value[' . $i . ']', ts('Please enter a valid Max Participants.'), 'positiveInteger');
300 //$this->add('textArea', 'option_description['.$i.']', ts('Description'), array('rows' => 1, 'cols' => 40 ));
302 elseif (in_array($memberComponentId, $this->_extendComponentId
)) {
303 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
304 $js = ['onchange' => "calculateRowValues( $i );"];
306 $this->add('select', 'membership_type_id[' . $i . ']', ts('Membership Type'),
307 ['' => ' '] +
$membershipTypes, FALSE, $js
309 $this->add('text', 'membership_num_terms[' . $i . ']', ts('Number of Terms'), CRM_Utils_Array
::value('membership_num_terms', $attributes));
313 $this->add('number', 'option_weight[' . $i . ']', ts('Order'), $attributes['weight']);
316 $this->add('checkbox', 'option_status[' . $i . ']', ts('Active?'));
318 $this->add('select', 'option_visibility_id[' . $i . ']', ts('Visibility'), $visibilityType);
319 $defaultOption[$i] = NULL;
321 //for checkbox handling of default option
322 $this->add('checkbox', "default_checkbox_option[$i]", NULL);
324 //default option selection
325 $this->addRadio('default_option', NULL, $defaultOption);
326 $_showHide->addToTemplate();
328 // is_display_amounts
329 $this->add('checkbox', 'is_display_amounts', ts('Display Amount?'));
332 $this->add('number', 'weight', ts('Order'), CRM_Core_DAO
::getAttribute('CRM_Price_DAO_PriceField', 'weight'), TRUE);
333 $this->addRule('weight', ts('is a numeric field'), 'numeric');
335 // checkbox / radio options per line
336 $this->add('text', 'options_per_line', ts('Options Per Line'));
337 $this->addRule('options_per_line', ts('must be a numeric value'), 'numeric');
339 $this->add('textarea', 'help_pre', ts('Pre Field Help'),
340 CRM_Core_DAO
::getAttribute('CRM_Price_DAO_PriceField', 'help_pre')
343 // help post, mask, attributes, javascript ?
344 $this->add('textarea', 'help_post', ts('Post Field Help'),
345 CRM_Core_DAO
::getAttribute('CRM_Price_DAO_PriceField', 'help_post')
348 $this->add('datepicker', 'active_on', ts('Active On'), [], FALSE, ['time' => TRUE]);
351 $this->add('datepicker', 'expire_on', ts('Expire On'), [], FALSE, ['time' => TRUE]);
354 $this->add('checkbox', 'is_required', ts('Required?'));
357 $this->add('checkbox', 'is_active', ts('Active?'));
363 'name' => ts('Save'),
368 'name' => ts('Save and New'),
373 'name' => ts('Cancel'),
377 $this->add('select', 'visibility_id', ts('Visibility'), CRM_Core_PseudoConstant
::visibility());
379 // add a form rule to check default value
380 $this->addFormRule(['CRM_Price_Form_Field', 'formRule'], $this);
382 // if view mode pls freeze it with the done button.
383 if ($this->_action
& CRM_Core_Action
::VIEW
) {
385 $url = CRM_Utils_System
::url('civicrm/admin/price/field', 'reset=1&action=browse&sid=' . $this->_sid
);
386 $this->addElement('xbutton',
391 'onclick' => "location.href='$url'",
398 * Global validation rules for the form.
400 * @param array $fields
401 * Posted values of the form.
403 * @param array $files
407 * if errors then list of errors to be posted back to the form,
410 public static function formRule($fields, $files, $form) {
412 // all option fields are of type "money"
415 /** Check the option values entered
416 * Appropriate values are required for the selected datatype
417 * Incomplete row checking is also required.
419 if (($form->_action
& CRM_Core_Action
::ADD ||
$form->_action
& CRM_Core_Action
::UPDATE
) &&
420 $fields['html_type'] === 'Text'
422 if ($fields['price'] == NULL) {
423 $errors['price'] = ts('Price is a required field');
425 if ($fields['financial_type_id'] == '') {
426 $errors['financial_type_id'] = ts('Financial Type is a required field');
430 //avoid the same price field label in Within PriceSet
431 $priceFieldLabel = new CRM_Price_DAO_PriceField();
432 $priceFieldLabel->label
= $fields['label'];
433 $priceFieldLabel->price_set_id
= $form->_sid
;
436 if ($priceFieldLabel->find(TRUE) && $form->getEntityId() != $priceFieldLabel->id
) {
441 $errors['label'] = ts('Name already exists in Database.');
444 if ((is_numeric(CRM_Utils_Array
::value('count', $fields)) &&
445 empty($fields['count'])
447 (CRM_Utils_Array
::value('html_type', $fields) == 'Text')
449 $errors['count'] = ts('Participant Count must be greater than zero.');
452 if ($form->_action
& CRM_Core_Action
::ADD
) {
453 if ($fields['html_type'] != 'Text') {
455 $publicOptionCount = $_flagOption = $_rowError = 0;
457 $_showHide = new CRM_Core_ShowHideBlocks('', '');
458 $visibilityOptions = CRM_Price_BAO_PriceFieldValue
::buildOptions('visibility_id', 'validate');
460 for ($index = 1; $index <= self
::NUM_OPTION
; $index++
) {
462 $noLabel = $noAmount = $noWeight = 1;
463 if (!empty($fields['option_label'][$index])) {
465 $duplicateIndex = CRM_Utils_Array
::key($fields['option_label'][$index],
466 $fields['option_label']
469 if ((!($duplicateIndex === FALSE)) &&
470 (!($duplicateIndex == $index))
472 $errors["option_label[{$index}]"] = ts('Duplicate label value');
476 if ($form->_useForMember
) {
477 if (!empty($fields['membership_type_id'][$index])) {
478 $memTypesIDS[] = $fields['membership_type_id'][$index];
482 // allow for 0 value.
483 if (!empty($fields['option_amount'][$index]) ||
484 strlen($fields['option_amount'][$index]) > 0
489 if (!empty($fields['option_weight'][$index])) {
491 $duplicateIndex = CRM_Utils_Array
::key($fields['option_weight'][$index],
492 $fields['option_weight']
495 if ((!($duplicateIndex === FALSE)) &&
496 (!($duplicateIndex == $index))
498 $errors["option_weight[{$index}]"] = ts('Duplicate weight value');
502 if (!$noLabel && !$noAmount && !empty($fields['option_financial_type_id']) && $fields['option_financial_type_id'][$index] == '' && $fields['html_type'] != 'Text') {
503 $errors["option_financial_type_id[{$index}]"] = ts('Financial Type is a Required field.');
505 if ($noLabel && !$noAmount) {
506 $errors["option_label[{$index}]"] = ts('Label cannot be empty.');
510 if (!$noLabel && $noAmount) {
511 $errors["option_amount[{$index}]"] = ts('Amount cannot be empty.');
515 if ($noLabel && $noAmount) {
519 elseif (!empty($fields['option_max_value'][$index]) &&
520 !empty($fields['option_count'][$index]) &&
521 ($fields['option_count'][$index] > $fields['option_max_value'][$index])
523 $errors["option_max_value[{$index}]"] = ts('Participant count can not be greater than max participants.');
527 $showBlocks = 'optionField_' . $index;
529 $_showHide->addShow($showBlocks);
533 if (!empty($_emptyRow)) {
534 $_showHide->addHide($showBlocks);
537 $_showHide->addShow($showBlocks);
539 if ($index == self
::NUM_OPTION
) {
540 $hideBlock = 'additionalOption';
541 $_showHide->addHide($hideBlock);
544 if (!empty($fields['option_visibility_id'][$index]) && (!$noLabel ||
!$noAmount)) {
545 if ($visibilityOptions[$fields['option_visibility_id'][$index]] == 'public') {
546 $publicOptionCount++
;
550 $_flagOption = $_emptyRow = 0;
553 if (!empty($memTypesIDS)) {
554 // check for checkboxes allowing user to select multiple memberships from same membership organization
555 if ($fields['html_type'] == 'CheckBox') {
556 $foundDuplicate = FALSE;
558 foreach ($memTypesIDS as $key => $val) {
559 $memTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($val);
560 if (in_array($memTypeDetails['member_of_contact_id'], $orgIds)) {
561 $foundDuplicate = TRUE;
564 $orgIds[$val] = $memTypeDetails['member_of_contact_id'];
567 if ($foundDuplicate) {
568 $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.');
572 // CRM-10390 - Only one price field in a set can include auto-renew membership options
573 $foundAutorenew = FALSE;
574 foreach ($memTypesIDS as $key => $val) {
575 // see if any price field option values in this price field are for memberships with autorenew
576 $memTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($val);
577 if (!empty($memTypeDetails['auto_renew'])) {
578 $foundAutorenew = TRUE;
583 if ($foundAutorenew) {
584 // if so, check for other fields in this price set which also have auto-renew membership options
585 $otherFieldAutorenew = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($form->_sid
);
586 if ($otherFieldAutorenew) {
587 $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.');
591 $_showHide->addToTemplate();
593 if ($countemptyrows == 15) {
594 $errors['option_label[1]'] = $errors['option_amount[1]'] = ts('Label and value cannot be empty.');
598 if ($visibilityOptions[$fields['visibility_id']] == 'public' && $publicOptionCount == 0) {
599 $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.');
600 for ($index = 1; $index <= self
::NUM_OPTION
; $index++
) {
601 if (!empty($fields['option_label'][$index]) ||
!empty($fields['option_amount'][$index])) {
602 $errors["option_visibility_id[{$index}]"] = ts('Public field should at least have one public option.');
607 if ($visibilityOptions[$fields['visibility_id']] == 'admin' && $publicOptionCount > 0) {
608 $errors['visibility_id'] = ts('Field with \'Admin\' visibility should only contain \'Admin\' options.');
610 for ($index = 1; $index <= self
::NUM_OPTION
; $index++
) {
612 $isOptionSet = !empty($fields['option_label'][$index]) ||
!empty($fields['option_amount'][$index]);
613 $currentOptionVisibility = $visibilityOptions[$fields['option_visibility_id'][$index]] ??
NULL;
615 if ($isOptionSet && $currentOptionVisibility == 'public') {
616 $errors["option_visibility_id[{$index}]"] = ts('\'Admin\' field should only have \'Admin\' visibility options.');
621 elseif (!empty($fields['max_value']) &&
622 !empty($fields['count']) &&
623 ($fields['count'] > $fields['max_value'])
625 $errors['max_value'] = ts('Participant count can not be greater than max participants.');
628 // do not process if no option rows were submitted
629 if (empty($fields['option_amount']) && empty($fields['option_label'])) {
633 if (empty($fields['option_name'])) {
634 $fields['option_amount'] = [];
637 if (empty($fields['option_label'])) {
638 $fields['option_label'] = [];
642 return empty($errors) ?
TRUE : $errors;
648 * @throws \CRM_Core_Exception
649 * @throws \CiviCRM_API3_Exception
651 public function postProcess() {
652 // store the submitted values in an array
653 $params = $this->controller
->exportValues('Field');
654 $params['id'] = $this->getEntityId();
655 $priceField = $this->submit($params);
656 if (!is_a($priceField, 'CRM_Core_Error')) {
657 // Required by extensions implementing the postProcess hook (to get the ID of new entities)
658 $this->setEntityId($priceField->id
);
659 CRM_Core_Session
::setStatus(ts('Price Field \'%1\' has been saved.', [1 => $priceField->label
]), ts('Saved'), 'success');
661 $buttonName = $this->controller
->getButtonName();
662 $session = CRM_Core_Session
::singleton();
663 if ($buttonName == $this->getButtonName('next', 'new')) {
664 CRM_Core_Session
::setStatus(ts(' You can add another price set field.'), '', 'info');
665 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/admin/price/field', 'reset=1&action=add&sid=' . $this->_sid
));
668 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/admin/price/field', 'reset=1&action=browse&sid=' . $this->_sid
));
672 public function submit($params) {
673 $params['price'] = CRM_Utils_Rule
::cleanMoney($params['price']);
674 foreach ($params['option_amount'] as $key => $amount) {
675 $params['option_amount'][$key] = CRM_Utils_Rule
::cleanMoney($amount);
678 $params['is_display_amounts'] = CRM_Utils_Array
::value('is_display_amounts', $params, FALSE);
679 $params['is_required'] = CRM_Utils_Array
::value('is_required', $params, FALSE);
680 $params['is_active'] = CRM_Utils_Array
::value('is_active', $params, FALSE);
681 $params['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $params, FALSE);
682 $params['visibility_id'] = CRM_Utils_Array
::value('visibility_id', $params, FALSE);
683 $params['count'] = CRM_Utils_Array
::value('count', $params, FALSE);
685 // need the FKEY - price set id
686 $params['price_set_id'] = $this->_sid
;
688 if ($this->_action
& (CRM_Core_Action
::UPDATE | CRM_Core_Action
::ADD
)) {
689 $fieldValues = ['price_set_id' => $this->_sid
];
691 if ($this->getEntityId()) {
692 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $this->getEntityId(), 'weight', 'id');
694 $params['weight'] = CRM_Utils_Weight
::updateOtherWeights('CRM_Price_DAO_PriceField', $oldWeight, $params['weight'], $fieldValues);
697 // make value <=> name consistency.
698 if (isset($params['option_name'])) {
699 $params['option_value'] = $params['option_name'];
701 $params['is_enter_qty'] = CRM_Utils_Array
::value('is_enter_qty', $params, FALSE);
703 if ($params['html_type'] === 'Text') {
704 // if html type is Text, force is_enter_qty on
705 $params['is_enter_qty'] = 1;
706 // modify params values as per the option group and option
708 $params['option_amount'] = [1 => $params['price']];
709 $params['option_label'] = [1 => $params['label']];
710 $params['option_count'] = [1 => $params['count']];
711 $params['option_max_value'] = [1 => CRM_Utils_Array
::value('max_value', $params)];
712 //$params['option_description'] = array( 1 => $params['description'] );
713 $params['option_weight'] = [1 => $params['weight']];
714 $params['option_financial_type_id'] = [1 => $params['financial_type_id']];
715 $params['option_visibility_id'] = [1 => CRM_Utils_Array
::value('visibility_id', $params)];
718 $params['membership_num_terms'] = (!empty($params['membership_type_id'])) ? CRM_Utils_Array
::value('membership_num_terms', $params, 1) : NULL;
720 $priceField = CRM_Price_BAO_PriceField
::create($params);