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