3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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_Upgrade_Snapshot_V4p2_Price_BAO_Field
extends CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field
{
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
52 * (reference ) an assoc array of name/value pairs.
54 * @return CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field object
57 public static function &add(&$params) {
58 $priceFieldBAO = new CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field();
60 $priceFieldBAO->copyValues($params);
62 if ($id = CRM_Utils_Array
::value('id', $params)) {
63 $priceFieldBAO->id
= $id;
66 $priceFieldBAO->save();
67 return $priceFieldBAO;
71 * Takes an associative array and creates a price field object
73 * This function is invoked from within the web form layer and also from the api layer
75 * @param array $params
76 * (reference) an assoc array of name/value pairs.
78 * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field object
81 public 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_Upgrade_Snapshot_V4p2_Price_DAO_FieldValue();
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++
) {
123 if (array_key_exists('option_amount', $params) &&
124 array_key_exists($index, $params['option_amount']) &&
125 (CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_label', $params)) ||
!empty($params['is_quick_config'])) &&
126 !CRM_Utils_System
::isNull($params['option_amount'][$index])
129 'price_field_id' => $priceField->id
,
130 'label' => trim($params['option_label'][$index]),
131 'name' => CRM_Utils_String
::munge($params['option_label'][$index], '_', 64),
132 'amount' => CRM_Utils_Rule
::cleanMoney(trim($params['option_amount'][$index])),
133 'count' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_count', $params), NULL),
134 'max_value' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_max_value', $params), NULL),
135 'description' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('option_description', $params), NULL),
136 'membership_type_id' => CRM_Utils_Array
::value($index, CRM_Utils_Array
::value('membership_type_id', $params), NULL),
137 'weight' => $params['option_weight'][$index],
139 'is_default' => CRM_Utils_Array
::value($params['option_weight'][$index], $defaultArray) ?
$defaultArray[$params['option_weight'][$index]] : 0,
142 if ($opIds = CRM_Utils_Array
::value('option_id', $params)) {
143 if ($opId = CRM_Utils_Array
::value($index, $opIds)) {
144 $optionsIds['id'] = $opId;
146 else { $optionsIds['id'] = NULL;
149 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue
::create($options, $optionsIds);
153 $transaction->commit();
158 * Fetch object based on array of properties
160 * @param array $params
161 * (reference ) an assoc array of name/value pairs.
162 * @param array $defaults
163 * (reference ) an assoc array to hold the flattened values.
165 * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field object
168 public static function retrieve(&$params, &$defaults) {
169 return CRM_Core_DAO
::commonRetrieve('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $params, $defaults);
173 * Update the is_active flag in the db
176 * Id of the database record.
177 * @param bool $is_active
178 * Value we want to set the is_active field.
180 * @return Object DAO object on sucess, null otherwise
184 public static function setIsActive($id, $is_active) {
185 return CRM_Core_DAO
::setFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $id, 'is_active', $is_active);
189 * Get the field title.
194 * @return string name
199 public static function getTitle($id) {
200 return CRM_Core_DAO
::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $id, 'label');
204 * This function for building custom fields
206 * @param CRM_Core_Form $qf
207 * Form object (reference).
208 * @param string $elementName
209 * Name of the custom field.
210 * @param int $fieldId
211 * @param bool $inactiveNeeded
212 * @param bool $useRequired
213 * True if required else false.
214 * @param string $label
215 * Label for custom field.
216 * @param null $fieldOptions
217 * @param array $freezeOptions
222 public static function addQuickFormElement(&$qf,
228 $fieldOptions = NULL,
229 $freezeOptions = array()
232 $field = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
233 $field->id
= $fieldId;
234 if (!$field->find(TRUE)) {
235 /* FIXME: failure! */
240 $otherAmount = $qf->get('values');
241 $config = CRM_Core_Config
::singleton();
242 $qf->assign('currencySymbol', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Currency', $config->defaultCurrency
, 'symbol', 'name'));
243 // get currency name for price field and option attributes
244 $currencyName = $config->defaultCurrency
;
246 if (!isset($label)) {
247 $label = (property_exists($qf, '_membershipBlock') && !empty($qf->_membershipBlock
['is_separate_payment']) && $field->name
== 'contribution_amount' && empty($otherAmount['is_allow_other_amount'])) ?
ts('Additional Contribution') : $field->label
;
250 if ($field->name
== 'contribution_amount') {
251 $qf->_contributionAmount
= 1;
254 if (isset($qf->_online
) && $qf->_online
) {
255 $useRequired = FALSE;
258 $customOption = $fieldOptions;
259 if (!is_array($customOption)) {
260 $customOption = CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field
::getOptions($field->id
, $inactiveNeeded);
264 $valueFieldName = 'amount';
266 switch ($field->html_type
) {
268 $optionKey = key($customOption);
269 $count = CRM_Utils_Array
::value('count', $customOption[$optionKey], '');
270 $max_value = CRM_Utils_Array
::value('max_value', $customOption[$optionKey], '');
271 $priceVal = implode($seperator, array($customOption[$optionKey][$valueFieldName], $count, $max_value));
274 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig
&& property_exists($qf, '_contributionAmount') && $qf->_contributionAmount
) {
275 $qf->assign('priceset', $elementName);
276 $extra = array('onclick' => 'useAmountOther();');
279 // if seperate membership payment is used with quick config priceset then change the other amount label
280 if (property_exists($qf, '_membershipBlock') && !empty($qf->_membershipBlock
['is_separate_payment']) && $qf->_quickConfig
&& $field->name
== 'other_amount' && !property_exists($qf, '_contributionAmount')) {
281 $label = ts('Additional Contribution');
283 } elseif (!empty($fieldOptions[$optionKey]['label'])) { //check for label.
284 $label = $fieldOptions[$optionKey]['label'];
287 if ($field->is_display_amounts
) {
288 $label .= ' - ';
289 $label .= CRM_Utils_Money
::format(CRM_Utils_Array
::value($valueFieldName, $customOption[$optionKey]));
292 $element = &$qf->add('text', $elementName, $label,
295 'price' => json_encode(array($optionKey, $priceVal)),
299 $useRequired && $field->is_required
303 if (in_array($optionKey, $freezeOptions)) {
308 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig
) {
309 $message = ts("Please enter a valid amount.");
312 $message = ts('%1 must be an integer (whole number).', array(1 => $label));
313 $type = "positiveInteger";
315 // integers will have numeric rule applied to them.
316 $qf->addRule($elementName, $message, $type);
322 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig
&& property_exists($qf, '_contributionAmount') && $qf->_contributionAmount
) {
323 $qf->assign('contriPriceset', $elementName);
326 foreach ($customOption as $opId => $opt) {
327 if ($field->is_display_amounts
) {
328 $opt['label'] = !empty($opt['label']) ?
$opt['label'] . ' - ' : '';
329 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
331 $count = CRM_Utils_Array
::value('count', $opt, '');
332 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
333 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
335 'price' => json_encode(array($elementName, $priceVal)),
336 'data-amount' => $opt[$valueFieldName],
337 'data-currency' => $currencyName,
339 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig
&& $field->name
== 'contribution_amount') {
340 $extra +
= array('onclick' => 'clearAmountOther();');
341 } elseif (property_exists($qf, '_quickConfig') && $qf->_quickConfig
&& $field->name
== 'membership_amount') {
343 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
344 'membership-type' => $opt['membership_type_id'],
346 $qf->assign('membershipFieldID', $field->id
);
348 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
351 if (in_array($opId, $freezeOptions)) {
352 $choice[$opId]->freeze();
356 if (property_exists($qf, '_membershipBlock') && !empty($qf->_membershipBlock
['is_separate_payment']) && $field->name
== 'contribution_amount') {
357 $choice[] = $qf->createElement('radio', NULL, '', 'No thank you', '-1',
359 'onclick' => 'clearAmountOther();',
364 if (!$field->is_required
) {
366 if (!empty($otherAmount['is_allow_other_amount']) && $field->name
== 'contribution_amount') {
367 $none = ts('Other Amount');
368 } elseif (property_exists($qf, '_membershipBlock') && empty($qf->_membershipBlock
['is_required']) && $field->name
== 'membership_amount') {
369 $none = ts('No thank you');
371 $none = ts('-none-');
374 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
375 array('price' => json_encode(array($elementName, "0")))
379 $element = &$qf->addGroup($choice, $elementName, $label);
381 // make contribution field required for quick config when membership block is enabled
382 if (($field->name
== 'contribution_amount' ||
$field->name
== 'membership_amount') && property_exists($qf, '_membershipBlock') && !empty($qf->_membershipBlock
) && !$field->is_required
) {
383 $useRequired = $field->is_required
= TRUE;
386 if ($useRequired && $field->is_required
) {
387 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
392 $selectOption = $allowedOptions = $priceVal = array();
394 foreach ($customOption as $opt) {
395 $count = CRM_Utils_Array
::value('count', $opt, '');
396 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
397 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
399 if ($field->is_display_amounts
) {
400 $opt['label'] .= ' - ';
401 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
403 $selectOption[$opt['id']] = $opt['label'];
405 if (!in_array($opt['id'], $freezeOptions)) {
406 $allowedOptions[] = $opt['id'];
409 $element = &$qf->add('select', $elementName, $label,
411 '' => ts('- select -')) +
$selectOption,
412 $useRequired && $field->is_required
,
413 array('price' => json_encode($priceVal))
417 $button = substr($qf->controller
->getButtonName(), -4);
418 if (!empty($freezeOptions) && $button != 'skip') {
419 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
426 foreach ($customOption as $opId => $opt) {
427 $count = CRM_Utils_Array
::value('count', $opt, '');
428 $max_value = CRM_Utils_Array
::value('max_value', $opt, '');
429 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
431 if ($field->is_display_amounts
) {
432 $opt['label'] .= ' - ';
433 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
435 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
437 'price' => json_encode(array($opt['id'], $priceVal)),
438 'data-amount' => $opt[$valueFieldName],
439 'data-currency' => $currencyName,
444 if (in_array($opId, $freezeOptions)) {
445 $check[$opId]->freeze();
448 $element = &$qf->addGroup($check, $elementName, $label);
449 if ($useRequired && $field->is_required
) {
450 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
454 if (isset($qf->_online
) && $qf->_online
) {
460 * Retrieve a list of options for the specified field
462 * @param int $fieldId
464 * @param bool $inactiveNeeded
465 * Include inactive options.
467 * Ignore stored values\.
469 * @return array array of options
471 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
472 static $options = array();
474 if ($reset ||
empty($options[$fieldId])) {
476 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue
::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
477 $options[$fieldId] = $values;
480 return $options[$fieldId];
484 * @param $optionLabel
489 public static function getOptionId($optionLabel, $fid) {
490 if (!$optionLabel ||
!$fid) {
494 $optionGroupName = "civicrm_price_field.amount.{$fid}";
498 option_value.id as id
500 civicrm_option_value option_value,
501 civicrm_option_group option_group
503 option_group.name = %1
504 AND option_group.id = option_value.option_group_id
505 AND option_value.label = %2";
507 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($optionGroupName, 'String'), 2 => array($optionLabel, 'String')));
509 while ($dao->fetch()) {
515 * Delete the price set field.
525 public static function deleteField($id) {
526 $field = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
529 if ($field->find(TRUE)) {
530 // delete the options for this field
531 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue
::deleteValues($id);
533 // reorder the weight before delete
534 $fieldValues = array('price_set_id' => $field->price_set_id
);
536 CRM_Utils_Weight
::delWeight('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $field->id
, $fieldValues);
538 // now delete the field
539 return $field->delete();
548 public static function &htmlTypes() {
549 static $htmlTypes = NULL;
552 'Text' => ts('Text / Numeric Quantity'),
553 'Select' => ts('Select'),
554 'Radio' => ts('Radio'),
555 'CheckBox' => ts('CheckBox'),
562 * Validate the priceset
564 * @param int $priceSetId
567 * retrun the error string
575 public static function priceSetValidation($priceSetId, $fields, &$error) {
576 // check for at least one positive
577 // amount price field should be selected.
578 $priceField = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
579 $priceField->price_set_id
= $priceSetId;
582 $priceFields = array();
584 while ($priceField->fetch()) {
585 $key = "price_{$priceField->id}";
586 if (!empty($fields[$key])) {
587 $priceFields[$priceField->id
] = $fields[$key];
591 if (!empty($priceFields)) {
592 // we should has to have positive amount.
595 FROM civicrm_price_field
596 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
597 $fieldDAO = CRM_Core_DAO
::executeQuery($sql);
598 $htmlTypes = array();
599 while ($fieldDAO->fetch()) {
600 $htmlTypes[$fieldDAO->id
] = $fieldDAO->html_type
;
603 $selectedAmounts = array();
605 foreach ($htmlTypes as $fieldId => $type) {
607 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue
::getValues($fieldId, $options);
609 if (empty($options)) {
615 if ($type == 'Text') {
616 foreach ($options as $opId => $option) {
617 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
621 elseif (is_array($fields["price_{$fieldId}"])) {
622 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
623 $selectedAmounts[$opId] = $options[$opId]['amount'];
626 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
627 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
631 list($componentName) = explode(':', $fields['_qf_default']);
632 // now we have all selected amount in hand.
633 $totalAmount = array_sum($selectedAmounts);
634 if ($totalAmount < 0) {
635 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
639 $error['_qf_default'] = ts("Please select at least one option from price set.");