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
21 * Business objects for managing price fields.
24 class CRM_Price_BAO_PriceField
extends CRM_Price_DAO_PriceField
{
29 * List of visibility option ID's, of the form name => ID
33 private static $visibilityOptionsKeys;
36 * Create or update a PriceField.
38 * @param array $params
39 * @return CRM_Price_DAO_PriceField
41 public static function add($params) {
42 return self
::writeRecord($params);
46 * Takes an associative array and creates a price field object.
48 * This function is invoked from within the web form layer and also from the api layer
50 * @param array $params
51 * (reference) an assoc array of name/value pairs.
53 * @return CRM_Price_DAO_PriceField
55 * @throws \CRM_Core_Exception
56 * @throws \CiviCRM_API3_Exception
58 public static function create(&$params) {
59 if (empty($params['id']) && empty($params['name'])) {
60 $params['name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 242));
62 $transaction = new CRM_Core_Transaction();
64 $priceField = self
::add($params);
66 if (is_a($priceField, 'CRM_Core_Error')) {
67 $transaction->rollback();
71 if (!empty($params['id']) && empty($priceField->html_type
)) {
72 $priceField->html_type
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $params['id'], 'html_type');
75 $maxIndex = CRM_Price_Form_Field
::NUM_OPTION
;
76 if ($priceField->html_type
== 'Text') {
78 $fieldOptions = civicrm_api3('price_field_value', 'get', [
79 'price_field_id' => $priceField->id
,
82 foreach ($fieldOptions['values'] as $option) {
83 $optionsIds['id'] = $option['id'];
84 $params['option_id'] = [1 => $option['id']];
85 // CRM-19741 If we are dealing with price fields that are Text only set the field value label to match
86 if (!empty($params['id']) && $priceField->label
!= $option['label']) {
87 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
88 $fieldValue->label
= $priceField->label
;
89 $fieldValue->id
= $option['id'];
95 //html type would be empty in update scenario not sure what would happen ...
96 if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
97 $tempArray = array_keys($params['default_checkbox_option']);
98 foreach ($tempArray as $v) {
99 if ($params['option_amount'][$v]) {
100 $defaultArray[$v] = 1;
105 if (!empty($params['default_option'])) {
106 $defaultArray[$params['default_option']] = 1;
110 for ($index = 1; $index <= $maxIndex; $index++
) {
111 if (array_key_exists('option_amount', $params) &&
112 array_key_exists($index, $params['option_amount']) &&
113 (CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_label', $params)) ||
!empty($params['is_quick_config'])) &&
114 !CRM_Utils_System
::isNull($params['option_amount'][$index])
117 'price_field_id' => $priceField->id
,
118 'label' => trim($params['option_label'][$index]),
119 'name' => CRM_Utils_String
::munge($params['option_label'][$index], '_', 64),
120 'amount' => trim($params['option_amount'][$index]),
121 'count' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_count', $params), NULL),
122 'max_value' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_max_value', $params), NULL),
123 'description' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_description', $params), NULL),
124 'membership_type_id' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_type_id', $params), NULL),
125 'weight' => $params['option_weight'][$index],
127 'is_default' => !empty($defaultArray[$params['option_weight'][$index]]) ?
$defaultArray[$params['option_weight'][$index]] : 0,
128 'membership_num_terms' => NULL,
129 'non_deductible_amount' => $params['non_deductible_amount'] ??
NULL,
130 'visibility_id' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_visibility_id', $params), self
::getVisibilityOptionID('public')),
133 if ($options['membership_type_id']) {
134 $options['membership_num_terms'] = CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_num_terms', $params), 1);
135 $options['is_default'] = !empty($defaultArray[$params['membership_type_id'][$index]]) ?
$defaultArray[$params['membership_type_id'][$index]] : 0;
138 if (CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_financial_type_id', $params))) {
139 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
141 elseif (!empty($params['financial_type_id'])) {
142 $options['financial_type_id'] = $params['financial_type_id'];
144 if ($opIds = CRM_Utils_Array
::value('option_id', $params)) {
145 if ($opId = CRM_Utils_Array
::value($index, $opIds)) {
146 $options['id'] = $opId;
149 $options['id'] = NULL;
153 CRM_Price_BAO_PriceFieldValue
::create($options, $optionsIds);
155 catch (Exception
$e) {
156 $transaction->rollback();
157 throw new CRM_Core_Exception($e->getMessage());
160 elseif (!empty($optionsIds) && !empty($optionsIds['id'])) {
161 $optionsLoad = civicrm_api3('price_field_value', 'get', ['id' => $optionsIds['id']]);
162 $options = $optionsLoad['values'][$optionsIds['id']];
163 $options['is_active'] = CRM_Utils_Array
::value('is_active', $params, 1);
165 CRM_Price_BAO_PriceFieldValue
::create($options, $optionsIds);
167 catch (Exception
$e) {
168 $transaction->rollback();
169 throw new CRM_Core_Exception($e->getMessage());
174 $transaction->commit();
179 * Fetch object based on array of properties.
181 * @param array $params
182 * (reference ) an assoc array of name/value pairs.
183 * @param array $defaults
184 * (reference ) an assoc array to hold the flattened values.
186 * @return CRM_Price_DAO_PriceField
188 public static function retrieve(&$params, &$defaults) {
189 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
193 * Update the is_active flag in the db.
196 * Id of the database record.
197 * @param bool $is_active
198 * Value we want to set the is_active field.
201 * true if we found and updated the object, else false
203 public static function setIsActive($id, $is_active) {
204 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
208 * Freeze form if the event is full.
211 * @param $fieldOptions
215 public static function freezeIfEnabled(&$element, $fieldOptions) {
216 if (!empty($fieldOptions['is_full'])) {
223 * Get the field title.
232 public static function getTitle($id) {
233 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
237 * This function for building custom fields.
239 * @param CRM_Core_Form $qf
240 * Form object (reference).
241 * @param string $elementName
242 * Name of the custom field.
243 * @param int $fieldId
244 * @param bool $inactiveNeeded
245 * @param bool $useRequired
246 * True if required else false.
247 * @param string $label
248 * Label for custom field.
250 * @param null $fieldOptions
251 * @param array $freezeOptions
255 public static function addQuickFormElement(
262 $fieldOptions = NULL,
266 $field = new CRM_Price_DAO_PriceField();
267 $field->id
= $fieldId;
268 if (!$field->find(TRUE)) {
269 /* FIXME: failure! */
274 if (isset($qf->_mode
) && empty($qf->_mode
)) {
277 elseif (isset($qf->_values
)) {
278 $is_pay_later = $qf->_values
['is_pay_later'] ??
NULL;
281 $otherAmount = $qf->get('values');
282 $config = CRM_Core_Config
::singleton();
283 $currencySymbol = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_Currency', $config->defaultCurrency
, 'symbol', 'name');
284 $qf->assign('currencySymbol', $currencySymbol);
285 // get currency name for price field and option attributes
286 $currencyName = $config->defaultCurrency
;
288 if (!isset($label)) {
289 $label = (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') ?
ts('Additional Contribution') : $field->label
;
292 if ($field->name
== 'contribution_amount') {
293 $qf->_contributionAmount
= 1;
296 if (isset($qf->_online
) && $qf->_online
) {
297 $useRequired = FALSE;
300 $customOption = $fieldOptions;
301 if (!is_array($customOption)) {
302 $customOption = CRM_Price_BAO_PriceField
::getOptions($field->id
, $inactiveNeeded);
306 $valueFieldName = 'amount';
308 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
309 $taxTerm = Civi
::settings()->get('tax_term');
310 $displayOpt = $invoiceSettings['tax_display_settings'] ??
NULL;
311 $invoicing = $invoiceSettings['invoicing'] ??
NULL;
312 switch ($field->html_type
) {
314 $optionKey = key($customOption);
315 $count = CRM_Utils_Array
::value('count', $customOption[$optionKey], '');
316 $max_value = CRM_Utils_Array
::value('max_value', $customOption[$optionKey], '');
317 $taxAmount = $customOption[$optionKey]['tax_amount'] ??
NULL;
318 if (isset($taxAmount) && $displayOpt && $invoicing) {
319 $qf->assign('displayOpt', $displayOpt);
320 $qf->assign('taxTerm', $taxTerm);
321 $qf->assign('invoicing', $invoicing);
323 $priceVal = implode($seperator, [
324 $customOption[$optionKey][$valueFieldName] +
$taxAmount,
330 if (!empty($qf->_membershipBlock
) && !empty($qf->_quickConfig
) && $field->name
== 'other_amount' && empty($qf->_contributionAmount
)) {
333 elseif (!empty($fieldOptions[$optionKey]['label'])) {
335 $label = $fieldOptions[$optionKey]['label'];
336 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
) && strtolower($fieldOptions[$optionKey]['name']) == 'other_amount') {
337 $label .= ' ' . $currencySymbol;
338 $qf->assign('priceset', $elementName);
339 $extra = ['onclick' => 'useAmountOther();'];
343 $element = &$qf->add('text', $elementName, $label,
346 'price' => json_encode([$optionKey, $priceVal]),
350 $useRequired && $field->is_required
353 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
356 // CRM-6902 - Add "max" option for a price set field
357 if (in_array($optionKey, $freezeOptions)) {
358 self
::freezeIfEnabled($element, $fieldOptions[$optionKey]);
359 // CRM-14696 - Improve display for sold out price set options
360 $element->setLabel($label . ' <span class="sold-out-option">' . ts('Sold out') . '</span>');
364 if (!empty($qf->_quickConfig
)) {
365 $message = ts('Please enter a valid amount.');
369 $message = ts('%1 must be a number (with or without decimal point).', [1 => $label]);
372 // integers will have numeric rule applied to them.
373 $qf->addRule($elementName, $message, $type);
379 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
)) {
380 $qf->assign('contriPriceset', $elementName);
383 foreach ($customOption as $opId => $opt) {
384 $taxAmount = $opt['tax_amount'] ??
NULL;
385 if ($field->is_display_amounts
) {
386 $opt['label'] = !empty($opt['label']) ?
$opt['label'] . '<span class="crm-price-amount-label-separator"> - </span>' : '';
387 $preHelpText = $postHelpText = '';
388 if (!empty($opt['help_pre'])) {
389 $preHelpText = '<span class="crm-price-amount-help-pre description">' . $opt['help_pre'] . '</span><span class="crm-price-amount-help-pre-separator">: </span>';
391 if (!empty($opt['help_post'])) {
392 $postHelpText = '<span class="crm-price-amount-help-post-separator">: </span><span class="crm-price-amount-help-post description">' . $opt['help_post'] . '</span>';
394 if (isset($taxAmount) && $invoicing) {
395 if ($displayOpt == 'Do_not_show') {
396 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName] +
$taxAmount) . '</span>';
398 elseif ($displayOpt == 'Inclusive') {
399 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName] +
$taxAmount) . '</span>';
400 $opt['label'] .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money
::format($opt['tax_amount']) . ')</span>';
403 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName]) . '</span>';
404 $opt['label'] .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money
::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
408 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName]) . '</span>';
410 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
412 $count = CRM_Utils_Array
::value('count', $opt, '');
413 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
414 $priceVal = implode($seperator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
415 if (isset($opt['visibility_id'])) {
416 $visibility_id = $opt['visibility_id'];
419 $visibility_id = self
::getVisibilityOptionID('public');
422 'price' => json_encode([$elementName, $priceVal]),
423 'data-amount' => $opt[$valueFieldName],
424 'data-currency' => $currencyName,
425 'data-price-field-values' => json_encode($customOption),
426 'visibility' => $visibility_id,
428 if (!empty($qf->_quickConfig
) && $field->name
== 'contribution_amount') {
429 $extra +
= ['onclick' => 'clearAmountOther();'];
431 if ($field->name
== 'membership_amount') {
433 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
434 'membership-type' => $opt['membership_type_id'],
436 $qf->assign('membershipFieldID', $field->id
);
439 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
441 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
444 // CRM-6902 - Add "max" option for a price set field
445 if (in_array($opId, $freezeOptions)) {
446 self
::freezeIfEnabled($choice[$opId], $customOption[$opId]);
447 // CRM-14696 - Improve display for sold out price set options
448 $choice[$opId]->setText('<span class="sold-out-option">' . $choice[$opId]->getText() . ' (' . ts('Sold out') . ')</span>');
451 if (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') {
452 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
454 'price' => json_encode([$elementName, '0|0']),
455 'data-currency' => $currencyName,
456 'onclick' => 'clearAmountOther();',
461 if (!$field->is_required
) {
463 if (!empty($otherAmount['is_allow_other_amount']) && $field->name
== 'contribution_amount') {
464 $none = ts('Other Amount');
466 elseif (!empty($qf->_membershipBlock
) && empty($qf->_membershipBlock
['is_required']) && $field->name
== 'membership_amount') {
467 $none = ts('No thank you');
470 $none = ts('- none -');
473 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
474 ['price' => json_encode([$elementName, '0'])]
478 $element = &$qf->addGroup($choice, $elementName, $label);
480 // make contribution field required for quick config when membership block is enabled
481 if (($field->name
== 'membership_amount' ||
$field->name
== 'contribution_amount')
482 && !empty($qf->_membershipBlock
) && !$field->is_required
484 $useRequired = $field->is_required
= TRUE;
487 if ($useRequired && $field->is_required
) {
488 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
493 $selectOption = $allowedOptions = $priceVal = [];
495 foreach ($customOption as $opt) {
496 $taxAmount = $opt['tax_amount'] ??
NULL;
497 $count = CRM_Utils_Array
::value('count', $opt, '');
498 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
500 if ($field->is_display_amounts
) {
501 $opt['label'] .= ' - ';
502 if (isset($taxAmount) && $invoicing) {
503 $opt['label'] = $opt['label'] . self
::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
506 $opt['label'] = $opt['label'] . CRM_Utils_Money
::format($opt[$valueFieldName]);
510 $priceVal[$opt['id']] = implode($seperator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
512 if (!in_array($opt['id'], $freezeOptions)) {
513 $allowedOptions[] = $opt['id'];
515 // CRM-14696 - Improve display for sold out price set options
517 $opt['id'] = 'crm_disabled_opt-' . $opt['id'];
518 $opt['label'] = $opt['label'] . ' (' . ts('Sold out') . ')';
521 $selectOption[$opt['id']] = $opt['label'];
524 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
527 if (isset($opt['visibility_id'])) {
528 $visibility_id = $opt['visibility_id'];
531 $visibility_id = self
::getVisibilityOptionID('public');
533 $element = &$qf->add('select', $elementName, $label,
535 '' => ts('- select -'),
537 $useRequired && $field->is_required
,
538 ['price' => json_encode($priceVal), 'class' => 'crm-select2', 'data-price-field-values' => json_encode($customOption)]
541 // CRM-6902 - Add "max" option for a price set field
542 $button = substr($qf->controller
->getButtonName(), -4);
543 if (!empty($freezeOptions) && $button != 'skip') {
544 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
551 foreach ($customOption as $opId => $opt) {
552 $taxAmount = $opt['tax_amount'] ??
NULL;
553 $count = CRM_Utils_Array
::value('count', $opt, '');
554 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
556 if ($field->is_display_amounts
) {
557 $preHelpText = $postHelpText = '';
558 if (isset($opt['help_pre'])) {
559 $preHelpText = '<span class="crm-price-amount-help-pre description">' . $opt['help_pre'] . '</span>: ';
561 if (isset($opt['help_post'])) {
562 $postHelpText = ': <span class="crm-price-amount-help-post description">' . $opt['help_post'] . '</span>';
564 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span> - ';
565 if (isset($taxAmount) && $invoicing) {
566 $opt['label'] .= self
::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
569 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
571 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
573 $priceVal = implode($seperator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
574 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
576 'price' => json_encode([$opt['id'], $priceVal]),
577 'data-amount' => $opt[$valueFieldName],
578 'data-currency' => $currencyName,
579 'visibility' => $opt['visibility_id'],
583 $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], ['size' => '4']);
584 $qf->addGroup($txtcheck, 'txt-' . $elementName, $label);
586 // CRM-6902 - Add "max" option for a price set field
587 if (in_array($opId, $freezeOptions)) {
588 self
::freezeIfEnabled($check[$opId], $customOption[$opId]);
589 // CRM-14696 - Improve display for sold out price set options
590 $check[$opId]->setText('<span class="sold-out-option">' . $check[$opId]->getText() . ' (' . ts('Sold out') . ')</span>');
593 $element = &$qf->addGroup($check, $elementName, $label);
594 if ($useRequired && $field->is_required
) {
595 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
599 if (isset($qf->_online
) && $qf->_online
) {
605 * Retrieve a list of options for the specified field.
607 * @param int $fieldId
609 * @param bool $inactiveNeeded
610 * Include inactive options.
612 * Discard stored values.
613 * @param bool $isDefaultContributionPriceSet
614 * Discard tax amount calculation for price set = default_contribution_amount.
619 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE, $isDefaultContributionPriceSet = FALSE) {
620 if ($reset ||
!isset(Civi
::$statics[__CLASS__
]['priceOptions'])) {
621 Civi
::$statics[__CLASS__
]['priceOptions'] = [];
622 // This would happen if the function was only called to clear the cache.
623 if (empty($fieldId)) {
628 if (empty(Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId])) {
629 $values = $options = [];
630 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
631 $options[$fieldId] = $values;
632 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
634 // ToDo - Code for Hook Invoke
636 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
637 if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates) && !$isDefaultContributionPriceSet) {
638 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
639 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
640 $options[$fieldId][$priceFieldId]['tax_amount'] = $taxAmount['tax_amount'];
643 Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId] = $options[$fieldId];
646 return Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId];
650 * @param $optionLabel
655 public static function getOptionId($optionLabel, $fid) {
656 if (!$optionLabel ||
!$fid) {
660 $optionGroupName = "civicrm_price_field.amount.{$fid}";
664 option_value.id as id
666 civicrm_option_value option_value,
667 civicrm_option_group option_group
669 option_group.name = %1
670 AND option_group.id = option_value.option_group_id
671 AND option_value.label = %2";
673 $dao = CRM_Core_DAO
::executeQuery($query, [
674 1 => [$optionGroupName, 'String'],
675 2 => [$optionLabel, 'String'],
678 while ($dao->fetch()) {
684 * Delete the price set field.
692 public static function deleteField($id) {
693 $field = new CRM_Price_DAO_PriceField();
696 if ($field->find(TRUE)) {
697 // delete the options for this field
698 CRM_Price_BAO_PriceFieldValue
::deleteValues($id);
700 // reorder the weight before delete
701 $fieldValues = ['price_set_id' => $field->price_set_id
];
703 CRM_Utils_Weight
::delWeight('CRM_Price_DAO_PriceField', $field->id
, $fieldValues);
705 // now delete the field
706 return $field->delete();
715 public static function &htmlTypes() {
716 static $htmlTypes = NULL;
719 'Text' => ts('Text / Numeric Quantity'),
720 'Select' => ts('Select'),
721 'Radio' => ts('Radio'),
722 'CheckBox' => ts('CheckBox'),
729 * Validate the priceset.
731 * @param int $priceSetId
734 * retrun the error string
738 * @param bool $allowNoneSelection
741 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
742 // check for at least one positive
743 // amount price field should be selected.
744 $priceField = new CRM_Price_DAO_PriceField();
745 $priceField->price_set_id
= $priceSetId;
750 if ($allowNoneSelection) {
751 $noneSelectedPriceFields = [];
754 while ($priceField->fetch()) {
755 $key = "price_{$priceField->id}";
757 if ($allowNoneSelection) {
758 if (array_key_exists($key, $fields)) {
759 if ($fields[$key] == 0 && !$priceField->is_required
) {
760 $noneSelectedPriceFields[] = $priceField->id
;
765 if (!empty($fields[$key])) {
766 $priceFields[$priceField->id
] = $fields[$key];
770 if (!empty($priceFields)) {
771 // we should has to have positive amount.
774 FROM civicrm_price_field
775 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
776 $fieldDAO = CRM_Core_DAO
::executeQuery($sql);
778 while ($fieldDAO->fetch()) {
779 $htmlTypes[$fieldDAO->id
] = $fieldDAO->html_type
;
782 $selectedAmounts = [];
784 foreach ($htmlTypes as $fieldId => $type) {
786 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $options);
788 if (empty($options)) {
792 if ($type == 'Text') {
793 foreach ($options as $opId => $option) {
794 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
798 elseif (is_array($fields["price_{$fieldId}"])) {
799 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
800 $selectedAmounts[$opId] = $options[$opId]['amount'];
803 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
804 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
808 list($componentName) = explode(':', $fields['_qf_default']);
809 // now we have all selected amount in hand.
810 $totalAmount = array_sum($selectedAmounts);
811 // The form offers a field to enter the amount paid. This may differ from the amount that is due to complete the purchase
812 $totalPaymentAmountEnteredOnForm = CRM_Utils_Array
::value('partial_payment_total', $fields, CRM_Utils_Array
::value('total_amount', $fields));
813 if ($totalAmount < 0) {
814 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', [1 => $componentName]);
816 elseif ($totalAmount > 0 &&
817 // if total amount is equal to all selected amount in hand
818 $totalPaymentAmountEnteredOnForm >= $totalAmount &&
819 (CRM_Utils_Array
::value('contribution_status_id', $fields) == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Partially paid'))
821 $error['total_amount'] = ts('You have specified the status Partially Paid but have entered an amount that equals or exceeds the amount due. Please adjust the status of the payment or the amount');
825 if ($allowNoneSelection) {
826 if (empty($noneSelectedPriceFields)) {
827 $error['_qf_default'] = ts('Please select at least one option from price set.');
831 $error['_qf_default'] = ts('Please select at least one option from price set.');
837 * Generate the label for price fields based on tax display setting option on CiviContribute Component Settings page.
840 * @param string $valueFieldName
842 * @param string $displayOpt
843 * Tax display setting option.
845 * @param string $taxTerm
848 * Tax label for custom field.
850 public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm) {
851 if ($displayOpt == 'Do_not_show') {
852 $label = CRM_Utils_Money
::format($opt[$valueFieldName] +
$opt['tax_amount']);
854 elseif ($displayOpt == 'Inclusive') {
855 $label = CRM_Utils_Money
::format($opt[$valueFieldName] +
$opt['tax_amount']);
856 $label .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money
::format($opt['tax_amount']) . ')</span>';
859 $label = CRM_Utils_Money
::format($opt[$valueFieldName]);
860 $label .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money
::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
867 * Given the name of a visibility option, returns its ID.
869 * @param string $visibilityName
873 public static function getVisibilityOptionID($visibilityName) {
875 if (!isset(self
::$visibilityOptionsKeys)) {
876 self
::$visibilityOptionsKeys = CRM_Price_BAO_PriceField
::buildOptions(
880 'labelColumn' => 'name',
886 if (isset(self
::$visibilityOptionsKeys[$visibilityName])) {
887 return self
::$visibilityOptionsKeys[$visibilityName];