[REF] Refactor price field form to allow for unit testing of the form
[civicrm-core.git] / CRM / Price / Form / Option.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * form to process actions on the field aspect of Custom
20 */
21 class CRM_Price_Form_Option extends CRM_Core_Form {
22
23 /**
24 * The price field id saved to the session for an update.
25 *
26 * @var int
27 */
28 protected $_fid;
29
30 /**
31 * Option value id, used when editing the Option
32 *
33 * @var int
34 */
35 protected $_oid;
36
37 /**
38 * Array of Money fields
39 *
40 * @var array
41 */
42 protected $_moneyFields = ['amount', 'non_deductible_amount'];
43
44 /**
45 * Set variables up before form is built.
46 *
47 * @return void
48 */
49 public function preProcess() {
50 $this->setPageTitle(ts('Price Option'));
51 $this->_fid = CRM_Utils_Request::retrieve('fid', 'Positive',
52 $this
53 );
54 $this->_oid = CRM_Utils_Request::retrieve('oid', 'Positive',
55 $this
56 );
57 }
58
59 /**
60 * Set default values for the form. Note that in edit/view mode
61 * the default values are retrieved from the database
62 *
63 * @return array|void array of default values
64 */
65 public function setDefaultValues() {
66 if ($this->_action == CRM_Core_Action::DELETE) {
67 return NULL;
68 }
69 $defaults = [];
70
71 if (isset($this->_oid)) {
72 $params = ['id' => $this->_oid];
73
74 CRM_Price_BAO_PriceFieldValue::retrieve($params, $defaults);
75
76 // fix the display of the monetary value, CRM-4038
77 foreach ($this->_moneyFields as $field) {
78 // @todo use formatLocaleNumericRoundedByOptionalPrecision - but note that there is an issue where php doesn't handle
79 // money strings beyond a certain total length - per https://github.com/civicrm/civicrm-core/pull/18409
80 // & https://github.com/civicrm/civicrm-core/pull/18409
81 $defaults[$field] = CRM_Utils_Money::format(CRM_Utils_Array::value($field, $defaults), NULL, '%a');
82 }
83 }
84
85 $memberComponentId = CRM_Core_Component::getComponentID('CiviMember');
86 $extendComponentId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'extends', 'id');
87
88 if (!isset($defaults['membership_num_terms']) && $memberComponentId == $extendComponentId) {
89 $defaults['membership_num_terms'] = 1;
90 }
91 // set financial type used for price set to set default for new option
92 if (!$this->_oid) {
93 $defaults['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'financial_type_id', 'id');
94 }
95 if (!isset($defaults['weight']) || !$defaults['weight']) {
96 $fieldValues = ['price_field_id' => $this->_fid];
97 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Price_DAO_PriceFieldValue', $fieldValues);
98 $defaults['is_active'] = 1;
99 }
100
101 return $defaults;
102 }
103
104 /**
105 * Build the form object.
106 *
107 * @return void
108 */
109 public function buildQuickForm() {
110 if ($this->_action == CRM_Core_Action::UPDATE) {
111 $finTypeId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_oid, 'financial_type_id');
112 if (!CRM_Financial_BAO_FinancialType::checkPermissionToEditFinancialType($finTypeId)) {
113 CRM_Core_Error::statusBounce(ts("You do not have permission to access this page"));
114 }
115 }
116 if ($this->_action == CRM_Core_Action::DELETE) {
117 $this->addButtons([
118 [
119 'type' => 'next',
120 'name' => ts('Delete'),
121 ],
122 [
123 'type' => 'cancel',
124 'name' => ts('Cancel'),
125 ],
126 ]);
127 return NULL;
128 }
129 else {
130 $attributes = CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceFieldValue');
131 // lets trim all the whitespace
132 $this->applyFilter('__ALL__', 'trim');
133
134 // hidden Option Id for validation use
135 $this->add('hidden', 'optionId', $this->_oid);
136
137 // Needed for i18n dialog
138 $this->assign('optionId', $this->_oid);
139
140 //hidden field ID for validation use
141 $this->add('hidden', 'fieldId', $this->_fid);
142
143 // label
144 $this->add('text', 'label', ts('Option Label'), NULL, TRUE);
145 $memberComponentId = CRM_Core_Component::getComponentID('CiviMember');
146 if ($this->_action == CRM_Core_Action::UPDATE) {
147 $this->_sid = CRM_Utils_Request::retrieve('sid', 'Positive', $this);
148 }
149 elseif ($this->_action == CRM_Core_Action::ADD ||
150 $this->_action == CRM_Core_Action::VIEW
151 ) {
152 $this->_sid = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $this->_fid, 'price_set_id', 'id');
153 }
154 $this->isEvent = FALSE;
155 $extendComponentId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_sid, 'extends', 'id');
156 $this->assign('showMember', FALSE);
157 if ($memberComponentId == $extendComponentId) {
158 $this->assign('showMember', TRUE);
159 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
160 $this->add('select', 'membership_type_id', ts('Membership Type'), [
161 '' => ' ',
162 ] + $membershipTypes, FALSE,
163 ['onClick' => "calculateRowValues( );"]);
164 $this->add('number', 'membership_num_terms', ts('Number of Terms'), $attributes['membership_num_terms']);
165 }
166 else {
167 $allComponents = explode(CRM_Core_DAO::VALUE_SEPARATOR, $extendComponentId);
168 $eventComponentId = CRM_Core_Component::getComponentID('CiviEvent');
169 if (in_array($eventComponentId, $allComponents)) {
170 $this->isEvent = TRUE;
171 // count
172 $this->add('number', 'count', ts('Participant Count'));
173 $this->addRule('count', ts('Please enter a valid Max Participants.'), 'positiveInteger');
174
175 $this->add('number', 'max_value', ts('Max Participants'));
176 $this->addRule('max_value', ts('Please enter a valid Max Participants.'), 'positiveInteger');
177 }
178
179 }
180 //Financial Type
181 $financialType = CRM_Financial_BAO_FinancialType::getIncomeFinancialType();
182
183 if (count($financialType)) {
184 $this->assign('financialType', $financialType);
185 }
186 $this->add(
187 'select',
188 'financial_type_id',
189 ts('Financial Type'),
190 ['' => ts('- select -')] + $financialType,
191 TRUE
192 );
193
194 //CRM_Core_DAO::getFieldValue( 'CRM_Price_DAO_PriceField', $this->_fid, 'weight', 'id' );
195 // FIX ME: duplicate rule?
196 /*
197 $this->addRule( 'label',
198 ts('Duplicate option label.'),
199 'optionExists',
200 array( 'CRM_Core_DAO_OptionValue', $this->_oid, $this->_ogId, 'label' ) );
201 */
202
203 // value
204 $this->add('text', 'amount', ts('Option Amount'), NULL, TRUE);
205
206 // the above value is used directly by QF, so the value has to be have a rule
207 // please check with Lobo before u comment this
208 $this->registerRule('amount', 'callback', 'money', 'CRM_Utils_Rule');
209 $this->addRule('amount', ts('Please enter a monetary value for this field.'), 'money');
210
211 $this->add('text', 'non_deductible_amount', ts('Non-deductible Amount'), NULL);
212 $this->registerRule('non_deductible_amount', 'callback', 'money', 'CRM_Utils_Rule');
213 $this->addRule('non_deductible_amount', ts('Please enter a monetary value for this field.'), 'money');
214
215 $this->add('textarea', 'description', ts('Description'));
216 $this->add('textarea', 'help_pre', ts('Pre Option Help'));
217 $this->add('textarea', 'help_post', ts('Post Option Help'));
218
219 // weight
220 $this->add('number', 'weight', ts('Order'), NULL, TRUE);
221 $this->addRule('weight', ts('is a numeric field'), 'numeric');
222
223 // is active ?
224 $this->add('checkbox', 'is_active', ts('Active?'));
225
226 // is public?
227 $this->add('select', 'visibility_id', ts('Visibility'), CRM_Core_PseudoConstant::visibility());
228
229 //is default
230 $this->add('checkbox', 'is_default', ts('Default'));
231
232 if ($this->_fid) {
233 //hide the default checkbox option for text field
234 $htmlType = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceField', $this->_fid, 'html_type');
235 $this->assign('hideDefaultOption', FALSE);
236 if ($htmlType == 'Text') {
237 $this->assign('hideDefaultOption', TRUE);
238 }
239 }
240 // add buttons
241 $this->addButtons([
242 [
243 'type' => 'next',
244 'name' => ts('Save'),
245 ],
246 [
247 'type' => 'cancel',
248 'name' => ts('Cancel'),
249 ],
250 ]);
251
252 // if view mode pls freeze it with the done button.
253 if ($this->_action & CRM_Core_Action::VIEW) {
254 $this->freeze();
255 $this->addButtons([
256 [
257 'type' => 'cancel',
258 'name' => ts('Done'),
259 'isDefault' => TRUE,
260 ],
261 ]);
262 }
263 }
264
265 $this->addFormRule(['CRM_Price_Form_Option', 'formRule'], $this);
266 }
267
268 /**
269 * Global validation rules for the form.
270 *
271 * @param array $fields
272 * Posted values of the form.
273 *
274 * @param $files
275 * @param CRM_Core_Form $form
276 *
277 * @return array
278 * if errors then list of errors to be posted back to the form,
279 * true otherwise
280 */
281 public static function formRule($fields, $files, $form) {
282 $errors = [];
283 if (!empty($fields['count']) && !empty($fields['max_value']) &&
284 $fields['count'] > $fields['max_value']
285 ) {
286 $errors['count'] = ts('Participant count can not be greater than max participants.');
287 }
288
289 $priceField = CRM_Price_BAO_PriceField::findById($fields['fieldId']);
290 $visibilityOptions = CRM_Core_PseudoConstant::get('CRM_Price_BAO_PriceFieldValue', 'visibility_id', ['labelColumn' => 'name']);
291
292 $publicCount = 0;
293 $options = CRM_Price_BAO_PriceField::getOptions($priceField->id);
294 foreach ($options as $currentOption) {
295 if ($fields['optionId'] == $currentOption['id'] && $visibilityOptions[$fields['visibility_id']] == 'public') {
296 $publicCount++;
297 }
298 elseif ($fields['optionId'] != $currentOption['id'] && $visibilityOptions[$currentOption['visibility_id']] == 'public') {
299 $publicCount++;
300 }
301 }
302 if ($visibilityOptions[$priceField->visibility_id] == 'public' && $publicCount == 0 && $visibilityOptions[$fields['visibility_id']] == 'admin') {
303 $errors['visibility_id'] = ts('All other options for this \'Public\' field have \'Admin\' visibility. There should at least be one \'Public\' option, or make the field \'Admin\' only.');
304 }
305 elseif ($visibilityOptions[$priceField->visibility_id] == 'admin' && $visibilityOptions[$fields['visibility_id']] == 'public') {
306 $errors['visibility_id'] = ts('You must choose \'Admin\' visibility for this price option, as it belongs to a field with \'Admin\' visibility.');
307 }
308
309 return empty($errors) ? TRUE : $errors;
310 }
311
312 /**
313 * Process the form.
314 *
315 * @return void
316 */
317 public function postProcess() {
318 if ($this->_action == CRM_Core_Action::DELETE) {
319 $fieldValues = ['price_field_id' => $this->_fid];
320 $wt = CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceFieldValue', $this->_oid, $fieldValues);
321 $label = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue',
322 $this->_oid,
323 'label', 'id'
324 );
325
326 if (CRM_Price_BAO_PriceFieldValue::del($this->_oid)) {
327 CRM_Core_Session::setStatus(ts('%1 option has been deleted.', [1 => $label]), ts('Record Deleted'), 'success');
328 }
329 return NULL;
330 }
331 else {
332 $params = $this->controller->exportValues('Option');
333 $fieldLabel = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $this->_fid, 'label');
334
335 foreach ($this->_moneyFields as $field) {
336 $params[$field] = CRM_Utils_Rule::cleanMoney(trim($params[$field]));
337 }
338 $params['price_field_id'] = $this->_fid;
339 $params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE);
340 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
341 $params['visibility_id'] = CRM_Utils_Array::value('visibility_id', $params, FALSE);
342 $ids = [];
343 if ($this->_oid) {
344 $params['id'] = $this->_oid;
345 }
346 $optionValue = CRM_Price_BAO_PriceFieldValue::create($params, $ids);
347
348 CRM_Core_Session::setStatus(ts("The option '%1' has been saved.", [1 => $params['label']]), ts('Value Saved'), 'success');
349 }
350 }
351
352 }