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 * Takes an associative array and creates a price field object.
38 * the function extract all the params it needs to initialize the create a
39 * price field object. the params array could contain additional unused name/value
42 * @param array $params
43 * (reference) an assoc array of name/value pairs.
45 * @return CRM_Price_BAO_PriceField
47 public static function add(&$params) {
48 $hook = empty($params['id']) ?
'create' : 'edit';
49 CRM_Utils_Hook
::pre($hook, 'PriceField', CRM_Utils_Array
::value('id', $params), $params);
51 $priceFieldBAO = new CRM_Price_BAO_PriceField();
53 $priceFieldBAO->copyValues($params);
55 if ($id = CRM_Utils_Array
::value('id', $params)) {
56 $priceFieldBAO->id
= $id;
59 $priceFieldBAO->save();
60 CRM_Utils_Hook
::post($hook, 'PriceField', $priceFieldBAO->id
, $priceFieldBAO);
61 return $priceFieldBAO;
65 * Takes an associative array and creates a price field object.
67 * This function is invoked from within the web form layer and also from the api layer
69 * @param array $params
70 * (reference) an assoc array of name/value pairs.
72 * @return CRM_Price_DAO_PriceField
74 * @throws \CRM_Core_Exception
75 * @throws \CiviCRM_API3_Exception
77 public static function create(&$params) {
78 if (empty($params['id']) && empty($params['name'])) {
79 $params['name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 242));
81 $transaction = new CRM_Core_Transaction();
83 $priceField = self
::add($params);
85 if (is_a($priceField, 'CRM_Core_Error')) {
86 $transaction->rollback();
90 if (!empty($params['id']) && empty($priceField->html_type
)) {
91 $priceField->html_type
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $params['id'], 'html_type');
94 $maxIndex = CRM_Price_Form_Field
::NUM_OPTION
;
95 if ($priceField->html_type
== 'Text') {
97 $fieldOptions = civicrm_api3('price_field_value', 'get', [
98 'price_field_id' => $priceField->id
,
101 foreach ($fieldOptions['values'] as $option) {
102 $optionsIds['id'] = $option['id'];
103 $params['option_id'] = [1 => $option['id']];
104 // CRM-19741 If we are dealing with price fields that are Text only set the field value label to match
105 if (!empty($params['id']) && $priceField->label
!= $option['label']) {
106 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
107 $fieldValue->label
= $priceField->label
;
108 $fieldValue->id
= $option['id'];
114 //html type would be empty in update scenario not sure what would happen ...
115 if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
116 $tempArray = array_keys($params['default_checkbox_option']);
117 foreach ($tempArray as $v) {
118 if ($params['option_amount'][$v]) {
119 $defaultArray[$v] = 1;
124 if (!empty($params['default_option'])) {
125 $defaultArray[$params['default_option']] = 1;
129 for ($index = 1; $index <= $maxIndex; $index++
) {
130 if (array_key_exists('option_amount', $params) &&
131 array_key_exists($index, $params['option_amount']) &&
132 (CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_label', $params)) ||
!empty($params['is_quick_config'])) &&
133 !CRM_Utils_System
::isNull($params['option_amount'][$index])
136 'price_field_id' => $priceField->id
,
137 'label' => trim($params['option_label'][$index]),
138 'name' => CRM_Utils_String
::munge($params['option_label'][$index], '_', 64),
139 'amount' => trim($params['option_amount'][$index]),
140 'count' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_count', $params), NULL),
141 'max_value' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_max_value', $params), NULL),
142 'description' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_description', $params), NULL),
143 'membership_type_id' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_type_id', $params), NULL),
144 'weight' => $params['option_weight'][$index],
146 'is_default' => !empty($defaultArray[$params['option_weight'][$index]]) ?
$defaultArray[$params['option_weight'][$index]] : 0,
147 'membership_num_terms' => NULL,
148 'non_deductible_amount' => CRM_Utils_Array
::value('non_deductible_amount', $params),
149 'visibility_id' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_visibility_id', $params), self
::getVisibilityOptionID('public')),
152 if ($options['membership_type_id']) {
153 $options['membership_num_terms'] = CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_num_terms', $params), 1);
154 $options['is_default'] = !empty($defaultArray[$params['membership_type_id'][$index]]) ?
$defaultArray[$params['membership_type_id'][$index]] : 0;
157 if (CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_financial_type_id', $params))) {
158 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
160 elseif (!empty($params['financial_type_id'])) {
161 $options['financial_type_id'] = $params['financial_type_id'];
163 if ($opIds = CRM_Utils_Array
::value('option_id', $params)) {
164 if ($opId = CRM_Utils_Array
::value($index, $opIds)) {
165 $options['id'] = $opId;
168 $options['id'] = NULL;
172 CRM_Price_BAO_PriceFieldValue
::create($options, $optionsIds);
174 catch (Exception
$e) {
175 $transaction->rollback();
176 throw new CRM_Core_Exception($e->getMessage());
179 elseif (!empty($optionsIds) && !empty($optionsIds['id'])) {
180 $optionsLoad = civicrm_api3('price_field_value', 'get', ['id' => $optionsIds['id']]);
181 $options = $optionsLoad['values'][$optionsIds['id']];
182 $options['is_active'] = CRM_Utils_Array
::value('is_active', $params, 1);
184 CRM_Price_BAO_PriceFieldValue
::create($options, $optionsIds);
186 catch (Exception
$e) {
187 $transaction->rollback();
188 throw new CRM_Core_Exception($e->getMessage());
193 $transaction->commit();
198 * Fetch object based on array of properties.
200 * @param array $params
201 * (reference ) an assoc array of name/value pairs.
202 * @param array $defaults
203 * (reference ) an assoc array to hold the flattened values.
205 * @return CRM_Price_DAO_PriceField
207 public static function retrieve(&$params, &$defaults) {
208 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
212 * Update the is_active flag in the db.
215 * Id of the database record.
216 * @param bool $is_active
217 * Value we want to set the is_active field.
220 * true if we found and updated the object, else false
222 public static function setIsActive($id, $is_active) {
223 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
227 * Freeze form if the event is full.
230 * @param $fieldOptions
234 public static function freezeIfEnabled(&$element, $fieldOptions) {
235 if (!empty($fieldOptions['is_full'])) {
242 * Get the field title.
251 public static function getTitle($id) {
252 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
256 * This function for building custom fields.
258 * @param CRM_Core_Form $qf
259 * Form object (reference).
260 * @param string $elementName
261 * Name of the custom field.
262 * @param int $fieldId
263 * @param bool $inactiveNeeded
264 * @param bool $useRequired
265 * True if required else false.
266 * @param string $label
267 * Label for custom field.
269 * @param null $fieldOptions
270 * @param array $freezeOptions
274 public static function addQuickFormElement(
281 $fieldOptions = NULL,
285 $field = new CRM_Price_DAO_PriceField();
286 $field->id
= $fieldId;
287 if (!$field->find(TRUE)) {
288 /* FIXME: failure! */
293 if (isset($qf->_mode
) && empty($qf->_mode
)) {
296 elseif (isset($qf->_values
)) {
297 $is_pay_later = CRM_Utils_Array
::value('is_pay_later', $qf->_values
);
300 $otherAmount = $qf->get('values');
301 $config = CRM_Core_Config
::singleton();
302 $currencySymbol = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_Currency', $config->defaultCurrency
, 'symbol', 'name');
303 $qf->assign('currencySymbol', $currencySymbol);
304 // get currency name for price field and option attributes
305 $currencyName = $config->defaultCurrency
;
307 if (!isset($label)) {
308 $label = (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') ?
ts('Additional Contribution') : $field->label
;
311 if ($field->name
== 'contribution_amount') {
312 $qf->_contributionAmount
= 1;
315 if (isset($qf->_online
) && $qf->_online
) {
316 $useRequired = FALSE;
319 $customOption = $fieldOptions;
320 if (!is_array($customOption)) {
321 $customOption = CRM_Price_BAO_PriceField
::getOptions($field->id
, $inactiveNeeded);
325 $valueFieldName = 'amount';
327 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
328 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
329 $displayOpt = CRM_Utils_Array
::value('tax_display_settings', $invoiceSettings);
330 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
331 switch ($field->html_type
) {
333 $optionKey = key($customOption);
334 $count = CRM_Utils_Array
::value('count', $customOption[$optionKey], '');
335 $max_value = CRM_Utils_Array
::value('max_value', $customOption[$optionKey], '');
336 $taxAmount = CRM_Utils_Array
::value('tax_amount', $customOption[$optionKey]);
337 if (isset($taxAmount) && $displayOpt && $invoicing) {
338 $qf->assign('displayOpt', $displayOpt);
339 $qf->assign('taxTerm', $taxTerm);
340 $qf->assign('invoicing', $invoicing);
342 $priceVal = implode($seperator, [
343 $customOption[$optionKey][$valueFieldName] +
$taxAmount,
349 if (!empty($qf->_membershipBlock
) && !empty($qf->_quickConfig
) && $field->name
== 'other_amount' && empty($qf->_contributionAmount
)) {
352 elseif (!empty($fieldOptions[$optionKey]['label'])) {
354 $label = $fieldOptions[$optionKey]['label'];
355 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
) && strtolower($fieldOptions[$optionKey]['name']) == 'other_amount') {
356 $label .= ' ' . $currencySymbol;
357 $qf->assign('priceset', $elementName);
358 $extra = ['onclick' => 'useAmountOther();'];
362 $element = &$qf->add('text', $elementName, $label,
365 'price' => json_encode([$optionKey, $priceVal]),
369 $useRequired && $field->is_required
372 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
375 // CRM-6902 - Add "max" option for a price set field
376 if (in_array($optionKey, $freezeOptions)) {
377 self
::freezeIfEnabled($element, $fieldOptions[$optionKey]);
378 // CRM-14696 - Improve display for sold out price set options
379 $element->setLabel($label . ' <span class="sold-out-option">' . ts('Sold out') . '</span>');
383 if (!empty($qf->_quickConfig
)) {
384 $message = ts('Please enter a valid amount.');
388 $message = ts('%1 must be a number (with or without decimal point).', [1 => $label]);
391 // integers will have numeric rule applied to them.
392 $qf->addRule($elementName, $message, $type);
398 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
)) {
399 $qf->assign('contriPriceset', $elementName);
402 foreach ($customOption as $opId => $opt) {
403 $taxAmount = CRM_Utils_Array
::value('tax_amount', $opt);
404 if ($field->is_display_amounts
) {
405 $opt['label'] = !empty($opt['label']) ?
$opt['label'] . '<span class="crm-price-amount-label-separator"> - </span>' : '';
406 $preHelpText = $postHelpText = '';
407 if (!empty($opt['help_pre'])) {
408 $preHelpText = '<span class="crm-price-amount-help-pre description">' . $opt['help_pre'] . '</span>: ';
410 if (!empty($opt['help_post'])) {
411 $postHelpText = ': <span class="crm-price-amount-help-post description">' . $opt['help_post'] . '</span>';
413 if (isset($taxAmount) && $invoicing) {
414 if ($displayOpt == 'Do_not_show') {
415 $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>';
417 elseif ($displayOpt == 'Inclusive') {
418 $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>';
419 $opt['label'] .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money
::format($opt['tax_amount']) . ')</span>';
422 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName]) . '</span>';
423 $opt['label'] .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money
::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
427 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName]) . '</span>';
429 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
431 $count = CRM_Utils_Array
::value('count', $opt, '');
432 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
433 $priceVal = implode($seperator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
434 if (isset($opt['visibility_id'])) {
435 $visibility_id = $opt['visibility_id'];
438 $visibility_id = self
::getVisibilityOptionID('public');
441 'price' => json_encode([$elementName, $priceVal]),
442 'data-amount' => $opt[$valueFieldName],
443 'data-currency' => $currencyName,
444 'data-price-field-values' => json_encode($customOption),
445 'visibility' => $visibility_id,
447 if (!empty($qf->_quickConfig
) && $field->name
== 'contribution_amount') {
448 $extra +
= ['onclick' => 'clearAmountOther();'];
450 if ($field->name
== 'membership_amount') {
452 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
453 'membership-type' => $opt['membership_type_id'],
455 $qf->assign('membershipFieldID', $field->id
);
458 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
460 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
463 // CRM-6902 - Add "max" option for a price set field
464 if (in_array($opId, $freezeOptions)) {
465 self
::freezeIfEnabled($choice[$opId], $customOption[$opId]);
466 // CRM-14696 - Improve display for sold out price set options
467 $choice[$opId]->setText('<span class="sold-out-option">' . $choice[$opId]->getText() . ' (' . ts('Sold out') . ')</span>');
470 if (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') {
471 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
473 'price' => json_encode([$elementName, '0|0']),
474 'data-currency' => $currencyName,
475 'onclick' => 'clearAmountOther();',
480 if (!$field->is_required
) {
482 if (!empty($otherAmount['is_allow_other_amount']) && $field->name
== 'contribution_amount') {
483 $none = ts('Other Amount');
485 elseif (!empty($qf->_membershipBlock
) && empty($qf->_membershipBlock
['is_required']) && $field->name
== 'membership_amount') {
486 $none = ts('No thank you');
489 $none = ts('- none -');
492 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
493 ['price' => json_encode([$elementName, '0'])]
497 $element = &$qf->addGroup($choice, $elementName, $label);
499 // make contribution field required for quick config when membership block is enabled
500 if (($field->name
== 'membership_amount' ||
$field->name
== 'contribution_amount')
501 && !empty($qf->_membershipBlock
) && !$field->is_required
503 $useRequired = $field->is_required
= TRUE;
506 if ($useRequired && $field->is_required
) {
507 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
512 $selectOption = $allowedOptions = $priceVal = [];
514 foreach ($customOption as $opt) {
515 $taxAmount = CRM_Utils_Array
::value('tax_amount', $opt);
516 $count = CRM_Utils_Array
::value('count', $opt, '');
517 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
519 if ($field->is_display_amounts
) {
520 $opt['label'] .= ' - ';
521 if (isset($taxAmount) && $invoicing) {
522 $opt['label'] = $opt['label'] . self
::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
525 $opt['label'] = $opt['label'] . CRM_Utils_Money
::format($opt[$valueFieldName]);
529 $priceVal[$opt['id']] = implode($seperator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
531 if (!in_array($opt['id'], $freezeOptions)) {
532 $allowedOptions[] = $opt['id'];
534 // CRM-14696 - Improve display for sold out price set options
536 $opt['id'] = 'crm_disabled_opt-' . $opt['id'];
537 $opt['label'] = $opt['label'] . ' (' . ts('Sold out') . ')';
540 $selectOption[$opt['id']] = $opt['label'];
543 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
546 if (isset($opt['visibility_id'])) {
547 $visibility_id = $opt['visibility_id'];
550 $visibility_id = self
::getVisibilityOptionID('public');
552 $element = &$qf->add('select', $elementName, $label,
554 '' => ts('- select -'),
556 $useRequired && $field->is_required
,
557 ['price' => json_encode($priceVal), 'class' => 'crm-select2', 'data-price-field-values' => json_encode($customOption)]
560 // CRM-6902 - Add "max" option for a price set field
561 $button = substr($qf->controller
->getButtonName(), -4);
562 if (!empty($freezeOptions) && $button != 'skip') {
563 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
570 foreach ($customOption as $opId => $opt) {
571 $taxAmount = CRM_Utils_Array
::value('tax_amount', $opt);
572 $count = CRM_Utils_Array
::value('count', $opt, '');
573 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
575 if ($field->is_display_amounts
) {
576 $preHelpText = $postHelpText = '';
577 if (isset($opt['help_pre'])) {
578 $preHelpText = '<span class="crm-price-amount-help-pre description">' . $opt['help_pre'] . '</span>: ';
580 if (isset($opt['help_post'])) {
581 $postHelpText = ': <span class="crm-price-amount-help-post description">' . $opt['help_post'] . '</span>';
583 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span> - ';
584 if (isset($taxAmount) && $invoicing) {
585 $opt['label'] .= self
::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
588 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
590 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
592 $priceVal = implode($seperator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
593 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
595 'price' => json_encode([$opt['id'], $priceVal]),
596 'data-amount' => $opt[$valueFieldName],
597 'data-currency' => $currencyName,
598 'visibility' => $opt['visibility_id'],
602 $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], ['size' => '4']);
603 $qf->addGroup($txtcheck, 'txt-' . $elementName, $label);
605 // CRM-6902 - Add "max" option for a price set field
606 if (in_array($opId, $freezeOptions)) {
607 self
::freezeIfEnabled($check[$opId], $customOption[$opId]);
608 // CRM-14696 - Improve display for sold out price set options
609 $check[$opId]->setText('<span class="sold-out-option">' . $check[$opId]->getText() . ' (' . ts('Sold out') . ')</span>');
612 $element = &$qf->addGroup($check, $elementName, $label);
613 if ($useRequired && $field->is_required
) {
614 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
618 if (isset($qf->_online
) && $qf->_online
) {
624 * Retrieve a list of options for the specified field.
626 * @param int $fieldId
628 * @param bool $inactiveNeeded
629 * Include inactive options.
631 * Discard stored values.
632 * @param bool $isDefaultContributionPriceSet
633 * Discard tax amount calculation for price set = default_contribution_amount.
638 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE, $isDefaultContributionPriceSet = FALSE) {
639 if ($reset ||
!isset(Civi
::$statics[__CLASS__
]['priceOptions'])) {
640 Civi
::$statics[__CLASS__
]['priceOptions'] = [];
641 // This would happen if the function was only called to clear the cache.
642 if (empty($fieldId)) {
647 if (empty(Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId])) {
648 $values = $options = [];
649 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
650 $options[$fieldId] = $values;
651 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
653 // ToDo - Code for Hook Invoke
655 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
656 if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates) && !$isDefaultContributionPriceSet) {
657 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
658 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
659 $options[$fieldId][$priceFieldId]['tax_amount'] = $taxAmount['tax_amount'];
662 Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId] = $options[$fieldId];
665 return Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId];
669 * @param $optionLabel
674 public static function getOptionId($optionLabel, $fid) {
675 if (!$optionLabel ||
!$fid) {
679 $optionGroupName = "civicrm_price_field.amount.{$fid}";
683 option_value.id as id
685 civicrm_option_value option_value,
686 civicrm_option_group option_group
688 option_group.name = %1
689 AND option_group.id = option_value.option_group_id
690 AND option_value.label = %2";
692 $dao = CRM_Core_DAO
::executeQuery($query, [
693 1 => [$optionGroupName, 'String'],
694 2 => [$optionLabel, 'String'],
697 while ($dao->fetch()) {
703 * Delete the price set field.
711 public static function deleteField($id) {
712 $field = new CRM_Price_DAO_PriceField();
715 if ($field->find(TRUE)) {
716 // delete the options for this field
717 CRM_Price_BAO_PriceFieldValue
::deleteValues($id);
719 // reorder the weight before delete
720 $fieldValues = ['price_set_id' => $field->price_set_id
];
722 CRM_Utils_Weight
::delWeight('CRM_Price_DAO_PriceField', $field->id
, $fieldValues);
724 // now delete the field
725 return $field->delete();
734 public static function &htmlTypes() {
735 static $htmlTypes = NULL;
738 'Text' => ts('Text / Numeric Quantity'),
739 'Select' => ts('Select'),
740 'Radio' => ts('Radio'),
741 'CheckBox' => ts('CheckBox'),
748 * Validate the priceset.
750 * @param int $priceSetId
753 * retrun the error string
757 * @param bool $allowNoneSelection
760 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
761 // check for at least one positive
762 // amount price field should be selected.
763 $priceField = new CRM_Price_DAO_PriceField();
764 $priceField->price_set_id
= $priceSetId;
769 if ($allowNoneSelection) {
770 $noneSelectedPriceFields = [];
773 while ($priceField->fetch()) {
774 $key = "price_{$priceField->id}";
776 if ($allowNoneSelection) {
777 if (array_key_exists($key, $fields)) {
778 if ($fields[$key] == 0 && !$priceField->is_required
) {
779 $noneSelectedPriceFields[] = $priceField->id
;
784 if (!empty($fields[$key])) {
785 $priceFields[$priceField->id
] = $fields[$key];
789 if (!empty($priceFields)) {
790 // we should has to have positive amount.
793 FROM civicrm_price_field
794 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
795 $fieldDAO = CRM_Core_DAO
::executeQuery($sql);
797 while ($fieldDAO->fetch()) {
798 $htmlTypes[$fieldDAO->id
] = $fieldDAO->html_type
;
801 $selectedAmounts = [];
803 foreach ($htmlTypes as $fieldId => $type) {
805 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $options);
807 if (empty($options)) {
811 if ($type == 'Text') {
812 foreach ($options as $opId => $option) {
813 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
817 elseif (is_array($fields["price_{$fieldId}"])) {
818 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
819 $selectedAmounts[$opId] = $options[$opId]['amount'];
822 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
823 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
827 list($componentName) = explode(':', $fields['_qf_default']);
828 // now we have all selected amount in hand.
829 $totalAmount = array_sum($selectedAmounts);
830 // The form offers a field to enter the amount paid. This may differ from the amount that is due to complete the purchase
831 $totalPaymentAmountEnteredOnForm = CRM_Utils_Array
::value('partial_payment_total', $fields, CRM_Utils_Array
::value('total_amount', $fields));
832 if ($totalAmount < 0) {
833 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', [1 => $componentName]);
835 elseif ($totalAmount > 0 &&
836 // if total amount is equal to all selected amount in hand
837 $totalPaymentAmountEnteredOnForm >= $totalAmount &&
838 (CRM_Utils_Array
::value('contribution_status_id', $fields) == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Partially paid'))
840 $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');
844 if ($allowNoneSelection) {
845 if (empty($noneSelectedPriceFields)) {
846 $error['_qf_default'] = ts('Please select at least one option from price set.');
850 $error['_qf_default'] = ts('Please select at least one option from price set.');
856 * Generate the label for price fields based on tax display setting option on CiviContribute Component Settings page.
859 * @param string $valueFieldName
861 * @param string $displayOpt
862 * Tax display setting option.
864 * @param string $taxTerm
867 * Tax label for custom field.
869 public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm) {
870 if ($displayOpt == 'Do_not_show') {
871 $label = CRM_Utils_Money
::format($opt[$valueFieldName] +
$opt['tax_amount']);
873 elseif ($displayOpt == 'Inclusive') {
874 $label = CRM_Utils_Money
::format($opt[$valueFieldName] +
$opt['tax_amount']);
875 $label .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money
::format($opt['tax_amount']) . ')</span>';
878 $label = CRM_Utils_Money
::format($opt[$valueFieldName]);
879 $label .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money
::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
886 * Given the name of a visibility option, returns its ID.
888 * @param string $visibilityName
892 public static function getVisibilityOptionID($visibilityName) {
894 if (!isset(self
::$visibilityOptionsKeys)) {
895 self
::$visibilityOptionsKeys = CRM_Price_BAO_PriceField
::buildOptions(
899 'labelColumn' => 'name',
905 if (isset(self
::$visibilityOptionsKeys[$visibilityName])) {
906 return self
::$visibilityOptionsKeys[$visibilityName];