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 variables up before form is built.
83 public function preProcess() {
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]];
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);
96 CRM_Utils_System
::appendBreadCrumb($breadCrumb);
98 $this->setPageTitle(ts('Price Field'));
102 * Set default values for the form.
105 * array of default values
106 * @throws \CRM_Core_Exception
108 public function setDefaultValues() {
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'];
117 // if text, retrieve price
118 if ($defaults['html_type'] == 'Text') {
119 $isActive = $defaults['is_active'];
120 $valueParams = ['price_field_id' => $this->getEntityId()];
122 CRM_Price_BAO_PriceFieldValue
::retrieve($valueParams, $defaults);
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;
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;
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;
145 $enabledComponents = CRM_Core_Component
::getEnabledComponents();
146 $eventComponentId = NULL;
147 if (array_key_exists('CiviEvent', $enabledComponents)) {
148 $eventComponentId = CRM_Core_Component
::getComponentID('CiviEvent');
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;
162 * Build the form object.
164 public function buildQuickForm() {
165 // lets trim all the whitespace
166 $this->applyFilter('__ALL__', 'trim');
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());
174 $this->add('text', 'label', ts('Field Label'), CRM_Core_DAO
::getAttribute('CRM_Price_DAO_PriceField', 'label'), TRUE);
177 $javascript = 'onchange="option_html_type(this.form)";';
179 $htmlTypes = CRM_Price_BAO_PriceField
::htmlTypes();
181 // Text box for Participant Count for a field
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)
189 unset($financialType[$finTypeId]);
192 if (count($financialType)) {
193 $this->assign('financialType', $financialType);
196 //Visibility Type Options
197 $visibilityType = CRM_Core_PseudoConstant
::visibility();
198 $this->assign('visibilityType', $visibilityType);
200 $enabledComponents = CRM_Core_Component
::getEnabledComponents();
201 $eventComponentId = $memberComponentId = NULL;
202 if (array_key_exists('CiviEvent', $enabledComponents)) {
203 $eventComponentId = CRM_Core_Component
::getComponentID('CiviEvent');
205 if (array_key_exists('CiviMember', $enabledComponents)) {
206 $memberComponentId = CRM_Core_Component
::getComponentID('CiviMember');
209 $attributes = CRM_Core_DAO
::getAttribute('CRM_Price_DAO_PriceFieldValue');
211 $this->add('select', 'financial_type_id',
212 ts('Financial Type'),
213 [' ' => ts('- select -')] +
$financialType
216 $this->assign('useForMember', FALSE);
217 if (in_array($eventComponentId, $this->_extendComponentId
)) {
218 $this->add('text', 'count', ts('Participant Count'), $attributes['count']);
220 $this->addRule('count', ts('Participant Count should be a positive number'), 'positiveInteger');
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');
225 $this->assign('useForEvent', TRUE);
228 if (in_array($memberComponentId, $this->_extendComponentId
)) {
229 $this->_useForMember
= 1;
230 $this->assign('useForMember', $this->_useForMember
);
232 $this->assign('useForEvent', FALSE);
235 $sel = $this->add('select', 'html_type', ts('Input Field Type'),
236 $htmlTypes, TRUE, $javascript
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');
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');
248 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
249 $this->freeze('html_type');
252 // form fields of Custom Option rows
253 $_showHide = new CRM_Core_ShowHideBlocks('', '');
255 for ($i = 1; $i <= self
::NUM_OPTION
; $i++
) {
257 //the show hide blocks
258 $showBlocks = 'optionField_' . $i;
260 $_showHide->addHide($showBlocks);
261 if ($i == self
::NUM_OPTION
) {
262 $_showHide->addHide('additionalOption');
266 $_showHide->addShow($showBlocks);
269 $attributes['label']['size'] = 25;
270 $this->add('text', 'option_label[' . $i . ']', ts('Label'), $attributes['label']);
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');
279 'option_financial_type_id[' . $i . ']',
280 ts('Financial Type'),
281 ['' => ts('- select -')] +
$financialType
283 if (in_array($eventComponentId, $this->_extendComponentId
)) {
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');
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');
293 //$this->add('textArea', 'option_description['.$i.']', ts('Description'), array('rows' => 1, 'cols' => 40 ));
295 elseif (in_array($memberComponentId, $this->_extendComponentId
)) {
296 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
297 $js = ['onchange' => "calculateRowValues( $i );"];
299 $this->add('select', 'membership_type_id[' . $i . ']', ts('Membership Type'),
300 ['' => ' '] +
$membershipTypes, FALSE, $js
302 $this->add('text', 'membership_num_terms[' . $i . ']', ts('Number of Terms'), CRM_Utils_Array
::value('membership_num_terms', $attributes));
306 $this->add('number', 'option_weight[' . $i . ']', ts('Order'), $attributes['weight']);
309 $this->add('checkbox', 'option_status[' . $i . ']', ts('Active?'));
311 $this->add('select', 'option_visibility_id[' . $i . ']', ts('Visibility'), $visibilityType);
312 $defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i);
314 //for checkbox handling of default option
315 $this->add('checkbox', "default_checkbox_option[$i]", NULL);
317 //default option selection
318 $this->addGroup($defaultOption, 'default_option');
319 $_showHide->addToTemplate();
321 // is_display_amounts
322 $this->add('checkbox', 'is_display_amounts', ts('Display Amount?'));
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');
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');
332 $this->add('textarea', 'help_pre', ts('Pre Field Help'),
333 CRM_Core_DAO
::getAttribute('CRM_Price_DAO_PriceField', 'help_post')
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')
341 $this->add('datepicker', 'active_on', ts('Active On'), [], FALSE, ['time' => TRUE]);
344 $this->add('datepicker', 'expire_on', ts('Expire On'), [], FALSE, ['time' => TRUE]);
347 $this->add('checkbox', 'is_required', ts('Required?'));
350 $this->add('checkbox', 'is_active', ts('Active?'));
356 'name' => ts('Save'),
361 'name' => ts('Save and New'),
366 'name' => ts('Cancel'),
370 $this->add('select', 'visibility_id', ts('Visibility'), CRM_Core_PseudoConstant
::visibility());
372 // add a form rule to check default value
373 $this->addFormRule(['CRM_Price_Form_Field', 'formRule'], $this);
375 // if view mode pls freeze it with the done button.
376 if ($this->_action
& CRM_Core_Action
::VIEW
) {
378 $url = CRM_Utils_System
::url('civicrm/admin/price/field', 'reset=1&action=browse&sid=' . $this->_sid
);
379 $this->addElement('button',
382 ['onclick' => "location.href='$url'"]
388 * Global validation rules for the form.
390 * @param array $fields
391 * Posted values of the form.
393 * @param array $files
397 * if errors then list of errors to be posted back to the form,
400 public static function formRule($fields, $files, $form) {
402 // all option fields are of type "money"
405 /** Check the option values entered
406 * Appropriate values are required for the selected datatype
407 * Incomplete row checking is also required.
409 if (($form->_action
& CRM_Core_Action
::ADD ||
$form->_action
& CRM_Core_Action
::UPDATE
) &&
410 $fields['html_type'] === 'Text'
412 if ($fields['price'] == NULL) {
413 $errors['price'] = ts('Price is a required field');
415 if ($fields['financial_type_id'] == '') {
416 $errors['financial_type_id'] = ts('Financial Type is a required field');
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
;
426 if ($priceFieldLabel->find(TRUE) && $form->getEntityId() != $priceFieldLabel->id
) {
431 $errors['label'] = ts('Name already exists in Database.');
434 if ((is_numeric(CRM_Utils_Array
::value('count', $fields)) &&
435 empty($fields['count'])
437 (CRM_Utils_Array
::value('html_type', $fields) == 'Text')
439 $errors['count'] = ts('Participant Count must be greater than zero.');
442 if ($form->_action
& CRM_Core_Action
::ADD
) {
443 if ($fields['html_type'] != 'Text') {
445 $publicOptionCount = $_flagOption = $_rowError = 0;
447 $_showHide = new CRM_Core_ShowHideBlocks('', '');
448 $visibilityOptions = CRM_Price_BAO_PriceFieldValue
::buildOptions('visibility_id', 'validate');
450 for ($index = 1; $index <= self
::NUM_OPTION
; $index++
) {
452 $noLabel = $noAmount = $noWeight = 1;
453 if (!empty($fields['option_label'][$index])) {
455 $duplicateIndex = CRM_Utils_Array
::key($fields['option_label'][$index],
456 $fields['option_label']
459 if ((!($duplicateIndex === FALSE)) &&
460 (!($duplicateIndex == $index))
462 $errors["option_label[{$index}]"] = ts('Duplicate label value');
466 if ($form->_useForMember
) {
467 if (!empty($fields['membership_type_id'][$index])) {
468 $memTypesIDS[] = $fields['membership_type_id'][$index];
472 // allow for 0 value.
473 if (!empty($fields['option_amount'][$index]) ||
474 strlen($fields['option_amount'][$index]) > 0
479 if (!empty($fields['option_weight'][$index])) {
481 $duplicateIndex = CRM_Utils_Array
::key($fields['option_weight'][$index],
482 $fields['option_weight']
485 if ((!($duplicateIndex === FALSE)) &&
486 (!($duplicateIndex == $index))
488 $errors["option_weight[{$index}]"] = ts('Duplicate weight value');
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.');
495 if ($noLabel && !$noAmount) {
496 $errors["option_label[{$index}]"] = ts('Label cannot be empty.');
500 if (!$noLabel && $noAmount) {
501 $errors["option_amount[{$index}]"] = ts('Amount cannot be empty.');
505 if ($noLabel && $noAmount) {
509 elseif (!empty($fields['option_max_value'][$index]) &&
510 !empty($fields['option_count'][$index]) &&
511 ($fields['option_count'][$index] > $fields['option_max_value'][$index])
513 $errors["option_max_value[{$index}]"] = ts('Participant count can not be greater than max participants.');
517 $showBlocks = 'optionField_' . $index;
519 $_showHide->addShow($showBlocks);
523 if (!empty($_emptyRow)) {
524 $_showHide->addHide($showBlocks);
527 $_showHide->addShow($showBlocks);
529 if ($index == self
::NUM_OPTION
) {
530 $hideBlock = 'additionalOption';
531 $_showHide->addHide($hideBlock);
534 if (!empty($fields['option_visibility_id'][$index]) && (!$noLabel ||
!$noAmount)) {
535 if ($visibilityOptions[$fields['option_visibility_id'][$index]] == 'public') {
536 $publicOptionCount++
;
540 $_flagOption = $_emptyRow = 0;
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;
548 foreach ($memTypesIDS as $key => $val) {
549 $org = CRM_Member_BAO_MembershipType
::getMembershipTypeOrganization($val);
550 if (in_array($org[$val], $orgIds)) {
551 $foundDuplicate = TRUE;
554 $orgIds[$val] = $org[$val];
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.');
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;
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.');
581 $_showHide->addToTemplate();
583 if ($countemptyrows == 15) {
584 $errors['option_label[1]'] = $errors['option_amount[1]'] = ts('Label and value cannot be empty.');
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.');
597 if ($visibilityOptions[$fields['visibility_id']] == 'admin' && $publicOptionCount > 0) {
598 $errors['visibility_id'] = ts('Field with \'Admin\' visibility should only contain \'Admin\' options.');
600 for ($index = 1; $index <= self
::NUM_OPTION
; $index++
) {
602 $isOptionSet = !empty($fields['option_label'][$index]) ||
!empty($fields['option_amount'][$index]);
603 $currentOptionVisibility = $visibilityOptions[$fields['option_visibility_id'][$index]] ??
NULL;
605 if ($isOptionSet && $currentOptionVisibility == 'public') {
606 $errors["option_visibility_id[{$index}]"] = ts('\'Admin\' field should only have \'Admin\' visibility options.');
611 elseif (!empty($fields['max_value']) &&
612 !empty($fields['count']) &&
613 ($fields['count'] > $fields['max_value'])
615 $errors['max_value'] = ts('Participant count can not be greater than max participants.');
618 // do not process if no option rows were submitted
619 if (empty($fields['option_amount']) && empty($fields['option_label'])) {
623 if (empty($fields['option_name'])) {
624 $fields['option_amount'] = [];
627 if (empty($fields['option_label'])) {
628 $fields['option_label'] = [];
632 return empty($errors) ?
TRUE : $errors;
638 * @throws \CRM_Core_Exception
639 * @throws \CiviCRM_API3_Exception
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 foreach ($params['option_amount'] as $key => $amount) {
646 $params['option_amount'][$key] = CRM_Utils_Rule
::cleanMoney($amount);
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);
656 // need the FKEY - price set id
657 $params['price_set_id'] = $this->_sid
;
659 if ($this->_action
& (CRM_Core_Action
::UPDATE | CRM_Core_Action
::ADD
)) {
660 $fieldValues = ['price_set_id' => $this->_sid
];
662 if ($this->getEntityId()) {
663 $oldWeight = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $this->getEntityId(), 'weight', 'id');
665 $params['weight'] = CRM_Utils_Weight
::updateOtherWeights('CRM_Price_DAO_PriceField', $oldWeight, $params['weight'], $fieldValues);
668 // make value <=> name consistency.
669 if (isset($params['option_name'])) {
670 $params['option_value'] = $params['option_name'];
672 $params['is_enter_qty'] = CRM_Utils_Array
::value('is_enter_qty', $params, FALSE);
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
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)];
689 $params['id'] = $this->getEntityId();
691 $params['membership_num_terms'] = (!empty($params['membership_type_id'])) ? CRM_Utils_Array
::value('membership_num_terms', $params, 1) : NULL;
693 $priceField = CRM_Price_BAO_PriceField
::create($params);
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');
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
));
707 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/admin/price/field', 'reset=1&action=browse&sid=' . $this->_sid
));