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 +--------------------------------------------------------------------+
13 * Business objects for managing price fields.
16 class CRM_Price_BAO_PriceField
extends CRM_Price_DAO_PriceField
{
21 * List of visibility option ID's, of the form name => ID
25 private static $visibilityOptionsKeys;
28 * Create or update a PriceField.
30 * @param array $params
31 * @return CRM_Price_DAO_PriceField
33 public static function add($params) {
34 return self
::writeRecord($params);
38 * Takes an associative array and creates a price field object.
40 * This function is invoked from within the web form layer and also from the api layer
42 * @param array $params
43 * (reference) an assoc array of name/value pairs.
45 * @return CRM_Price_DAO_PriceField
47 * @throws \CRM_Core_Exception
48 * @throws \CiviCRM_API3_Exception
50 public static function create(&$params) {
51 if (empty($params['id']) && empty($params['name'])) {
52 $params['name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 242));
54 $transaction = new CRM_Core_Transaction();
56 $priceField = self
::add($params);
58 if (is_a($priceField, 'CRM_Core_Error')) {
59 $transaction->rollback();
63 if (!empty($params['id']) && empty($priceField->html_type
)) {
64 $priceField->html_type
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $params['id'], 'html_type');
67 $maxIndex = CRM_Price_Form_Field
::NUM_OPTION
;
68 if ($priceField->html_type
== 'Text') {
70 $fieldOptions = civicrm_api3('price_field_value', 'get', [
71 'price_field_id' => $priceField->id
,
74 foreach ($fieldOptions['values'] as $option) {
75 $optionsIds['id'] = $option['id'];
76 $params['option_id'] = [1 => $option['id']];
77 // CRM-19741 If we are dealing with price fields that are Text only set the field value label to match
78 if (!empty($params['id']) && $priceField->label
!= $option['label']) {
79 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
80 $fieldValue->label
= $priceField->label
;
81 $fieldValue->id
= $option['id'];
87 //html type would be empty in update scenario not sure what would happen ...
88 if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
89 $tempArray = array_keys($params['default_checkbox_option']);
90 foreach ($tempArray as $v) {
91 if ($params['option_amount'][$v]) {
92 $defaultArray[$v] = 1;
97 if (!empty($params['default_option'])) {
98 $defaultArray[$params['default_option']] = 1;
102 for ($index = 1; $index <= $maxIndex; $index++
) {
103 if (array_key_exists('option_amount', $params) &&
104 array_key_exists($index, $params['option_amount']) &&
105 (CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_label', $params)) ||
!empty($params['is_quick_config'])) &&
106 !CRM_Utils_System
::isNull($params['option_amount'][$index])
109 'price_field_id' => $priceField->id
,
110 'label' => trim($params['option_label'][$index]),
111 'name' => CRM_Utils_String
::munge($params['option_label'][$index], '_', 64),
112 'amount' => trim($params['option_amount'][$index]),
113 'count' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_count', $params), NULL),
114 'max_value' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_max_value', $params), NULL),
115 'description' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_description', $params), NULL),
116 'membership_type_id' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_type_id', $params), NULL),
117 'weight' => $params['option_weight'][$index],
119 'is_default' => !empty($defaultArray[$params['option_weight'][$index]]) ?
$defaultArray[$params['option_weight'][$index]] : 0,
120 'membership_num_terms' => NULL,
121 'non_deductible_amount' => $params['non_deductible_amount'] ??
NULL,
122 'visibility_id' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_visibility_id', $params), self
::getVisibilityOptionID('public')),
125 if ($options['membership_type_id']) {
126 $options['membership_num_terms'] = CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_num_terms', $params), 1);
127 $options['is_default'] = !empty($defaultArray[$params['membership_type_id'][$index]]) ?
$defaultArray[$params['membership_type_id'][$index]] : 0;
130 if (CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_financial_type_id', $params))) {
131 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
133 elseif (!empty($params['financial_type_id'])) {
134 $options['financial_type_id'] = $params['financial_type_id'];
136 if ($opIds = CRM_Utils_Array
::value('option_id', $params)) {
137 if ($opId = CRM_Utils_Array
::value($index, $opIds)) {
138 $options['id'] = $opId;
141 $options['id'] = NULL;
145 CRM_Price_BAO_PriceFieldValue
::create($options, $optionsIds);
147 catch (Exception
$e) {
148 $transaction->rollback();
149 throw new CRM_Core_Exception($e->getMessage());
152 elseif (!empty($optionsIds) && !empty($optionsIds['id'])) {
153 $optionsLoad = civicrm_api3('price_field_value', 'get', ['id' => $optionsIds['id']]);
154 $options = $optionsLoad['values'][$optionsIds['id']];
155 $options['is_active'] = CRM_Utils_Array
::value('is_active', $params, 1);
157 CRM_Price_BAO_PriceFieldValue
::create($options, $optionsIds);
159 catch (Exception
$e) {
160 $transaction->rollback();
161 throw new CRM_Core_Exception($e->getMessage());
166 $transaction->commit();
171 * Fetch object based on array of properties.
173 * @param array $params
174 * (reference ) an assoc array of name/value pairs.
175 * @param array $defaults
176 * (reference ) an assoc array to hold the flattened values.
178 * @return CRM_Price_DAO_PriceField
180 public static function retrieve(&$params, &$defaults) {
181 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
185 * Update the is_active flag in the db.
188 * Id of the database record.
189 * @param bool $is_active
190 * Value we want to set the is_active field.
193 * true if we found and updated the object, else false
195 public static function setIsActive($id, $is_active) {
196 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
200 * Freeze form if the event is full.
203 * @param $fieldOptions
207 public static function freezeIfEnabled(&$element, $fieldOptions) {
208 if (!empty($fieldOptions['is_full'])) {
215 * Get the field title.
224 public static function getTitle($id) {
225 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
229 * This function for building custom fields.
231 * @param CRM_Core_Form $qf
232 * Form object (reference).
233 * @param string $elementName
234 * Name of the custom field.
235 * @param int $fieldId
236 * @param bool $inactiveNeeded
237 * @param bool $useRequired
238 * True if required else false.
239 * @param string $label
240 * Label for custom field.
242 * @param null $fieldOptions
243 * @param array $freezeOptions
247 public static function addQuickFormElement(
254 $fieldOptions = NULL,
258 $field = new CRM_Price_DAO_PriceField();
259 $field->id
= $fieldId;
260 if (!$field->find(TRUE)) {
261 /* FIXME: failure! */
266 if (isset($qf->_mode
) && empty($qf->_mode
)) {
269 elseif (isset($qf->_values
)) {
270 $is_pay_later = $qf->_values
['is_pay_later'] ??
NULL;
273 $otherAmount = $qf->get('values');
274 $config = CRM_Core_Config
::singleton();
275 $currencySymbol = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_Currency', $config->defaultCurrency
, 'symbol', 'name');
276 $qf->assign('currencySymbol', $currencySymbol);
277 // get currency name for price field and option attributes
278 $currencyName = $config->defaultCurrency
;
280 if (!isset($label)) {
281 $label = (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') ?
ts('Additional Contribution') : $field->label
;
284 if ($field->name
=== 'contribution_amount') {
285 $qf->_contributionAmount
= 1;
288 if (isset($qf->_online
) && $qf->_online
) {
289 $useRequired = FALSE;
292 $customOption = $fieldOptions;
293 if (!is_array($customOption)) {
294 $customOption = CRM_Price_BAO_PriceField
::getOptions($field->id
, $inactiveNeeded);
298 $valueFieldName = 'amount';
300 $taxTerm = Civi
::settings()->get('tax_term');
301 $displayOpt = Civi
::settings()->get('tax_display_settings');
302 $invoicing = Civi
::settings()->get('invoicing');
303 switch ($field->html_type
) {
305 $optionKey = key($customOption);
306 $count = CRM_Utils_Array
::value('count', $customOption[$optionKey], '');
307 $max_value = CRM_Utils_Array
::value('max_value', $customOption[$optionKey], '');
308 $taxAmount = $customOption[$optionKey]['tax_amount'] ??
NULL;
309 if (isset($taxAmount) && $displayOpt && $invoicing) {
310 $qf->assign('displayOpt', $displayOpt);
311 $qf->assign('taxTerm', $taxTerm);
312 $qf->assign('invoicing', $invoicing);
314 $priceVal = implode($separator, [
315 $customOption[$optionKey][$valueFieldName] +
$taxAmount,
321 if (!empty($qf->_membershipBlock
) && !empty($qf->_quickConfig
) && $field->name
== 'other_amount' && empty($qf->_contributionAmount
)) {
324 elseif (!empty($fieldOptions[$optionKey]['label'])) {
326 $label = $fieldOptions[$optionKey]['label'];
327 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
) && strtolower($fieldOptions[$optionKey]['name']) == 'other_amount') {
328 $label .= ' ' . $currencySymbol;
329 $qf->assign('priceset', $elementName);
331 'onclick' => 'useAmountOther();',
332 'autocomplete' => 'off',
337 $element = &$qf->add('text', $elementName, $label,
340 'price' => json_encode([$optionKey, $priceVal]),
344 $useRequired && $field->is_required
347 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
350 // CRM-6902 - Add "max" option for a price set field
351 if (in_array($optionKey, $freezeOptions)) {
352 self
::freezeIfEnabled($element, $fieldOptions[$optionKey]);
353 // CRM-14696 - Improve display for sold out price set options
354 $element->setLabel($label . ' <span class="sold-out-option">' . ts('Sold out') . '</span>');
358 if (!empty($qf->_quickConfig
)) {
359 $message = ts('Please enter a valid amount.');
363 $message = ts('%1 must be a number (with or without decimal point).', [1 => $label]);
366 // integers will have numeric rule applied to them.
367 $qf->addRule($elementName, $message, $type);
373 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
)) {
374 $qf->assign('contriPriceset', $elementName);
377 foreach ($customOption as $opId => $opt) {
378 $taxAmount = $opt['tax_amount'] ??
NULL;
379 if ($field->is_display_amounts
) {
380 $opt['label'] = !empty($opt['label']) ?
$opt['label'] . '<span class="crm-price-amount-label-separator"> - </span>' : '';
381 $preHelpText = $postHelpText = '';
382 if (!empty($opt['help_pre'])) {
383 $preHelpText = '<span class="crm-price-amount-help-pre description">' . $opt['help_pre'] . '</span><span class="crm-price-amount-help-pre-separator">: </span>';
385 if (!empty($opt['help_post'])) {
386 $postHelpText = '<span class="crm-price-amount-help-post-separator">: </span><span class="crm-price-amount-help-post description">' . $opt['help_post'] . '</span>';
388 if (isset($taxAmount) && $invoicing) {
389 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . self
::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
392 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName]) . '</span>';
394 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
396 $count = CRM_Utils_Array
::value('count', $opt, '');
397 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
398 $priceVal = implode($separator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
399 if (isset($opt['visibility_id'])) {
400 $visibility_id = $opt['visibility_id'];
403 $visibility_id = self
::getVisibilityOptionID('public');
406 'price' => json_encode([$elementName, $priceVal]),
407 'data-amount' => $opt[$valueFieldName],
408 'data-currency' => $currencyName,
409 'data-price-field-values' => json_encode($customOption),
410 'visibility' => $visibility_id,
412 if (!empty($qf->_quickConfig
) && $field->name
== 'contribution_amount') {
413 $extra +
= ['onclick' => 'clearAmountOther();'];
415 if ($field->name
== 'membership_amount') {
417 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
418 'membership-type' => $opt['membership_type_id'],
420 $qf->assign('membershipFieldID', $field->id
);
423 $choice[$opt['id']] = $opt['label'];
424 $choiceAttrs[$opt['id']] = $extra;
426 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
429 if (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') {
430 $choice['-1'] = ts('No thank you');
431 $choiceAttrs['-1'] = [
432 'price' => json_encode([$elementName, '0|0']),
433 'data-currency' => $currencyName,
434 'onclick' => 'clearAmountOther();',
438 if (!$field->is_required
) {
440 if (!empty($otherAmount['is_allow_other_amount']) && $field->name
== 'contribution_amount') {
441 $none = ts('Other Amount');
443 elseif (!empty($qf->_membershipBlock
) && empty($qf->_membershipBlock
['is_required']) && $field->name
== 'membership_amount') {
444 $none = ts('No thank you');
447 $none = ts('- none -');
450 $choice['0'] = $none;
451 $choiceAttrs['0'] = ['price' => json_encode([$elementName, '0'])];
454 $element = &$qf->addRadio($elementName, $label, $choice, [], NULL, FALSE, $choiceAttrs);
455 foreach ($element->getElements() as $radioElement) {
456 // CRM-6902 - Add "max" option for a price set field
457 if (in_array($radioElement->getValue(), $freezeOptions)) {
458 self
::freezeIfEnabled($radioElement, $customOption[$radioElement->getValue()]);
459 // CRM-14696 - Improve display for sold out price set options
460 $radioElement->setText('<span class="sold-out-option">' . $radioElement->getText() . ' (' . ts('Sold out') . ')</span>');
464 // make contribution field required for quick config when membership block is enabled
465 if (($field->name
== 'membership_amount' ||
$field->name
== 'contribution_amount')
466 && !empty($qf->_membershipBlock
) && !$field->is_required
468 $useRequired = $field->is_required
= TRUE;
471 if ($useRequired && $field->is_required
) {
472 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
477 $selectOption = $allowedOptions = $priceVal = [];
479 foreach ($customOption as $opt) {
480 $taxAmount = $opt['tax_amount'] ??
NULL;
481 $count = CRM_Utils_Array
::value('count', $opt, '');
482 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
484 if ($field->is_display_amounts
) {
485 $opt['label'] .= ' - ';
486 if (isset($taxAmount) && $invoicing) {
487 $opt['label'] = $opt['label'] . self
::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
490 $opt['label'] = $opt['label'] . CRM_Utils_Money
::format($opt[$valueFieldName]);
494 $priceVal[$opt['id']] = implode($separator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
496 if (!in_array($opt['id'], $freezeOptions)) {
497 $allowedOptions[] = $opt['id'];
499 // CRM-14696 - Improve display for sold out price set options
501 $opt['id'] = 'crm_disabled_opt-' . $opt['id'];
502 $opt['label'] = $opt['label'] . ' (' . ts('Sold out') . ')';
505 $selectOption[$opt['id']] = $opt['label'];
508 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
511 if (isset($opt['visibility_id'])) {
512 $visibility_id = $opt['visibility_id'];
515 $visibility_id = self
::getVisibilityOptionID('public');
517 $element = &$qf->add('select', $elementName, $label, $selectOption, $useRequired && $field->is_required
, [
518 'placeholder' => ts('- select %1 -', [1 => $label]),
519 'price' => json_encode($priceVal),
520 'class' => 'crm-select2',
521 'data-price-field-values' => json_encode($customOption),
524 // CRM-6902 - Add "max" option for a price set field
525 $button = substr($qf->controller
->getButtonName(), -4);
526 if (!empty($freezeOptions) && $button != 'skip') {
527 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
534 foreach ($customOption as $opId => $opt) {
535 $taxAmount = $opt['tax_amount'] ??
NULL;
536 $count = CRM_Utils_Array
::value('count', $opt, '');
537 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
539 if ($field->is_display_amounts
) {
540 $preHelpText = $postHelpText = '';
541 if (isset($opt['help_pre'])) {
542 $preHelpText = '<span class="crm-price-amount-help-pre description">' . $opt['help_pre'] . '</span>: ';
544 if (isset($opt['help_post'])) {
545 $postHelpText = ': <span class="crm-price-amount-help-post description">' . $opt['help_post'] . '</span>';
547 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span> - ';
548 if (isset($taxAmount) && $invoicing) {
549 $opt['label'] .= self
::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
552 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
554 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
556 $priceVal = implode($separator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
557 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
559 'price' => json_encode([$opt['id'], $priceVal]),
560 'data-amount' => $opt[$valueFieldName],
561 'data-currency' => $currencyName,
562 'visibility' => $opt['visibility_id'],
566 $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], ['size' => '4']);
567 $qf->addGroup($txtcheck, 'txt-' . $elementName, $label);
569 // CRM-6902 - Add "max" option for a price set field
570 if (in_array($opId, $freezeOptions)) {
571 self
::freezeIfEnabled($check[$opId], $customOption[$opId]);
572 // CRM-14696 - Improve display for sold out price set options
573 $check[$opId]->setText('<span class="sold-out-option">' . $check[$opId]->getText() . ' (' . ts('Sold out') . ')</span>');
576 $element = &$qf->addGroup($check, $elementName, $label);
577 if ($useRequired && $field->is_required
) {
578 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
582 if (isset($qf->_online
) && $qf->_online
) {
588 * Retrieve a list of options for the specified field.
590 * @param int $fieldId
592 * @param bool $inactiveNeeded
593 * Include inactive options.
595 * Discard stored values.
596 * @param bool $isDefaultContributionPriceSet
597 * Discard tax amount calculation for price set = default_contribution_amount.
602 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE, $isDefaultContributionPriceSet = FALSE) {
603 if ($reset ||
!isset(Civi
::$statics[__CLASS__
]['priceOptions'])) {
604 Civi
::$statics[__CLASS__
]['priceOptions'] = [];
605 // This would happen if the function was only called to clear the cache.
606 if (empty($fieldId)) {
611 if (empty(Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId])) {
612 $values = $options = [];
613 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
614 $options[$fieldId] = $values;
615 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
617 // ToDo - Code for Hook Invoke
619 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
620 if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates) && !$isDefaultContributionPriceSet) {
621 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
622 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
623 $options[$fieldId][$priceFieldId]['tax_amount'] = $taxAmount['tax_amount'];
626 Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId] = $options[$fieldId];
629 return Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId];
633 * @param $optionLabel
638 public static function getOptionId($optionLabel, $fid) {
639 if (!$optionLabel ||
!$fid) {
643 $optionGroupName = "civicrm_price_field.amount.{$fid}";
647 option_value.id as id
649 civicrm_option_value option_value,
650 civicrm_option_group option_group
652 option_group.name = %1
653 AND option_group.id = option_value.option_group_id
654 AND option_value.label = %2";
656 $dao = CRM_Core_DAO
::executeQuery($query, [
657 1 => [$optionGroupName, 'String'],
658 2 => [$optionLabel, 'String'],
661 while ($dao->fetch()) {
667 * Delete the price set field.
675 public static function deleteField($id) {
676 $field = new CRM_Price_DAO_PriceField();
679 if ($field->find(TRUE)) {
680 // delete the options for this field
681 CRM_Price_BAO_PriceFieldValue
::deleteValues($id);
683 // reorder the weight before delete
684 $fieldValues = ['price_set_id' => $field->price_set_id
];
686 CRM_Utils_Weight
::delWeight('CRM_Price_DAO_PriceField', $field->id
, $fieldValues);
688 // now delete the field
689 return $field->delete();
698 public static function &htmlTypes() {
699 static $htmlTypes = NULL;
702 'Text' => ts('Text / Numeric Quantity'),
703 'Select' => ts('Select'),
704 'Radio' => ts('Radio'),
705 'CheckBox' => ts('CheckBox'),
712 * Validate the priceset.
714 * @param int $priceSetId
717 * retrun the error string
721 * @param bool $allowNoneSelection
724 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
725 // check for at least one positive
726 // amount price field should be selected.
727 $priceField = new CRM_Price_DAO_PriceField();
728 $priceField->price_set_id
= $priceSetId;
733 if ($allowNoneSelection) {
734 $noneSelectedPriceFields = [];
737 while ($priceField->fetch()) {
738 $key = "price_{$priceField->id}";
740 if ($allowNoneSelection) {
741 if (array_key_exists($key, $fields)) {
742 if ($fields[$key] == 0 && !$priceField->is_required
) {
743 $noneSelectedPriceFields[] = $priceField->id
;
748 if (!empty($fields[$key])) {
749 $priceFields[$priceField->id
] = $fields[$key];
753 if (!empty($priceFields)) {
754 // we should has to have positive amount.
757 FROM civicrm_price_field
758 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
759 $fieldDAO = CRM_Core_DAO
::executeQuery($sql);
761 while ($fieldDAO->fetch()) {
762 $htmlTypes[$fieldDAO->id
] = $fieldDAO->html_type
;
765 $selectedAmounts = [];
767 foreach ($htmlTypes as $fieldId => $type) {
769 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $options);
771 if (empty($options)) {
775 if ($type == 'Text') {
776 foreach ($options as $opId => $option) {
777 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
781 elseif (is_array($fields["price_{$fieldId}"])) {
782 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
783 $selectedAmounts[$opId] = $options[$opId]['amount'];
786 elseif (array_key_exists($fields["price_{$fieldId}"], $options)) {
787 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
791 list($componentName) = explode(':', $fields['_qf_default']);
792 // now we have all selected amount in hand.
793 $totalAmount = array_sum($selectedAmounts);
794 // The form offers a field to enter the amount paid. This may differ from the amount that is due to complete the purchase
795 $totalPaymentAmountEnteredOnForm = CRM_Utils_Array
::value('total_amount', $fields);
796 if ($totalAmount < 0) {
797 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', [1 => $componentName]);
799 elseif ($totalAmount > 0 &&
800 // if total amount is equal to all selected amount in hand
801 $totalPaymentAmountEnteredOnForm >= $totalAmount &&
802 (CRM_Utils_Array
::value('contribution_status_id', $fields) == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Partially paid'))
804 $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');
808 if ($allowNoneSelection) {
809 if (empty($noneSelectedPriceFields)) {
810 $error['_qf_default'] = ts('Please select at least one option from price set.');
814 $error['_qf_default'] = ts('Please select at least one option from price set.');
820 * Generate the label for price fields based on tax display setting option on CiviContribute Component Settings page.
823 * @param string $valueFieldName
825 * @param string $displayOpt
826 * Tax display setting option.
828 * @param string $taxTerm
831 * Tax label for custom field.
833 public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm) {
834 if ($displayOpt == 'Do_not_show') {
835 $label = CRM_Utils_Money
::format($opt[$valueFieldName] +
$opt['tax_amount']);
837 elseif ($displayOpt == 'Inclusive') {
838 $label = CRM_Utils_Money
::format($opt[$valueFieldName] +
$opt['tax_amount']);
839 $label .= '<span class="crm-price-amount-tax"> ' . ts('(includes %1 of %2)', [1 => $taxTerm, 2 => CRM_Utils_Money
::format($opt['tax_amount'])]) . '</span>';
842 $label = CRM_Utils_Money
::format($opt[$valueFieldName]);
843 $label .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money
::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
850 * Given the name of a visibility option, returns its ID.
852 * @param string $visibilityName
856 public static function getVisibilityOptionID($visibilityName) {
858 if (!isset(self
::$visibilityOptionsKeys)) {
859 self
::$visibilityOptionsKeys = CRM_Core_PseudoConstant
::get('CRM_Price_BAO_PriceField', 'visibility_id', [
860 'labelColumn' => 'name',
865 if (isset(self
::$visibilityOptionsKeys[$visibilityName])) {
866 return self
::$visibilityOptionsKeys[$visibilityName];