Merge pull request #4898 from monishdeb/CRM-15619-fix
[civicrm-core.git] / CRM / Custom / Form / Option.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * form to process actions on the field aspect of Custom
38 */
39 class CRM_Custom_Form_Option extends CRM_Core_Form {
40
41 /**
42 * The custom field id saved to the session for an update
43 *
44 * @var int
45 */
46 protected $_fid;
47
48 /**
49 * The custom group id saved to the session for an update
50 *
51 * @var int
52 */
53 protected $_gid;
54
55 /**
56 * The option group ID
57 */
58 protected $_optionGroupID = NULL;
59
60 /**
61 * The Option id, used when editing the Option
62 *
63 * @var int
64 */
65 protected $_id;
66
67 /**
68 * Set variables up before form is built
69 *
70 * @param null
71 *
72 * @return void
73 */
74 public function preProcess() {
75 $this->_fid = CRM_Utils_Request::retrieve('fid', 'Positive', $this);
76
77 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this);
78
79 if (!isset($this->_gid) && $this->_fid) {
80 $this->_gid = CRM_Core_DAO::getFieldValue(
81 'CRM_Core_DAO_CustomField',
82 $this->_fid,
83 'custom_group_id'
84 );
85 }
86
87 if ($this->_fid) {
88 $this->_optionGroupID = CRM_Core_DAO::getFieldValue(
89 'CRM_Core_DAO_CustomField',
90 $this->_fid,
91 'option_group_id'
92 );
93 }
94
95 if ($isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_reserved', 'id')) {
96 CRM_Core_Error::fatal("You cannot add or edit muliple choice options in a reserved custom field-set.");
97 }
98
99 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
100 }
101
102 /**
103 * Set default values for the form. Note that in edit/view mode
104 * the default values are retrieved from the database
105 *
106 * @param null
107 *
108 * @return array
109 * array of default values
110 */
111 public function setDefaultValues() {
112 $defaults = $fieldDefaults = array();
113 if (isset($this->_id)) {
114 $params = array('id' => $this->_id);
115 CRM_Core_BAO_CustomOption::retrieve($params, $defaults);
116
117 $paramsField = array('id' => $this->_fid);
118 CRM_Core_BAO_CustomField::retrieve($paramsField, $fieldDefaults);
119
120 if ($fieldDefaults['html_type'] == 'CheckBox'
121 || $fieldDefaults['html_type'] == 'Multi-Select'
122 || $fieldDefaults['html_type'] == 'AdvMulti-Select'
123 ) {
124 if (!empty($fieldDefaults['default_value'])) {
125 $defaultCheckValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
126 substr($fieldDefaults['default_value'], 1, -1)
127 );
128 if (in_array($defaults['value'], $defaultCheckValues)) {
129 $defaults['default_value'] = 1;
130 }
131 }
132 }
133 else {
134 if (CRM_Utils_Array::value('default_value', $fieldDefaults) == CRM_Utils_Array::value('value', $defaults)) {
135 $defaults['default_value'] = 1;
136 }
137 }
138 }
139 else {
140 $defaults['is_active'] = 1;
141 }
142
143 if ($this->_action & CRM_Core_Action::ADD) {
144 $fieldValues = array('option_group_id' => $this->_optionGroupID);
145 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
146 }
147
148 return $defaults;
149 }
150
151 /**
152 * Build the form object
153 *
154 * @param null
155 *
156 * @return void
157 */
158 public function buildQuickForm() {
159 if ($this->_action == CRM_Core_Action::DELETE) {
160 $option = civicrm_api3('option_value', 'getsingle', array('id' => $this->_id));
161 $this->assign('label', $option['label']);
162 $this->addButtons(array(
163 array(
164 'type' => 'next',
165 'name' => ts('Delete'),
166 'isDefault' => TRUE,
167 ),
168 array(
169 'type' => 'cancel',
170 'name' => ts('Cancel'),
171 ),
172 )
173 );
174 }
175 else {
176 // lets trim all the whitespace
177 $this->applyFilter('__ALL__', 'trim');
178
179 // hidden Option Id for validation use
180 $this->add('hidden', 'optionId', $this->_id);
181
182 //hidden field ID for validation use
183 $this->add('hidden', 'fieldId', $this->_fid);
184
185 // label
186 $this->add('text', 'label', ts('Option Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'), TRUE);
187
188 $this->add('text', 'value', ts('Option Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'), TRUE);
189
190 // weight
191 $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'weight'), TRUE);
192 $this->addRule('weight', ts('is a numeric field'), 'numeric');
193
194 // is active ?
195 $this->add('checkbox', 'is_active', ts('Active?'));
196
197 // Set the default value for Custom Field
198 $this->add('checkbox', 'default_value', ts('Default'));
199
200 // add a custom form rule
201 $this->addFormRule(array('CRM_Custom_Form_Option', 'formRule'), $this);
202
203 // add buttons
204 $this->addButtons(array(
205 array(
206 'type' => 'next',
207 'name' => ts('Save'),
208 'isDefault' => TRUE,
209 ),
210 array(
211 'type' => 'next',
212 'name' => ts('Save and New'),
213 'subName' => 'new',
214 ),
215 array(
216 'type' => 'cancel',
217 'name' => ts('Cancel'),
218 ),
219 )
220 );
221
222 // if view mode pls freeze it with the done button.
223 if ($this->_action & CRM_Core_Action::VIEW) {
224 $this->freeze();
225 $url = CRM_Utils_System::url('civicrm/admin/custom/group/field/option',
226 'reset=1&action=browse&fid=' . $this->_fid . '&gid=' . $this->_gid,
227 TRUE, NULL, FALSE
228 );
229 $this->addElement('button',
230 'done',
231 ts('Done'),
232 array('onclick' => "location.href='$url'", 'class' => 'crm-form-submit')
233 );
234 }
235 }
236 $this->assign('id', $this->_id);
237 }
238
239 /**
240 * Global validation rules for the form
241 *
242 * @param array $fields
243 * Posted values of the form.
244 *
245 * @param $files
246 * @param CRM_Core_Form $form
247 *
248 * @return array
249 * list of errors to be posted back to the form
250 * @static
251 */
252 public static function formRule($fields, $files, $form) {
253 $optionLabel = $fields['label'];
254 $optionValue = $fields['value'];
255 $fieldId = $form->_fid;
256 $optionGroupId = $form->_optionGroupID;
257
258 $temp = array();
259 if (empty($form->_id)) {
260 $query = "
261 SELECT count(*)
262 FROM civicrm_option_value
263 WHERE option_group_id = %1
264 AND label = %2";
265 $params = array(
266 1 => array($optionGroupId, 'Integer'),
267 2 => array($optionLabel, 'String'),
268 );
269 if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
270 $errors['label'] = ts('There is an entry with the same label.');
271 }
272
273 $query = "
274 SELECT count(*)
275 FROM civicrm_option_value
276 WHERE option_group_id = %1
277 AND value = %2";
278 $params = array(
279 1 => array($optionGroupId, 'Integer'),
280 2 => array($optionValue, 'String'),
281 );
282 if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
283 $errors['value'] = ts('There is an entry with the same value.');
284 }
285 }
286 else {
287 //capture duplicate entries while updating Custom Options
288 $optionId = CRM_Utils_Type::escape($fields['optionId'], 'Integer');
289
290 //check label duplicates within a custom field
291 $query = "
292 SELECT count(*)
293 FROM civicrm_option_value
294 WHERE option_group_id = %1
295 AND id != %2
296 AND label = %3";
297 $params = array(
298 1 => array($optionGroupId, 'Integer'),
299 2 => array($optionId, 'Integer'),
300 3 => array($optionLabel, 'String'),
301 );
302 if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
303 $errors['label'] = ts('There is an entry with the same label.');
304 }
305
306 //check value duplicates within a custom field
307 $query = "
308 SELECT count(*)
309 FROM civicrm_option_value
310 WHERE option_group_id = %1
311 AND id != %2
312 AND value = %3";
313 $params = array(
314 1 => array($optionGroupId, 'Integer'),
315 2 => array($optionId, 'Integer'),
316 3 => array($optionValue, 'String'),
317 );
318 if (CRM_Core_DAO::singleValueQuery($query, $params) > 0) {
319 $errors['value'] = ts('There is an entry with the same value.');
320 }
321 }
322
323 $query = "
324 SELECT data_type
325 FROM civicrm_custom_field
326 WHERE id = %1";
327 $params = array(1 => array($fieldId, 'Integer'));
328 $dao = CRM_Core_DAO::executeQuery($query, $params);
329 if ($dao->fetch()) {
330 switch ($dao->data_type) {
331 case 'Int':
332 if (!CRM_Utils_Rule::integer($fields["value"])) {
333 $errors['value'] = ts('Please enter a valid integer value.');
334 }
335 break;
336
337 case 'Float':
338 // case 'Money':
339 if (!CRM_Utils_Rule::numeric($fields["value"])) {
340 $errors['value'] = ts('Please enter a valid number.');
341 }
342 break;
343
344 case 'Money':
345 if (!CRM_Utils_Rule::money($fields["value"])) {
346 $errors['value'] = ts('Please enter a valid value.');
347 }
348 break;
349
350 case 'Date':
351 if (!CRM_Utils_Rule::date($fields["value"])) {
352 $errors['value'] = ts('Please enter a valid date using YYYY-MM-DD format. Example: 2004-12-31.');
353 }
354 break;
355
356 case 'Boolean':
357 if (!CRM_Utils_Rule::integer($fields["value"]) &&
358 ($fields["value"] != '1' || $fields["value"] != '0')
359 ) {
360 $errors['value'] = ts('Please enter 1 or 0 as value.');
361 }
362 break;
363
364 case 'Country':
365 if (!empty($fields["value"])) {
366 $params = array(1 => array($fields['value'], 'String'));
367 $query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
368 if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
369 $errors['value'] = ts('Invalid default value for country.');
370 }
371 }
372 break;
373
374 case 'StateProvince':
375 if (!empty($fields["value"])) {
376 $params = array(1 => array($fields['value'], 'String'));
377 $query = "
378 SELECT count(*)
379 FROM civicrm_state_province
380 WHERE name = %1
381 OR abbreviation = %1";
382 if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
383 $errors['value'] = ts('The invalid value for State/Province data type');
384 }
385 }
386 break;
387 }
388 }
389
390 return empty($errors) ? TRUE : $errors;
391 }
392
393 /**
394 * Process the form
395 *
396 * @param null
397 *
398 * @return void
399 */
400 public function postProcess() {
401 // store the submitted values in an array
402 $params = $this->controller->exportValues('Option');
403
404 if ($this->_action == CRM_Core_Action::DELETE) {
405 $option = civicrm_api3('option_value', 'getsingle', array('id' => $this->_id));
406 $fieldValues = array('option_group_id' => $this->_optionGroupID);
407 CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
408 CRM_Core_BAO_CustomOption::del($this->_id);
409 CRM_Core_Session::setStatus(ts('Option "%1" has been deleted.', array(1 => $option['label'])), ts('Deleted'), 'success');
410 return;
411 }
412
413 // set values for custom field properties and save
414 $customOption = new CRM_Core_DAO_OptionValue();
415 $customOption->label = $params['label'];
416 $customOption->name = CRM_Utils_String::titleToVar($params['label']);
417 $customOption->weight = $params['weight'];
418 $customOption->value = $params['value'];
419 $customOption->is_active = CRM_Utils_Array::value('is_active', $params, FALSE);
420
421 $oldWeight = NULL;
422 if ($this->_id) {
423 $customOption->id = $this->_id;
424 CRM_Core_BAO_CustomOption::updateCustomValues($params);
425 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'weight', 'id');
426 }
427
428 $fieldValues = array('option_group_id' => $this->_optionGroupID);
429 $customOption->weight =
430 CRM_Utils_Weight::updateOtherWeights(
431 'CRM_Core_DAO_OptionValue',
432 $oldWeight,
433 $params['weight'],
434 $fieldValues);
435
436 $customOption->option_group_id = $this->_optionGroupID;
437
438 $customField = new CRM_Core_DAO_CustomField();
439 $customField->id = $this->_fid;
440 if (
441 $customField->find(TRUE) &&
442 (
443 $customField->html_type == 'CheckBox' ||
444 $customField->html_type == 'AdvMulti-Select' ||
445 $customField->html_type == 'Multi-Select'
446 )
447 ) {
448 $defVal = explode(
449 CRM_Core_DAO::VALUE_SEPARATOR,
450 substr($customField->default_value, 1, -1)
451 );
452 if (!empty($params['default_value'])) {
453 if (!in_array($customOption->value, $defVal)) {
454 if (empty($defVal[0])) {
455 $defVal = array($customOption->value);
456 }
457 else {
458 $defVal[] = $customOption->value;
459 }
460 $customField->default_value =
461 CRM_Core_DAO::VALUE_SEPARATOR .
462 implode(CRM_Core_DAO::VALUE_SEPARATOR, $defVal) .
463 CRM_Core_DAO::VALUE_SEPARATOR;
464 $customField->save();
465 }
466 }
467 elseif (in_array($customOption->value, $defVal)) {
468 $tempVal = array();
469 foreach ($defVal as $v) {
470 if ($v != $customOption->value) {
471 $tempVal[] = $v;
472 }
473 }
474
475 $customField->default_value =
476 CRM_Core_DAO::VALUE_SEPARATOR .
477 implode(CRM_Core_DAO::VALUE_SEPARATOR, $tempVal) .
478 CRM_Core_DAO::VALUE_SEPARATOR;
479 $customField->save();
480 }
481 }
482 else {
483 switch ($customField->data_type) {
484 case 'Money':
485 $customOption->value = CRM_Utils_Rule::cleanMoney($customOption->value);
486 break;
487
488 case 'Int':
489 $customOption->value = intval($customOption->value);
490 break;
491
492 case 'Float':
493 $customOption->value = floatval($customOption->value);
494 break;
495 }
496
497 if (!empty($params['default_value'])) {
498 $customField->default_value = $customOption->value;
499 $customField->save();
500 }
501 elseif ($customField->find(TRUE) && $customField->default_value == $customOption->value) {
502 // this is the case where this option is the current default value and we have been reset
503 $customField->default_value = 'null';
504 $customField->save();
505 }
506 }
507
508 $customOption->save();
509
510 $msg = ts('Your multiple choice option \'%1\' has been saved', array(1 => $customOption->label));
511 CRM_Core_Session::setStatus($msg, '', 'success');
512 $buttonName = $this->controller->getButtonName();
513 $session = CRM_Core_Session::singleton();
514 if ($buttonName == $this->getButtonName('next', 'new')) {
515 CRM_Core_Session::setStatus(ts('You can add another option.'), '', 'info');
516 $session->replaceUserContext(
517 CRM_Utils_System::url(
518 'civicrm/admin/custom/group/field/option',
519 'reset=1&action=add&fid=' . $this->_fid . '&gid=' . $this->_gid
520 )
521 );
522 }
523 }
524 }