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
53 * @internal param array $ids the array that holds all the db ids
55 * @return object CRM_Price_BAO_PriceField object
59 static function add(&$params) {
60 $priceFieldBAO = new CRM_Price_BAO_PriceField();
62 $priceFieldBAO->copyValues($params);
64 if ($id = CRM_Utils_Array
::value('id', $params)) {
65 $priceFieldBAO->id
= $id;
68 $priceFieldBAO->save();
69 return $priceFieldBAO;
73 * takes an associative array and creates a price field object
75 * This function is invoked from within the web form layer and also from the api layer
77 * @param array $params (reference) an assoc array of name/value pairs
79 * @return object CRM_Price_DAO_PriceField object
83 static function create(&$params) {
84 if(empty($params['id']) && empty($params['name'])) {
85 $params['name'] = strtolower(CRM_Utils_String
::munge($params['label'], '_', 242));
87 $transaction = new CRM_Core_Transaction();
89 $priceField = self
::add($params);
91 if (is_a($priceField, 'CRM_Core_Error')) {
92 $transaction->rollback();
96 $optionsIds = array();
97 $maxIndex = CRM_Price_Form_Field
::NUM_OPTION
;
99 if ($priceField->html_type
== 'Text') {
102 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
103 $fieldValue->price_field_id
= $priceField->id
;
105 // update previous field values( if any )
106 if ($fieldValue->find(TRUE)) {
107 $optionsIds['id'] = $fieldValue->id
;
110 $defaultArray = array();
111 //html type would be empty in update scenario not sure what would happen ...
112 if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
113 $tempArray = array_keys($params['default_checkbox_option']);
114 foreach ($tempArray as $v) {
115 if ($params['option_amount'][$v]) {
116 $defaultArray[$v] = 1;
121 if (!empty($params['default_option'])) {
122 $defaultArray[$params['default_option']] = 1;
126 for ($index = 1; $index <= $maxIndex; $index++
) {
127 if (array_key_exists('option_amount', $params) &&
128 array_key_exists($index, $params['option_amount']) &&
129 (CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_label', $params)) ||
!empty($params['is_quick_config'])) &&
130 !CRM_Utils_System
::isNull($params['option_amount'][$index])
133 'price_field_id' => $priceField->id
,
134 'label' => trim($params['option_label'][$index]),
135 'name' => CRM_Utils_String
::munge($params['option_label'][$index], '_', 64),
136 'amount' => CRM_Utils_Rule
::cleanMoney(trim($params['option_amount'][$index])),
137 'count' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_count', $params), NULL),
138 'max_value' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_max_value', $params), NULL),
139 'description' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_description', $params), NULL),
140 'membership_type_id' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_type_id', $params), NULL),
141 'weight' => $params['option_weight'][$index],
143 'is_default' => CRM_Utils_Array
::value($params['option_weight'][$index], $defaultArray) ?
$defaultArray[$params['option_weight'][$index]] : 0,
144 'membership_num_terms' => NULL,
147 if ($options['membership_type_id']) {
148 $options['membership_num_terms'] = CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_num_terms', $params), 1);
151 if (CRM_Utils_Array
::value( $index, CRM_Utils_Array
::value('option_financial_type_id', $params))) {
152 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
153 } elseif (!empty($params['financial_type_id'])) {
154 $options['financial_type_id'] = $params['financial_type_id'];
157 if ($opIds = CRM_Utils_Array
::value('option_id', $params)) {
158 if ($opId = CRM_Utils_Array
::value($index, $opIds)) {
159 $optionsIds['id'] = $opId;
161 $optionsIds['id'] = NULL;
164 CRM_Price_BAO_PriceFieldValue
::create($options, $optionsIds);
168 $transaction->commit();
173 * Takes a bunch of params that are needed to match certain criteria and
174 * retrieves the relevant objects. Typically the valid params are only
175 * contact_id. We'll tweak this function to be more full featured over a period
176 * of time. This is the inverse function of create. It also stores all the retrieved
177 * values in the default array
179 * @param array $params (reference ) an assoc array of name/value pairs
180 * @param array $defaults (reference ) an assoc array to hold the flattened values
182 * @return object CRM_Price_DAO_PriceField object
186 static function retrieve(&$params, &$defaults) {
187 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
191 * update the is_active flag in the db
193 * @param int $id Id of the database record
194 * @param boolean $is_active Value we want to set the is_active field
196 * @return Object DAO object on sucess, null otherwise
201 static function setIsActive($id, $is_active) {
202 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
206 * Get the field title.
208 * @param int $id id of field.
210 * @return string name
216 public static function getTitle($id) {
217 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
221 * This function for building custom fields
223 * @param CRM_Core_Form $qf form object (reference)
224 * @param string $elementName name of the custom field
226 * @param boolean $inactiveNeeded
227 * @param boolean $useRequired true if required else false
228 * @param string $label label for custom field
230 * @param null $fieldOptions
231 * @param array $feezeOptions
234 * @internal param bool $search true if used for search else false
238 public static function addQuickFormElement(&$qf,
244 $fieldOptions = NULL,
245 $feezeOptions = array()
248 $field = new CRM_Price_DAO_PriceField();
249 $field->id
= $fieldId;
250 if (!$field->find(TRUE)) {
251 /* FIXME: failure! */
256 if (isset($qf->_mode
) && empty($qf->_mode
)) {
259 elseif (isset($qf->_values
)) {
260 $is_pay_later = CRM_Utils_Array
::value( 'is_pay_later', $qf->_values
);
263 $otherAmount = $qf->get('values');
264 $config = CRM_Core_Config
::singleton();
265 $currencySymbol = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_Currency',$config->defaultCurrency
,'symbol','name');
266 $qf->assign('currencySymbol', $currencySymbol);
267 // get currency name for price field and option attributes
268 $currencyName = $config->defaultCurrency
;
270 if (!isset($label)) {
271 $label = (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') ?
ts('Additional Contribution') : $field->label
;
274 if ($field->name
== 'contribution_amount') {
275 $qf->_contributionAmount
= 1;
278 if (isset($qf->_online
) && $qf->_online
) {
279 $useRequired = FALSE;
282 $customOption = $fieldOptions;
283 if (!is_array($customOption)) {
284 $customOption = CRM_Price_BAO_PriceField
::getOptions($field->id
, $inactiveNeeded);
288 $valueFieldName = 'amount';
290 switch ($field->html_type
) {
292 $optionKey = key($customOption);
293 $count = CRM_Utils_Array
::value('count', $customOption[$optionKey], '');
294 $max_value = CRM_Utils_Array
::value('max_value', $customOption[$optionKey], '');
295 $priceVal = implode($seperator, array($customOption[$optionKey][$valueFieldName], $count, $max_value));
298 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
)) {
299 foreach($fieldOptions as &$fieldOption) {
300 if ($fieldOption['name'] == 'other_amount') {
301 $fieldOption['label'] = $fieldOption['label'] . ' ' . $currencySymbol;
304 $qf->assign('priceset', $elementName);
305 $extra = array('onclick' => 'useAmountOther();');
308 if (!empty($qf->_membershipBlock
) && !empty($qf->_quickConfig
) && $field->name
== 'other_amount' && empty($qf->_contributionAmount
)) {
311 elseif (!empty($fieldOptions[$optionKey]['label'])) { //check for label.
312 $label = $fieldOptions[$optionKey]['label'];
315 $element = &$qf->add('text', $elementName, $label,
317 array('price' => json_encode(array($optionKey, $priceVal)),
321 $useRequired && $field->is_required
324 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
328 if (in_array($optionKey, $feezeOptions)) {
333 if (!empty($qf->_quickConfig
)) {
334 $message = ts('Please enter a valid amount.');
338 $message = ts('%1 must be an integer (whole number).', array(1 => $label));
339 $type = 'positiveInteger';
341 // integers will have numeric rule applied to them.
342 $qf->addRule($elementName, $message, $type);
348 if (!empty($qf->_quickConfig
) && !empty($qf->_contributionAmount
)) {
349 $qf->assign('contriPriceset', $elementName);
352 foreach ($customOption as $opId => $opt) {
353 if ($field->is_display_amounts
) {
354 $opt['label'] = !empty($opt['label']) ?
$opt['label'] : '';
355 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money
::format($opt[$valueFieldName]) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
357 $count = CRM_Utils_Array
::value('count', $opt, '');
358 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
359 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
360 $extra = array('price' => json_encode(array($elementName, $priceVal)),
361 'data-amount' => $opt[$valueFieldName],
362 'data-currency' => $currencyName,
364 if (!empty($qf->_quickConfig
) && $field->name
== 'contribution_amount') {
365 $extra +
= array('onclick' => 'clearAmountOther();');
367 elseif (!empty($qf->_quickConfig
) && $field->name
== 'membership_amount') {
369 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
370 'membership-type' => $opt['membership_type_id'],
372 $qf->assign('membershipFieldID',$field->id
);
375 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
378 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
382 if (in_array($opId, $feezeOptions)) {
383 $choice[$opId]->freeze();
386 if (!empty($qf->_membershipBlock
) && $field->name
== 'contribution_amount') {
387 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
389 'onclick' => 'clearAmountOther();',
394 if (!$field->is_required
) {
396 if (!empty($otherAmount['is_allow_other_amount']) && $field->name
== 'contribution_amount') {
397 $none = ts('Other Amount');
399 elseif (!empty($qf->_membershipBlock
) && empty($qf->_membershipBlock
['is_required']) && $field->name
== 'membership_amount') {
400 $none = ts('No thank you');
403 $none = ts('- none -');
406 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
407 array('price' => json_encode(array($elementName, '0')))
411 $element = &$qf->addGroup($choice, $elementName, $label);
413 // make contribution field required for quick config when membership block is enabled
414 if (($field->name
== 'membership_amount' ||
$field->name
== 'contribution_amount')
415 && !empty($qf->_membershipBlock
) && !$field->is_required
) {
416 $useRequired = $field->is_required
= TRUE;
419 if ($useRequired && $field->is_required
) {
420 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
425 $selectOption = $allowedOptions = $priceVal = array();
427 foreach ($customOption as $opt) {
428 $count = CRM_Utils_Array
::value('count', $opt, '');
429 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
430 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
432 if ($field->is_display_amounts
) {
433 $opt['label'] .= ' - ';
434 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
436 $selectOption[$opt['id']] = $opt['label'];
438 if (!in_array($opt['id'], $feezeOptions)) {
439 $allowedOptions[] = $opt['id'];
442 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
445 $element = &$qf->add('select', $elementName, $label,
447 '' => ts('- select -')) +
$selectOption,
448 $useRequired && $field->is_required
,
449 array('price' => json_encode($priceVal))
453 $button = substr($qf->controller
->getButtonName(), -4);
454 if (!empty($feezeOptions) && $button != 'skip') {
455 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
462 foreach ($customOption as $opId => $opt) {
463 $count = CRM_Utils_Array
::value('count', $opt, '');
464 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
465 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
467 if ($field->is_display_amounts
) {
468 $opt['label'] .= ' - ';
469 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
471 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
472 array('price' => json_encode(array($opt['id'], $priceVal)),
473 'data-amount' => $opt[$valueFieldName],
474 'data-currency' => $currencyName,
478 $txtcheck[$opId] =& $qf->createElement( 'text', $opId, $opt['label'], array( 'size' => '4' ) );
479 $qf->addGroup($txtcheck, 'txt-'.$elementName, $label);
482 if (in_array($opId, $feezeOptions)) {
483 $check[$opId]->freeze();
486 $element = &$qf->addGroup($check, $elementName, $label);
487 if ($useRequired && $field->is_required
) {
488 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
492 if (isset($qf->_online
) && $qf->_online
) {
498 * Retrieve a list of options for the specified field
500 * @param int $fieldId price field ID
501 * @param bool $inactiveNeeded include inactive options
502 * @param bool $reset ignore stored values\
504 * @return array array of options
506 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
507 static $options = array();
509 if ($reset ||
empty($options[$fieldId])) {
511 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
512 $options[$fieldId] = $values;
515 return $options[$fieldId];
519 * @param $optionLabel
524 public static function getOptionId($optionLabel, $fid) {
525 if (!$optionLabel ||
!$fid) {
529 $optionGroupName = "civicrm_price_field.amount.{$fid}";
533 option_value.id as id
535 civicrm_option_value option_value,
536 civicrm_option_group option_group
538 option_group.name = %1
539 AND option_group.id = option_value.option_group_id
540 AND option_value.label = %2";
542 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($optionGroupName, 'String'), 2 => array($optionLabel, 'String')));
544 while ($dao->fetch()) {
550 * Delete the price set field.
552 * @param int $id Field Id
560 public static function deleteField($id) {
561 $field = new CRM_Price_DAO_PriceField();
564 if ($field->find(TRUE)) {
565 // delete the options for this field
566 CRM_Price_BAO_PriceFieldValue
::deleteValues($id);
568 // reorder the weight before delete
569 $fieldValues = array('price_set_id' => $field->price_set_id
);
571 CRM_Utils_Weight
::delWeight('CRM_Price_DAO_PriceField', $field->id
, $fieldValues);
573 // now delete the field
574 return $field->delete();
583 static function &htmlTypes() {
584 static $htmlTypes = NULL;
587 'Text' => ts('Text / Numeric Quantity'),
588 'Select' => ts('Select'),
589 'Radio' => ts('Radio'),
590 'CheckBox' => ts('CheckBox'),
597 * Validate the priceset
599 * @param int $priceSetId , array $fields
601 * retrun the error string
605 * @param bool $allowNoneSelection
611 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
612 // check for at least one positive
613 // amount price field should be selected.
614 $priceField = new CRM_Price_DAO_PriceField();
615 $priceField->price_set_id
= $priceSetId;
618 $priceFields = array();
620 if ($allowNoneSelection) {
621 $noneSelectedPriceFields = array();
624 while ($priceField->fetch()) {
625 $key = "price_{$priceField->id}";
627 if ($allowNoneSelection) {
628 if (array_key_exists($key, $fields)) {
629 if ($fields[$key] == 0 && !$priceField->is_required
) {
630 $noneSelectedPriceFields[] = $priceField->id
;
635 if (!empty($fields[$key])) {
636 $priceFields[$priceField->id
] = $fields[$key];
640 if (!empty($priceFields)) {
641 // we should has to have positive amount.
644 FROM civicrm_price_field
645 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
646 $fieldDAO = CRM_Core_DAO
::executeQuery($sql);
647 $htmlTypes = array();
648 while ($fieldDAO->fetch()) {
649 $htmlTypes[$fieldDAO->id
] = $fieldDAO->html_type
;
652 $selectedAmounts = array();
654 foreach ($htmlTypes as $fieldId => $type) {
656 CRM_Price_BAO_PriceFieldValue
::getValues($fieldId, $options);
658 if (empty($options)) {
662 if ($type == 'Text') {
663 foreach ($options as $opId => $option) {
664 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
668 elseif (is_array($fields["price_{$fieldId}"])) {
669 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
670 $selectedAmounts[$opId] = $options[$opId]['amount'];
673 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
674 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
678 list($componentName) = explode(':', $fields['_qf_default']);
679 // now we have all selected amount in hand.
680 $totalAmount = array_sum($selectedAmounts);
681 if ($totalAmount < 0) {
682 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
686 if ($allowNoneSelection) {
687 if (empty($noneSelectedPriceFields)) {
688 $error['_qf_default'] = ts('Please select at least one option from price set.');
691 $error['_qf_default'] = ts('Please select at least one option from price set.');