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 (!empty($qf->_membershipBlock
) && !empty($qf->_quickConfig
) && $field->name
== 'other_amount' && empty($qf->_contributionAmount
)) {
301 elseif (!empty($fieldOptions[$optionKey]['label'])) { //check for label.
302 $label = $fieldOptions[$optionKey]['label'];
305 $element = &$qf->add('text', $elementName, $label,
307 array('price' => json_encode(array($optionKey, $priceVal)),
311 $useRequired && $field->is_required
314 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
318 if (in_array($optionKey, $feezeOptions)) {
323 if (!empty($qf->_quickConfig
)) {
324 $message = ts('Please enter a valid amount.');
328 $message = ts('%1 must be an integer (whole number).', array(1 => $label));
329 $type = 'positiveInteger';
331 // integers will have numeric rule applied to them.
332 $qf->addRule($elementName, $message, $type);
338 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
)) {
339 $qf->assign('contriPriceset', $elementName);
342 foreach ($customOption as $opId => $opt) {
343 if ($field->is_display_amounts
) {
344 $opt['label'] = !empty($opt['label']) ?
$opt['label'] : '';
345 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName]) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
347 $count = CRM_Utils_Array
::value('count', $opt, '');
348 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
349 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
350 $extra = array('price' => json_encode(array($elementName, $priceVal)),
351 'data-amount' => $opt[$valueFieldName],
352 'data-currency' => $currencyName,
354 if (!empty($qf->_quickConfig
) && $field->name
== 'contribution_amount') {
355 $extra +
= array('onclick' => 'clearAmountOther();');
357 elseif (!empty($qf->_quickConfig
) && $field->name
== 'membership_amount') {
359 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
360 'membership-type' => $opt['membership_type_id'],
362 $qf->assign('membershipFieldID',$field->id
);
365 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
368 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
372 if (in_array($opId, $feezeOptions)) {
373 $choice[$opId]->freeze();
376 if (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') {
377 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
379 'onclick' => 'clearAmountOther();',
384 if (!$field->is_required
) {
386 if (!empty($otherAmount['is_allow_other_amount']) && $field->name
== 'contribution_amount') {
387 $none = ts('Other Amount');
389 elseif (!empty($qf->_membershipBlock
) && empty($qf->_membershipBlock
['is_required']) && $field->name
== 'membership_amount') {
390 $none = ts('No thank you');
393 $none = ts('- none -');
396 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
397 array('price' => json_encode(array($elementName, '0')))
401 $element = &$qf->addGroup($choice, $elementName, $label);
403 // make contribution field required for quick config when membership block is enabled
404 if (($field->name
== 'membership_amount' ||
$field->name
== 'contribution_amount')
405 && !empty($qf->_membershipBlock
) && !$field->is_required
) {
406 $useRequired = $field->is_required
= TRUE;
409 if ($useRequired && $field->is_required
) {
410 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
415 $selectOption = $allowedOptions = $priceVal = array();
417 foreach ($customOption as $opt) {
418 $count = CRM_Utils_Array
::value('count', $opt, '');
419 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
420 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
422 if ($field->is_display_amounts
) {
423 $opt['label'] .= ' - ';
424 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
426 $selectOption[$opt['id']] = $opt['label'];
428 if (!in_array($opt['id'], $feezeOptions)) {
429 $allowedOptions[] = $opt['id'];
432 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
435 $element = &$qf->add('select', $elementName, $label,
437 '' => ts('- select -')) +
$selectOption,
438 $useRequired && $field->is_required
,
439 array('price' => json_encode($priceVal))
443 $button = substr($qf->controller
->getButtonName(), -4);
444 if (!empty($feezeOptions) && $button != 'skip') {
445 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
452 foreach ($customOption as $opId => $opt) {
453 $count = CRM_Utils_Array
::value('count', $opt, '');
454 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
455 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
457 if ($field->is_display_amounts
) {
458 $opt['label'] .= ' - ';
459 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
461 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
462 array('price' => json_encode(array($opt['id'], $priceVal)),
463 'data-amount' => $opt[$valueFieldName],
464 'data-currency' => $currencyName,
468 $txtcheck[$opId] =& $qf->createElement( 'text', $opId, $opt['label'], array( 'size' => '4' ) );
469 $qf->addGroup($txtcheck, 'txt-'.$elementName, $label);
472 if (in_array($opId, $feezeOptions)) {
473 $check[$opId]->freeze();
476 $element = &$qf->addGroup($check, $elementName, $label);
477 if ($useRequired && $field->is_required
) {
478 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
482 if (isset($qf->_online
) && $qf->_online
) {
488 * Retrieve a list of options for the specified field
490 * @param int $fieldId price field ID
491 * @param bool $inactiveNeeded include inactive options
492 * @param bool $reset ignore stored values\
494 * @return array array of options
496 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
497 static $options = array();
499 if ($reset ||
empty($options[$fieldId])) {
501 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
502 $options[$fieldId] = $values;
505 return $options[$fieldId];
508 public static function getOptionId($optionLabel, $fid) {
509 if (!$optionLabel ||
!$fid) {
513 $optionGroupName = "civicrm_price_field.amount.{$fid}";
517 option_value.id as id
519 civicrm_option_value option_value,
520 civicrm_option_group option_group
522 option_group.name = %1
523 AND option_group.id = option_value.option_group_id
524 AND option_value.label = %2";
526 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($optionGroupName, 'String'), 2 => array($optionLabel, 'String')));
528 while ($dao->fetch()) {
534 * Delete the price set field.
536 * @param int $id Field Id
544 public static function deleteField($id) {
545 $field = new CRM_Price_DAO_PriceField();
548 if ($field->find(TRUE)) {
549 // delete the options for this field
550 CRM_Price_BAO_PriceFieldValue
::deleteValues($id);
552 // reorder the weight before delete
553 $fieldValues = array('price_set_id' => $field->price_set_id
);
555 CRM_Utils_Weight
::delWeight('CRM_Price_DAO_PriceField', $field->id
, $fieldValues);
557 // now delete the field
558 return $field->delete();
564 static function &htmlTypes() {
565 static $htmlTypes = NULL;
568 'Text' => ts('Text / Numeric Quantity'),
569 'Select' => ts('Select'),
570 'Radio' => ts('Radio'),
571 'CheckBox' => ts('CheckBox'),
578 * Validate the priceset
580 * @param int $priceSetId, array $fields
582 * retrun the error string
589 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
590 // check for at least one positive
591 // amount price field should be selected.
592 $priceField = new CRM_Price_DAO_PriceField();
593 $priceField->price_set_id
= $priceSetId;
596 $priceFields = array();
598 if ($allowNoneSelection) {
599 $noneSelectedPriceFields = array();
602 while ($priceField->fetch()) {
603 $key = "price_{$priceField->id}";
605 if ($allowNoneSelection) {
606 if (array_key_exists($key, $fields)) {
607 if ($fields[$key] == 0 && !$priceField->is_required
) {
608 $noneSelectedPriceFields[] = $priceField->id
;
613 if (!empty($fields[$key])) {
614 $priceFields[$priceField->id
] = $fields[$key];
618 if (!empty($priceFields)) {
619 // we should has to have positive amount.
622 FROM civicrm_price_field
623 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
624 $fieldDAO = CRM_Core_DAO
::executeQuery($sql);
625 $htmlTypes = array();
626 while ($fieldDAO->fetch()) {
627 $htmlTypes[$fieldDAO->id
] = $fieldDAO->html_type
;
630 $selectedAmounts = array();
632 foreach ($htmlTypes as $fieldId => $type) {
634 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $options);
636 if (empty($options)) {
640 if ($type == 'Text') {
641 foreach ($options as $opId => $option) {
642 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
646 elseif (is_array($fields["price_{$fieldId}"])) {
647 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
648 $selectedAmounts[$opId] = $options[$opId]['amount'];
651 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
652 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
656 list($componentName) = explode(':', $fields['_qf_default']);
657 // now we have all selected amount in hand.
658 $totalAmount = array_sum($selectedAmounts);
659 if ($totalAmount < 0) {
660 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
664 if ($allowNoneSelection) {
665 if (empty($noneSelectedPriceFields)) {
666 $error['_qf_default'] = ts('Please select at least one option from price set.');
669 $error['_qf_default'] = ts('Please select at least one option from price set.');