3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * Business objects for managing price fields.
40 class CRM_Price_BAO_PriceField
extends CRM_Price_DAO_PriceField
{
45 * takes an associative array and creates a price field object
47 * the function extract all the params it needs to initialize the create a
48 * price field object. the params array could contain additional unused name/value
51 * @param array $params (reference ) an assoc array of name/value pairs
52 * @param array $ids the array that holds all the db ids
54 * @return object CRM_Price_BAO_PriceField object
58 static function &add(&$params) {
59 $priceFieldBAO = new CRM_Price_BAO_PriceField();
61 $priceFieldBAO->copyValues($params);
63 if ($id = CRM_Utils_Array
::value('id', $params)) {
64 $priceFieldBAO->id
= $id;
67 $priceFieldBAO->save();
68 return $priceFieldBAO;
72 * takes an associative array and creates a price field object
74 * This function is invoked from within the web form layer and also from the api layer
76 * @param array $params (reference) an assoc array of name/value pairs
78 * @return object CRM_Price_DAO_PriceField object
82 static function create(&$params) {
83 $transaction = new CRM_Core_Transaction();
85 $priceField = self
::add($params);
87 if (is_a($priceField, 'CRM_Core_Error')) {
88 $transaction->rollback();
92 $options = $optionsIds = array();
93 $maxIndex = CRM_Price_Form_Field
::NUM_OPTION
;
95 if ($priceField->html_type
== 'Text') {
98 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
99 $fieldValue->price_field_id
= $priceField->id
;
101 // update previous field values( if any )
102 if ($fieldValue->find(TRUE)) {
103 $optionsIds['id'] = $fieldValue->id
;
106 $defaultArray = array();
107 if ($params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
108 $tempArray = array_keys($params['default_checkbox_option']);
109 foreach ($tempArray as $v) {
110 if ($params['option_amount'][$v]) {
111 $defaultArray[$v] = 1;
116 if (!empty($params['default_option'])) {
117 $defaultArray[$params['default_option']] = 1;
121 for ($index = 1; $index <= $maxIndex; $index++
) {
122 if (array_key_exists('option_amount', $params) &&
123 array_key_exists($index, $params['option_amount']) &&
124 (CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_label', $params)) ||
!empty($params['is_quick_config'])) &&
125 !CRM_Utils_System
::isNull($params['option_amount'][$index])
128 'price_field_id' => $priceField->id
,
129 'label' => trim($params['option_label'][$index]),
130 'name' => CRM_Utils_String
::munge($params['option_label'][$index], '_', 64),
131 'amount' => CRM_Utils_Rule
::cleanMoney(trim($params['option_amount'][$index])),
132 'count' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_count', $params), NULL),
133 'max_value' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_max_value', $params), NULL),
134 'description' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_description', $params), NULL),
135 'membership_type_id' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_type_id', $params), NULL),
136 'weight' => $params['option_weight'][$index],
138 'is_default' => CRM_Utils_Array
::value($params['option_weight'][$index], $defaultArray) ?
$defaultArray[$params['option_weight'][$index]] : 0,
139 'membership_num_terms' => NULL,
142 if ($options['membership_type_id']) {
143 $options['membership_num_terms'] = CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_num_terms', $params), 1);
146 if (CRM_Utils_Array
::value( $index, CRM_Utils_Array
::value('option_financial_type_id', $params))) {
147 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
148 } elseif (!empty($params['financial_type_id'])) {
149 $options['financial_type_id'] = $params['financial_type_id'];
152 if ($opIds = CRM_Utils_Array
::value('option_id', $params)) {
153 if ($opId = CRM_Utils_Array
::value($index, $opIds)) {
154 $optionsIds['id'] = $opId;
156 $optionsIds['id'] = NULL;
159 CRM_Price_BAO_PriceFieldValue
::create($options, $optionsIds);
163 $transaction->commit();
168 * Takes a bunch of params that are needed to match certain criteria and
169 * retrieves the relevant objects. Typically the valid params are only
170 * contact_id. We'll tweak this function to be more full featured over a period
171 * of time. This is the inverse function of create. It also stores all the retrieved
172 * values in the default array
174 * @param array $params (reference ) an assoc array of name/value pairs
175 * @param array $defaults (reference ) an assoc array to hold the flattened values
177 * @return object CRM_Price_DAO_PriceField object
181 static function retrieve(&$params, &$defaults) {
182 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
186 * update the is_active flag in the db
188 * @param int $id Id of the database record
189 * @param boolean $is_active Value we want to set the is_active field
191 * @return Object DAO object on sucess, null otherwise
196 static function setIsActive($id, $is_active) {
197 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
201 * Get the field title.
203 * @param int $id id of field.
205 * @return string name
211 public static function getTitle($id) {
212 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
216 * This function for building custom fields
218 * @param object $qf form object (reference)
219 * @param string $elementName name of the custom field
220 * @param boolean $inactiveNeeded
221 * @param boolean $useRequired true if required else false
222 * @param boolean $search true if used for search else false
223 * @param string $label label for custom field
228 public static function addQuickFormElement(&$qf,
234 $fieldOptions = NULL,
235 $feezeOptions = array()
238 $field = new CRM_Price_DAO_PriceField();
239 $field->id
= $fieldId;
240 if (!$field->find(TRUE)) {
241 /* FIXME: failure! */
246 if (isset($qf->_mode
) && empty($qf->_mode
)) {
249 elseif (isset($qf->_values
)) {
250 $is_pay_later = CRM_Utils_Array
::value( 'is_pay_later', $qf->_values
);
253 $otherAmount = $qf->get('values');
254 $config = CRM_Core_Config
::singleton();
255 $currencySymbol = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_Currency',$config->defaultCurrency
,'symbol','name');
256 $qf->assign('currencySymbol', $currencySymbol);
257 // get currency name for price field and option attributes
258 $currencyName = $config->defaultCurrency
;
260 if (!isset($label)) {
261 $label = (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') ?
ts('Additional Contribution') : $field->label
;
264 if ($field->name
== 'contribution_amount') {
265 $qf->_contributionAmount
= 1;
268 if (isset($qf->_online
) && $qf->_online
) {
269 $useRequired = FALSE;
272 $customOption = $fieldOptions;
273 if (!is_array($customOption)) {
274 $customOption = CRM_Price_BAO_PriceField
::getOptions($field->id
, $inactiveNeeded);
278 $valueFieldName = 'amount';
280 switch ($field->html_type
) {
282 $optionKey = key($customOption);
283 $count = CRM_Utils_Array
::value('count', $customOption[$optionKey], '');
284 $max_value = CRM_Utils_Array
::value('max_value', $customOption[$optionKey], '');
285 $priceVal = implode($seperator, array($customOption[$optionKey][$valueFieldName], $count, $max_value));
288 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
)) {
289 foreach($fieldOptions as &$fieldOption) {
290 if ($fieldOption['name'] == 'other_amount') {
291 $fieldOption['label'] = $fieldOption['label'] . ' ' . $currencySymbol;
294 $qf->assign('priceset', $elementName);
295 $extra = array('onclick' => 'useAmountOther();');
298 // if seperate membership payment is used with quick config priceset then change the other amount label
299 if (!empty($qf->_membershipBlock
) && !empty($qf->_quickConfig
) && $field->name
== 'other_amount' && empty($qf->_contributionAmount
)) {
300 $label = ts('Additional Contribution');
303 elseif (!empty($fieldOptions[$optionKey]['label'])) { //check for label.
304 $label = $fieldOptions[$optionKey]['label'];
307 $element = &$qf->add('text', $elementName, $label,
309 array('price' => json_encode(array($optionKey, $priceVal)),
313 $useRequired && $field->is_required
316 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
320 if (in_array($optionKey, $feezeOptions)) {
325 if (!empty($qf->_quickConfig
)) {
326 $message = ts('Please enter a valid amount.');
330 $message = ts('%1 must be an integer (whole number).', array(1 => $label));
331 $type = 'positiveInteger';
333 // integers will have numeric rule applied to them.
334 $qf->addRule($elementName, $message, $type);
340 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
)) {
341 $qf->assign('contriPriceset', $elementName);
344 foreach ($customOption as $opId => $opt) {
345 if ($field->is_display_amounts
) {
346 $opt['label'] = !empty($opt['label']) ?
$opt['label'] : '';
347 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName]) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
349 $count = CRM_Utils_Array
::value('count', $opt, '');
350 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
351 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
352 $extra = array('price' => json_encode(array($elementName, $priceVal)),
353 'data-amount' => $opt[$valueFieldName],
354 'data-currency' => $currencyName,
356 if (!empty($qf->_quickConfig
) && $field->name
== 'contribution_amount') {
357 $extra +
= array('onclick' => 'clearAmountOther();');
359 elseif (!empty($qf->_quickConfig
) && $field->name
== 'membership_amount') {
361 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
362 'membership-type' => $opt['membership_type_id'],
364 $qf->assign('membershipFieldID',$field->id
);
367 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
370 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
374 if (in_array($opId, $feezeOptions)) {
375 $choice[$opId]->freeze();
378 if (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') {
379 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
381 'onclick' => 'clearAmountOther();',
386 if (!$field->is_required
) {
388 if (!empty($otherAmount['is_allow_other_amount']) && $field->name
== 'contribution_amount') {
389 $none = ts('Other Amount');
391 elseif (!empty($qf->_membershipBlock
) && empty($qf->_membershipBlock
['is_required']) && $field->name
== 'membership_amount') {
392 $none = ts('No thank you');
395 $none = ts('- none -');
398 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
399 array('price' => json_encode(array($elementName, '0')))
403 $element = &$qf->addGroup($choice, $elementName, $label);
405 // make contribution field required for quick config when membership block is enabled
406 if (($field->name
== 'membership_amount' ||
$field->name
== 'contribution_amount')
407 && !empty($qf->_membershipBlock
) && !$field->is_required
) {
408 $useRequired = $field->is_required
= TRUE;
411 if ($useRequired && $field->is_required
) {
412 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
417 $selectOption = $allowedOptions = $priceVal = array();
419 foreach ($customOption as $opt) {
420 $count = CRM_Utils_Array
::value('count', $opt, '');
421 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
422 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
424 if ($field->is_display_amounts
) {
425 $opt['label'] .= ' - ';
426 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
428 $selectOption[$opt['id']] = $opt['label'];
430 if (!in_array($opt['id'], $feezeOptions)) {
431 $allowedOptions[] = $opt['id'];
434 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
437 $element = &$qf->add('select', $elementName, $label,
439 '' => ts('- select -')) +
$selectOption,
440 $useRequired && $field->is_required
,
441 array('price' => json_encode($priceVal))
445 $button = substr($qf->controller
->getButtonName(), -4);
446 if (!empty($feezeOptions) && $button != 'skip') {
447 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
454 foreach ($customOption as $opId => $opt) {
455 $count = CRM_Utils_Array
::value('count', $opt, '');
456 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
457 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
459 if ($field->is_display_amounts
) {
460 $opt['label'] .= ' - ';
461 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
463 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
464 array('price' => json_encode(array($opt['id'], $priceVal)),
465 'data-amount' => $opt[$valueFieldName],
466 'data-currency' => $currencyName,
470 $txtcheck[$opId] =& $qf->createElement( 'text', $opId, $opt['label'], array( 'size' => '4' ) );
471 $qf->addGroup($txtcheck, 'txt-'.$elementName, $label);
474 if (in_array($opId, $feezeOptions)) {
475 $check[$opId]->freeze();
478 $element = &$qf->addGroup($check, $elementName, $label);
479 if ($useRequired && $field->is_required
) {
480 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
484 if (isset($qf->_online
) && $qf->_online
) {
490 * Retrieve a list of options for the specified field
492 * @param int $fieldId price field ID
493 * @param bool $inactiveNeeded include inactive options
494 * @param bool $reset ignore stored values\
496 * @return array array of options
498 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
499 static $options = array();
501 if ($reset ||
empty($options[$fieldId])) {
503 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
504 $options[$fieldId] = $values;
507 return $options[$fieldId];
510 public static function getOptionId($optionLabel, $fid) {
511 if (!$optionLabel ||
!$fid) {
515 $optionGroupName = "civicrm_price_field.amount.{$fid}";
519 option_value.id as id
521 civicrm_option_value option_value,
522 civicrm_option_group option_group
524 option_group.name = %1
525 AND option_group.id = option_value.option_group_id
526 AND option_value.label = %2";
528 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($optionGroupName, 'String'), 2 => array($optionLabel, 'String')));
530 while ($dao->fetch()) {
536 * Delete the price set field.
538 * @param int $id Field Id
546 public static function deleteField($id) {
547 $field = new CRM_Price_DAO_PriceField();
550 if ($field->find(TRUE)) {
551 // delete the options for this field
552 CRM_Price_BAO_PriceFieldValue
::deleteValues($id);
554 // reorder the weight before delete
555 $fieldValues = array('price_set_id' => $field->price_set_id
);
557 CRM_Utils_Weight
::delWeight('CRM_Price_DAO_PriceField', $field->id
, $fieldValues);
559 // now delete the field
560 return $field->delete();
566 static function &htmlTypes() {
567 static $htmlTypes = NULL;
570 'Text' => ts('Text / Numeric Quantity'),
571 'Select' => ts('Select'),
572 'Radio' => ts('Radio'),
573 'CheckBox' => ts('CheckBox'),
580 * Validate the priceset
582 * @param int $priceSetId, array $fields
584 * retrun the error string
591 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
592 // check for at least one positive
593 // amount price field should be selected.
594 $priceField = new CRM_Price_DAO_PriceField();
595 $priceField->price_set_id
= $priceSetId;
598 $priceFields = array();
600 if ($allowNoneSelection) {
601 $noneSelectedPriceFields = array();
604 while ($priceField->fetch()) {
605 $key = "price_{$priceField->id}";
607 if ($allowNoneSelection) {
608 if (array_key_exists($key, $fields)) {
609 if ($fields[$key] == 0 && !$priceField->is_required
) {
610 $noneSelectedPriceFields[] = $priceField->id
;
615 if (!empty($fields[$key])) {
616 $priceFields[$priceField->id
] = $fields[$key];
620 if (!empty($priceFields)) {
621 // we should has to have positive amount.
624 FROM civicrm_price_field
625 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
626 $fieldDAO = CRM_Core_DAO
::executeQuery($sql);
627 $htmlTypes = array();
628 while ($fieldDAO->fetch()) {
629 $htmlTypes[$fieldDAO->id
] = $fieldDAO->html_type
;
632 $selectedAmounts = array();
634 foreach ($htmlTypes as $fieldId => $type) {
636 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $options);
638 if (empty($options)) {
642 if ($type == 'Text') {
643 foreach ($options as $opId => $option) {
644 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
648 elseif (is_array($fields["price_{$fieldId}"])) {
649 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
650 $selectedAmounts[$opId] = $options[$opId]['amount'];
653 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
654 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
658 list($componentName) = explode(':', $fields['_qf_default']);
659 // now we have all selected amount in hand.
660 $totalAmount = array_sum($selectedAmounts);
661 if ($totalAmount < 0) {
662 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
666 if ($allowNoneSelection) {
667 if (empty($noneSelectedPriceFields)) {
668 $error['_qf_default'] = ts('Please select at least one option from price set.');
671 $error['_qf_default'] = ts('Please select at least one option from price set.');