Merge pull request #1955 from totten/master-smarty-perm
[civicrm-core.git] / CRM / Custom / Form / Option.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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
83 if (!isset($this->_gid) && $this->_fid) {
84 $this->_gid = CRM_Core_DAO::getFieldValue(
85 'CRM_Core_DAO_CustomField',
86 $this->_fid,
87 'custom_group_id'
88 );
89 }
90
91 if ($this->_fid) {
92 $this->_optionGroupID = CRM_Core_DAO::getFieldValue(
93 'CRM_Core_DAO_CustomField',
94 $this->_fid,
95 'option_group_id'
96 );
97 }
98
99 if ($isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_reserved', 'id')) {
100 CRM_Core_Error::fatal("You cannot add or edit muliple choice options in a reserved custom field-set.");
101 }
102
103 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
104 }
105
106 /**
107 * This function sets the default values for the form. Note that in edit/view mode
108 * the default values are retrieved from the database
109 *
110 * @param null
111 *
112 * @return array array of default values
113 * @access public
114 */
115 function setDefaultValues() {
116 $defaults = $fieldDefaults = array();
117 if (isset($this->_id)) {
118 $params = array('id' => $this->_id);
119 CRM_Core_BAO_CustomOption::retrieve($params, $defaults);
120
121 $paramsField = array('id' => $this->_fid);
122 CRM_Core_BAO_CustomField::retrieve($paramsField, $fieldDefaults);
123
124 if ($fieldDefaults['html_type'] == 'CheckBox'
125 || $fieldDefaults['html_type'] == 'Multi-Select'
126 || $fieldDefaults['html_type'] == 'AdvMulti-Select'
127 ) {
128 if (CRM_Utils_Array::value('default_value', $fieldDefaults)) {
129 $defaultCheckValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
130 substr($fieldDefaults['default_value'], 1, -1)
131 );
132 if (in_array($defaults['value'], $defaultCheckValues)) {
133 $defaults['default_value'] = 1;
134 }
135 }
136 }
137 else {
138 if (CRM_Utils_Array::value('default_value', $fieldDefaults) == CRM_Utils_Array::value('value', $defaults)) {
139 $defaults['default_value'] = 1;
140 }
141 }
142 }
143 else {
144 $defaults['is_active'] = 1;
145 }
146
147 if ($this->_action & CRM_Core_Action::ADD) {
148 $fieldValues = array('option_group_id' => $this->_optionGroupID);
149 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
150 }
151
152 return $defaults;
153 }
154
155 /**
156 * Function to actually build the form
157 *
158 * @param null
159 *
160 * @return void
161 * @access public
162 */
163 public function buildQuickForm() {
164 if ($this->_action == CRM_Core_Action::DELETE) {
165 $this->addButtons(array(
166 array(
167 'type' => 'next',
168 'name' => ts('Delete'),
169 'isDefault' => TRUE,
170 ),
171 array(
172 'type' => 'cancel',
173 'name' => ts('Cancel'),
174 ),
175 )
176 );
177 }
178 else {
179 // lets trim all the whitespace
180 $this->applyFilter('__ALL__', 'trim');
181
182 // hidden Option Id for validation use
183 $this->add('hidden', 'optionId', $this->_id);
184
185 //hidden field ID for validation use
186 $this->add('hidden', 'fieldId', $this->_fid);
187
188 // label
189 $this->add('text', 'label', ts('Option Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'), TRUE);
190
191 $this->add('text', 'value', ts('Option Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'), TRUE);
192
193 // weight
194 $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'weight'), TRUE);
195 $this->addRule('weight', ts('is a numeric field'), 'numeric');
196
197 // is active ?
198 $this->add('checkbox', 'is_active', ts('Active?'));
199
200 // Set the default value for Custom Field
201 $this->add('checkbox', 'default_value', ts('Default'));
202
203 // add a custom form rule
204 $this->addFormRule(array('CRM_Custom_Form_Option', 'formRule'), $this);
205
206 // add buttons
207 $this->addButtons(array(
208 array(
209 'type' => 'next',
210 'name' => ts('Save'),
211 'isDefault' => TRUE,
212 ),
213 array(
214 'type' => 'next',
215 'name' => ts('Save and New'),
216 'subName' => 'new',
217 ),
218 array(
219 'type' => 'cancel',
220 'name' => ts('Cancel'),
221 ),
222 )
223 );
224
225
226 // if view mode pls freeze it with the done button.
227 if ($this->_action & CRM_Core_Action::VIEW) {
228 $this->freeze();
229 $url = CRM_Utils_System::url('civicrm/admin/custom/group/field/option',
230 'reset=1&action=browse&fid=' . $this->_fid . '&gid=' . $this->_gid,
231 TRUE, NULL, FALSE
232 );
233 $this->addElement('button',
234 'done',
235 ts('Done'),
236 array('onclick' => "location.href='$url'", 'class' => 'form-submit')
237 );
238 }
239 }
240 $this->assign('id', $this->_id);
241 }
242
243 /**
244 * global validation rules for the form
245 *
246 * @param array $fields posted values of the form
247 *
248 * @return array list of errors to be posted back to the form
249 * @static
250 * @access public
251 */
252 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 value.');
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 * @access public
400 */
401 public function postProcess() {
402 // store the submitted values in an array
403 $params = $this->controller->exportValues('Option');
404
405 if ($this->_action == CRM_Core_Action::DELETE) {
406 $fieldValues = array('option_group_id' => $this->_optionGroupID);
407 $wt = 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('Your multiple choice option has been deleted'), 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 (CRM_Utils_Array::value('default_value', $params)) {
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 (CRM_Utils_Array::value('default_value', $params)) {
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 }
525