3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
37 * Business objects for managing price fields.
40 class CRM_Price_BAO_PriceField
extends CRM_Price_DAO_PriceField
{
45 * List of visibility option ID's, of the form name => ID
49 private static $visibilityOptionsKeys;
52 * Takes an associative array and creates a price field object.
54 * the function extract all the params it needs to initialize the create a
55 * price field object. the params array could contain additional unused name/value
58 * @param array $params
59 * (reference) an assoc array of name/value pairs.
61 * @return CRM_Price_BAO_PriceField
63 public static function add(&$params) {
64 $priceFieldBAO = new CRM_Price_BAO_PriceField();
66 $priceFieldBAO->copyValues($params);
68 if ($id = CRM_Utils_Array
::value('id', $params)) {
69 $priceFieldBAO->id
= $id;
72 $priceFieldBAO->save();
73 return $priceFieldBAO;
77 * Takes an associative array and creates a price field object.
79 * This function is invoked from within the web form layer and also from the api layer
81 * @param array $params
82 * (reference) an assoc array of name/value pairs.
84 * @return CRM_Price_DAO_PriceField
86 * @throws \CRM_Core_Exception
87 * @throws \CiviCRM_API3_Exception
89 public static function create(&$params) {
90 if (empty($params['id']) && empty($params['name'])) {
91 $params['name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 242));
93 $transaction = new CRM_Core_Transaction();
95 $priceField = self
::add($params);
97 if (is_a($priceField, 'CRM_Core_Error')) {
98 $transaction->rollback();
102 if (!empty($params['id']) && empty($priceField->html_type
)) {
103 $priceField->html_type
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $params['id'], 'html_type');
106 $maxIndex = CRM_Price_Form_Field
::NUM_OPTION
;
107 if ($priceField->html_type
== 'Text') {
109 $fieldOptions = civicrm_api3('price_field_value', 'get', [
110 'price_field_id' => $priceField->id
,
113 foreach ($fieldOptions['values'] as $option) {
114 $optionsIds['id'] = $option['id'];
115 // CRM-19741 If we are dealing with price fields that are Text only set the field value label to match
116 if (!empty($params['id']) && $priceField->label
!= $option['label']) {
117 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
118 $fieldValue->label
= $priceField->label
;
119 $fieldValue->id
= $option['id'];
125 //html type would be empty in update scenario not sure what would happen ...
126 if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
127 $tempArray = array_keys($params['default_checkbox_option']);
128 foreach ($tempArray as $v) {
129 if ($params['option_amount'][$v]) {
130 $defaultArray[$v] = 1;
135 if (!empty($params['default_option'])) {
136 $defaultArray[$params['default_option']] = 1;
140 for ($index = 1; $index <= $maxIndex; $index++
) {
141 if (array_key_exists('option_amount', $params) &&
142 array_key_exists($index, $params['option_amount']) &&
143 (CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_label', $params)) ||
!empty($params['is_quick_config'])) &&
144 !CRM_Utils_System
::isNull($params['option_amount'][$index])
147 'price_field_id' => $priceField->id
,
148 'label' => trim($params['option_label'][$index]),
149 'name' => CRM_Utils_String
::munge($params['option_label'][$index], '_', 64),
150 'amount' => trim($params['option_amount'][$index]),
151 'count' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_count', $params), NULL),
152 'max_value' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_max_value', $params), NULL),
153 'description' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_description', $params), NULL),
154 'membership_type_id' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_type_id', $params), NULL),
155 'weight' => $params['option_weight'][$index],
157 'is_default' => CRM_Utils_Array
::value($params['option_weight'][$index], $defaultArray) ?
$defaultArray[$params['option_weight'][$index]] : 0,
158 'membership_num_terms' => NULL,
159 'non_deductible_amount' => CRM_Utils_Array
::value('non_deductible_amount', $params),
160 'visibility_id' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_visibility_id', $params), self
::getVisibilityOptionID('public')),
163 if ($options['membership_type_id']) {
164 $options['membership_num_terms'] = CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_num_terms', $params), 1);
165 $options['is_default'] = CRM_Utils_Array
::value($params['membership_type_id'][$index], $defaultArray) ?
$defaultArray[$params['membership_type_id'][$index]] : 0;
168 if (CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_financial_type_id', $params))) {
169 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
171 elseif (!empty($params['financial_type_id'])) {
172 $options['financial_type_id'] = $params['financial_type_id'];
174 if ($opIds = CRM_Utils_Array
::value('option_id', $params)) {
175 if ($opId = CRM_Utils_Array
::value($index, $opIds)) {
176 $optionsIds['id'] = $opId;
179 $optionsIds['id'] = NULL;
183 CRM_Price_BAO_PriceFieldValue
::create($options, $optionsIds);
185 catch (Exception
$e) {
186 $transaction->rollback();
187 throw new CRM_Core_Exception($e->getMessage());
190 elseif (!empty($optionsIds) && !empty($optionsIds['id'])) {
191 $optionsLoad = civicrm_api3('price_field_value', 'get', ['id' => $optionsIds['id']]);
192 $options = $optionsLoad['values'][$optionsIds['id']];
193 $options['is_active'] = CRM_Utils_Array
::value('is_active', $params, 1);
195 CRM_Price_BAO_PriceFieldValue
::create($options, $optionsIds);
197 catch (Exception
$e) {
198 $transaction->rollback();
199 throw new CRM_Core_Exception($e->getMessage());
204 $transaction->commit();
209 * Fetch object based on array of properties.
211 * @param array $params
212 * (reference ) an assoc array of name/value pairs.
213 * @param array $defaults
214 * (reference ) an assoc array to hold the flattened values.
216 * @return CRM_Price_DAO_PriceField
218 public static function retrieve(&$params, &$defaults) {
219 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
223 * Update the is_active flag in the db.
226 * Id of the database record.
227 * @param bool $is_active
228 * Value we want to set the is_active field.
231 * true if we found and updated the object, else false
233 public static function setIsActive($id, $is_active) {
234 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
238 * Freeze form if the event is full.
241 * @param $fieldOptions
245 public static function freezeIfEnabled(&$element, $fieldOptions) {
246 if (!empty($fieldOptions['is_full'])) {
253 * Get the field title.
262 public static function getTitle($id) {
263 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
267 * This function for building custom fields.
269 * @param CRM_Core_Form $qf
270 * Form object (reference).
271 * @param string $elementName
272 * Name of the custom field.
273 * @param int $fieldId
274 * @param bool $inactiveNeeded
275 * @param bool $useRequired
276 * True if required else false.
277 * @param string $label
278 * Label for custom field.
280 * @param null $fieldOptions
281 * @param array $freezeOptions
285 public static function addQuickFormElement(
292 $fieldOptions = NULL,
296 $field = new CRM_Price_DAO_PriceField();
297 $field->id
= $fieldId;
298 if (!$field->find(TRUE)) {
299 /* FIXME: failure! */
304 if (isset($qf->_mode
) && empty($qf->_mode
)) {
307 elseif (isset($qf->_values
)) {
308 $is_pay_later = CRM_Utils_Array
::value('is_pay_later', $qf->_values
);
311 $otherAmount = $qf->get('values');
312 $config = CRM_Core_Config
::singleton();
313 $currencySymbol = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_Currency', $config->defaultCurrency
, 'symbol', 'name');
314 $qf->assign('currencySymbol', $currencySymbol);
315 // get currency name for price field and option attributes
316 $currencyName = $config->defaultCurrency
;
318 if (!isset($label)) {
319 $label = (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') ?
ts('Additional Contribution') : $field->label
;
322 if ($field->name
== 'contribution_amount') {
323 $qf->_contributionAmount
= 1;
326 if (isset($qf->_online
) && $qf->_online
) {
327 $useRequired = FALSE;
330 $customOption = $fieldOptions;
331 if (!is_array($customOption)) {
332 $customOption = CRM_Price_BAO_PriceField
::getOptions($field->id
, $inactiveNeeded);
336 $valueFieldName = 'amount';
338 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
339 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
340 $displayOpt = CRM_Utils_Array
::value('tax_display_settings', $invoiceSettings);
341 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
342 switch ($field->html_type
) {
344 $optionKey = key($customOption);
345 $count = CRM_Utils_Array
::value('count', $customOption[$optionKey], '');
346 $max_value = CRM_Utils_Array
::value('max_value', $customOption[$optionKey], '');
347 $taxAmount = CRM_Utils_Array
::value('tax_amount', $customOption[$optionKey]);
348 if (isset($taxAmount) && $displayOpt && $invoicing) {
349 $qf->assign('displayOpt', $displayOpt);
350 $qf->assign('taxTerm', $taxTerm);
351 $qf->assign('invoicing', $invoicing);
353 $priceVal = implode($seperator, [
354 $customOption[$optionKey][$valueFieldName] +
$taxAmount,
360 if (!empty($qf->_membershipBlock
) && !empty($qf->_quickConfig
) && $field->name
== 'other_amount' && empty($qf->_contributionAmount
)) {
363 elseif (!empty($fieldOptions[$optionKey]['label'])) {
365 $label = $fieldOptions[$optionKey]['label'];
366 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
) && strtolower($fieldOptions[$optionKey]['name']) == 'other_amount') {
367 $label .= ' ' . $currencySymbol;
368 $qf->assign('priceset', $elementName);
369 $extra = ['onclick' => 'useAmountOther();'];
373 $element = &$qf->add('text', $elementName, $label,
376 'price' => json_encode([$optionKey, $priceVal]),
380 $useRequired && $field->is_required
383 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
386 // CRM-6902 - Add "max" option for a price set field
387 if (in_array($optionKey, $freezeOptions)) {
388 self
::freezeIfEnabled($element, $fieldOptions[$optionKey]);
389 // CRM-14696 - Improve display for sold out price set options
390 $element->setLabel($label . ' <span class="sold-out-option">' . ts('Sold out') . '</span>');
394 if (!empty($qf->_quickConfig
)) {
395 $message = ts('Please enter a valid amount.');
399 $message = ts('%1 must be a number (with or without decimal point).', [1 => $label]);
402 // integers will have numeric rule applied to them.
403 $qf->addRule($elementName, $message, $type);
409 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
)) {
410 $qf->assign('contriPriceset', $elementName);
413 foreach ($customOption as $opId => $opt) {
414 $taxAmount = CRM_Utils_Array
::value('tax_amount', $opt);
415 if ($field->is_display_amounts
) {
416 $opt['label'] = !empty($opt['label']) ?
$opt['label'] . '<span class="crm-price-amount-label-separator"> - </span>' : '';
417 $preHelpText = $postHelpText = '';
418 if (!empty($opt['help_pre'])) {
419 $preHelpText = '<span class="crm-price-amount-help-pre description">' . $opt['help_pre'] . '</span>: ';
421 if (!empty($opt['help_post'])) {
422 $postHelpText = ': <span class="crm-price-amount-help-post description">' . $opt['help_post'] . '</span>';
424 if (isset($taxAmount) && $invoicing) {
425 if ($displayOpt == 'Do_not_show') {
426 $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>';
428 elseif ($displayOpt == 'Inclusive') {
429 $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>';
430 $opt['label'] .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money
::format($opt['tax_amount']) . ')</span>';
433 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName]) . '</span>';
434 $opt['label'] .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money
::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
438 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName]) . '</span>';
440 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
442 $count = CRM_Utils_Array
::value('count', $opt, '');
443 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
444 $priceVal = implode($seperator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
445 if (isset($opt['visibility_id'])) {
446 $visibility_id = $opt['visibility_id'];
449 $visibility_id = self
::getVisibilityOptionID('public');
452 'price' => json_encode([$elementName, $priceVal]),
453 'data-amount' => $opt[$valueFieldName],
454 'data-currency' => $currencyName,
455 'data-price-field-values' => json_encode($customOption),
456 'visibility' => $visibility_id,
458 if (!empty($qf->_quickConfig
) && $field->name
== 'contribution_amount') {
459 $extra +
= ['onclick' => 'clearAmountOther();'];
461 if ($field->name
== 'membership_amount') {
463 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
464 'membership-type' => $opt['membership_type_id'],
466 $qf->assign('membershipFieldID', $field->id
);
469 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
471 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
474 // CRM-6902 - Add "max" option for a price set field
475 if (in_array($opId, $freezeOptions)) {
476 self
::freezeIfEnabled($choice[$opId], $customOption[$opId]);
477 // CRM-14696 - Improve display for sold out price set options
478 $choice[$opId]->setText('<span class="sold-out-option">' . $choice[$opId]->getText() . ' (' . ts('Sold out') . ')</span>');
481 if (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') {
482 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
484 'price' => json_encode([$elementName, '0|0']),
485 'data-currency' => $currencyName,
486 'onclick' => 'clearAmountOther();',
491 if (!$field->is_required
) {
493 if (!empty($otherAmount['is_allow_other_amount']) && $field->name
== 'contribution_amount') {
494 $none = ts('Other Amount');
496 elseif (!empty($qf->_membershipBlock
) && empty($qf->_membershipBlock
['is_required']) && $field->name
== 'membership_amount') {
497 $none = ts('No thank you');
500 $none = ts('- none -');
503 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
504 ['price' => json_encode([$elementName, '0'])]
508 $element = &$qf->addGroup($choice, $elementName, $label);
510 // make contribution field required for quick config when membership block is enabled
511 if (($field->name
== 'membership_amount' ||
$field->name
== 'contribution_amount')
512 && !empty($qf->_membershipBlock
) && !$field->is_required
514 $useRequired = $field->is_required
= TRUE;
517 if ($useRequired && $field->is_required
) {
518 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
523 $selectOption = $allowedOptions = $priceVal = [];
525 foreach ($customOption as $opt) {
526 $taxAmount = CRM_Utils_Array
::value('tax_amount', $opt);
527 $count = CRM_Utils_Array
::value('count', $opt, '');
528 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
530 if ($field->is_display_amounts
) {
531 $opt['label'] .= ' - ';
532 if (isset($taxAmount) && $invoicing) {
533 $opt['label'] = $opt['label'] . self
::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
536 $opt['label'] = $opt['label'] . CRM_Utils_Money
::format($opt[$valueFieldName]);
540 $priceVal[$opt['id']] = implode($seperator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
542 if (!in_array($opt['id'], $freezeOptions)) {
543 $allowedOptions[] = $opt['id'];
545 // CRM-14696 - Improve display for sold out price set options
547 $opt['id'] = 'crm_disabled_opt-' . $opt['id'];
548 $opt['label'] = $opt['label'] . ' (' . ts('Sold out') . ')';
551 $selectOption[$opt['id']] = $opt['label'];
554 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
557 if (isset($opt['visibility_id'])) {
558 $visibility_id = $opt['visibility_id'];
561 $visibility_id = self
::getVisibilityOptionID('public');
563 $element = &$qf->add('select', $elementName, $label,
565 '' => ts('- select -'),
567 $useRequired && $field->is_required
,
568 ['price' => json_encode($priceVal), 'class' => 'crm-select2', 'data-price-field-values' => json_encode($customOption)]
571 // CRM-6902 - Add "max" option for a price set field
572 $button = substr($qf->controller
->getButtonName(), -4);
573 if (!empty($freezeOptions) && $button != 'skip') {
574 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
581 foreach ($customOption as $opId => $opt) {
582 $taxAmount = CRM_Utils_Array
::value('tax_amount', $opt);
583 $count = CRM_Utils_Array
::value('count', $opt, '');
584 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
586 if ($field->is_display_amounts
) {
587 $preHelpText = $postHelpText = '';
588 if (isset($opt['help_pre'])) {
589 $preHelpText = '<span class="crm-price-amount-help-pre description">' . $opt['help_pre'] . '</span>: ';
591 if (isset($opt['help_post'])) {
592 $postHelpText = ': <span class="crm-price-amount-help-post description">' . $opt['help_post'] . '</span>';
594 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span> - ';
595 if (isset($taxAmount) && $invoicing) {
596 $opt['label'] .= self
::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
599 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
601 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
603 $priceVal = implode($seperator, [$opt[$valueFieldName] +
$taxAmount, $count, $max_value]);
604 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
606 'price' => json_encode([$opt['id'], $priceVal]),
607 'data-amount' => $opt[$valueFieldName],
608 'data-currency' => $currencyName,
609 'visibility' => $opt['visibility_id'],
613 $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], ['size' => '4']);
614 $qf->addGroup($txtcheck, 'txt-' . $elementName, $label);
616 // CRM-6902 - Add "max" option for a price set field
617 if (in_array($opId, $freezeOptions)) {
618 self
::freezeIfEnabled($check[$opId], $customOption[$opId]);
619 // CRM-14696 - Improve display for sold out price set options
620 $check[$opId]->setText('<span class="sold-out-option">' . $check[$opId]->getText() . ' (' . ts('Sold out') . ')</span>');
623 $element = &$qf->addGroup($check, $elementName, $label);
624 if ($useRequired && $field->is_required
) {
625 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
629 if (isset($qf->_online
) && $qf->_online
) {
635 * Retrieve a list of options for the specified field.
637 * @param int $fieldId
639 * @param bool $inactiveNeeded
640 * Include inactive options.
642 * Discard stored values.
643 * @param bool $isDefaultContributionPriceSet
644 * Discard tax amount calculation for price set = default_contribution_amount.
649 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE, $isDefaultContributionPriceSet = FALSE) {
650 if ($reset ||
!isset(Civi
::$statics[__CLASS__
]['priceOptions'])) {
651 Civi
::$statics[__CLASS__
]['priceOptions'] = [];
652 // This would happen if the function was only called to clear the cache.
653 if (empty($fieldId)) {
658 if (empty(Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId])) {
659 $values = $options = [];
660 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
661 $options[$fieldId] = $values;
662 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
664 // ToDo - Code for Hook Invoke
666 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
667 if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates) && !$isDefaultContributionPriceSet) {
668 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
669 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
670 $options[$fieldId][$priceFieldId]['tax_amount'] = $taxAmount['tax_amount'];
673 Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId] = $options[$fieldId];
676 return Civi
::$statics[__CLASS__
]['priceOptions'][$fieldId];
680 * @param $optionLabel
685 public static function getOptionId($optionLabel, $fid) {
686 if (!$optionLabel ||
!$fid) {
690 $optionGroupName = "civicrm_price_field.amount.{$fid}";
694 option_value.id as id
696 civicrm_option_value option_value,
697 civicrm_option_group option_group
699 option_group.name = %1
700 AND option_group.id = option_value.option_group_id
701 AND option_value.label = %2";
703 $dao = CRM_Core_DAO
::executeQuery($query, [
704 1 => [$optionGroupName, 'String'],
705 2 => [$optionLabel, 'String'],
708 while ($dao->fetch()) {
714 * Delete the price set field.
722 public static function deleteField($id) {
723 $field = new CRM_Price_DAO_PriceField();
726 if ($field->find(TRUE)) {
727 // delete the options for this field
728 CRM_Price_BAO_PriceFieldValue
::deleteValues($id);
730 // reorder the weight before delete
731 $fieldValues = ['price_set_id' => $field->price_set_id
];
733 CRM_Utils_Weight
::delWeight('CRM_Price_DAO_PriceField', $field->id
, $fieldValues);
735 // now delete the field
736 return $field->delete();
745 public static function &htmlTypes() {
746 static $htmlTypes = NULL;
749 'Text' => ts('Text / Numeric Quantity'),
750 'Select' => ts('Select'),
751 'Radio' => ts('Radio'),
752 'CheckBox' => ts('CheckBox'),
759 * Validate the priceset.
761 * @param int $priceSetId
764 * retrun the error string
768 * @param bool $allowNoneSelection
771 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
772 // check for at least one positive
773 // amount price field should be selected.
774 $priceField = new CRM_Price_DAO_PriceField();
775 $priceField->price_set_id
= $priceSetId;
780 if ($allowNoneSelection) {
781 $noneSelectedPriceFields = [];
784 while ($priceField->fetch()) {
785 $key = "price_{$priceField->id}";
787 if ($allowNoneSelection) {
788 if (array_key_exists($key, $fields)) {
789 if ($fields[$key] == 0 && !$priceField->is_required
) {
790 $noneSelectedPriceFields[] = $priceField->id
;
795 if (!empty($fields[$key])) {
796 $priceFields[$priceField->id
] = $fields[$key];
800 if (!empty($priceFields)) {
801 // we should has to have positive amount.
804 FROM civicrm_price_field
805 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
806 $fieldDAO = CRM_Core_DAO
::executeQuery($sql);
808 while ($fieldDAO->fetch()) {
809 $htmlTypes[$fieldDAO->id
] = $fieldDAO->html_type
;
812 $selectedAmounts = [];
814 foreach ($htmlTypes as $fieldId => $type) {
816 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $options);
818 if (empty($options)) {
822 if ($type == 'Text') {
823 foreach ($options as $opId => $option) {
824 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
828 elseif (is_array($fields["price_{$fieldId}"])) {
829 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
830 $selectedAmounts[$opId] = $options[$opId]['amount'];
833 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
834 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
838 list($componentName) = explode(':', $fields['_qf_default']);
839 // now we have all selected amount in hand.
840 $totalAmount = array_sum($selectedAmounts);
841 // The form offers a field to enter the amount paid. This may differ from the amount that is due to complete the purchase
842 $totalPaymentAmountEnteredOnForm = CRM_Utils_Array
::value('partial_payment_total', $fields, CRM_Utils_Array
::value('total_amount', $fields));
843 if ($totalAmount < 0) {
844 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', [1 => $componentName]);
846 elseif ($totalAmount > 0 &&
847 // if total amount is equal to all selected amount in hand
848 $totalPaymentAmountEnteredOnForm >= $totalAmount &&
849 (CRM_Utils_Array
::value('contribution_status_id', $fields) == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Partially paid'))
851 $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');
855 if ($allowNoneSelection) {
856 if (empty($noneSelectedPriceFields)) {
857 $error['_qf_default'] = ts('Please select at least one option from price set.');
861 $error['_qf_default'] = ts('Please select at least one option from price set.');
867 * Generate the label for price fields based on tax display setting option on CiviContribute Component Settings page.
870 * @param string $valueFieldName
872 * @param string $displayOpt
873 * Tax display setting option.
875 * @param string $taxTerm
878 * Tax label for custom field.
880 public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm) {
881 if ($displayOpt == 'Do_not_show') {
882 $label = CRM_Utils_Money
::format($opt[$valueFieldName] +
$opt['tax_amount']);
884 elseif ($displayOpt == 'Inclusive') {
885 $label = CRM_Utils_Money
::format($opt[$valueFieldName] +
$opt['tax_amount']);
886 $label .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money
::format($opt['tax_amount']) . ')</span>';
889 $label = CRM_Utils_Money
::format($opt[$valueFieldName]);
890 $label .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money
::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
897 * Given the name of a visibility option, returns its ID.
899 * @param string $visibilityName
903 public static function getVisibilityOptionID($visibilityName) {
905 if (!isset(self
::$visibilityOptionsKeys)) {
906 self
::$visibilityOptionsKeys = CRM_Price_BAO_PriceField
::buildOptions(
910 'labelColumn' => 'name',
916 if (isset(self
::$visibilityOptionsKeys[$visibilityName])) {
917 return self
::$visibilityOptionsKeys[$visibilityName];