CRM-11864 - Options admin - improve user feedback
[civicrm-core.git] / CRM / Custom / Form / Field.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
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 */
39class CRM_Custom_Form_Field extends CRM_Core_Form {
40
41 /**
42 * Constants for number of options for data types of multiple option.
43 */
44 CONST NUM_OPTION = 11;
45
46 /**
47 * the custom group id saved to the session for an update
48 *
49 * @var int
50 * @access protected
51 */
52 protected $_gid;
53
54 /**
55 * The field id, used when editing the field
56 *
57 * @var int
58 * @access protected
59 */
60 protected $_id;
61
62 /**
63 * The default custom data/input types, when editing the field
64 *
65 * @var array
66 * @access protected
67 */
68 protected $_defaultDataType;
69
70 /**
71 * array of custom field values if update mode
72 */
73 protected $_values;
74
75 /**
76 * Array for valid combinations of data_type & html_type
77 *
78 * @var array
79 * @static
80 */
81 private static $_dataTypeValues = NULL;
82 private static $_dataTypeKeys = NULL;
83
84 private static $_dataToHTML = NULL;
85
86 private static $_dataToLabels = NULL;
87
88 /**
89 * Function to set variables up before form is built
90 *
91 * @param null
92 *
93 * @return void
94 * @access public
95 */
96 public function preProcess() {
97 if (!(self::$_dataTypeKeys)) {
98 self::$_dataTypeKeys = array_keys(CRM_Core_BAO_CustomField::dataType());
99 self::$_dataTypeValues = array_values(CRM_Core_BAO_CustomField::dataType());
100 }
101
102 if (!self::$_dataToHTML) {
103 self::$_dataToHTML = CRM_Core_BAO_CustomField::dataToHtml();
104 }
105
2b83aa0d
CW
106 //custom field id
107 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
108
109 $this->_values = array();
110 //get the values form db if update.
111 if ($this->_id) {
112 $params = array('id' => $this->_id);
113 CRM_Core_BAO_CustomField::retrieve($params, $this->_values);
114 // note_length is an alias for the text_length field
115 $this->_values['note_length'] = CRM_Utils_Array::value('text_length', $this->_values);
116 // custom group id
117 $this->_gid = $this->_values['custom_group_id'];
118 }
119 else {
120 // custom group id
121 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this);
122 }
6a488035 123
d06700a7 124 if ($isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_reserved', 'id')) {
e89941dc 125 CRM_Core_Error::fatal("You cannot add or edit fields in a reserved custom field-set.");
d06700a7
RN
126 }
127
6a488035
TO
128 if ($this->_gid) {
129 $url = CRM_Utils_System::url('civicrm/admin/custom/group/field',
130 "reset=1&action=browse&gid={$this->_gid}"
131 );
132
133 $session = CRM_Core_Session::singleton();
134 $session->pushUserContext($url);
135 }
136
6a488035
TO
137 if (self::$_dataToLabels == NULL) {
138 self::$_dataToLabels = array(
139 array('Text' => ts('Text'), 'Select' => ts('Select'),
140 'Radio' => ts('Radio'), 'CheckBox' => ts('CheckBox'), 'Multi-Select' => ts('Multi-Select'),
141 'AdvMulti-Select' => ts('Advanced Multi-Select'),
142 'Autocomplete-Select' => ts('Autocomplete Select'),
143 ),
144 array('Text' => ts('Text'), 'Select' => ts('Select'),
145 'Radio' => ts('Radio'),
146 ),
147 array('Text' => ts('Text'), 'Select' => ts('Select'),
148 'Radio' => ts('Radio'),
149 ),
150 array('Text' => ts('Text'), 'Select' => ts('Select'),
151 'Radio' => ts('Radio'),
152 ),
153 array('TextArea' => ts('TextArea'), 'RichTextEditor' => 'RichTextEditor'),
154 array('Date' => ts('Select Date')),
155 array('Radio' => ts('Radio')),
156 array('StateProvince' => ts('Select State/Province'), 'Multi-Select' => ts('Multi-Select State/Province')),
157 array('Country' => ts('Select Country'), 'Multi-Select' => ts('Multi-Select Country ')),
158 array('File' => ts('Select File')),
159 array('Link' => ts('Link')),
160 array('ContactReference' => ts('Autocomplete Select')),
161 );
162 }
163 }
164
165 /**
166 * This function sets the default values for the form. Note that in edit/view mode
167 * the default values are retrieved from the database
168 *
169 * @param null
170 *
171 * @return array array of default values
172 * @access public
173 */
174 function setDefaultValues() {
175 $defaults = $this->_values;
176
177 if ($this->_id) {
178 $this->assign('id', $this->_id);
179 $this->_gid = $defaults['custom_group_id'];
180
181 //get the value for state or country
182 if ($defaults['data_type'] == 'StateProvince' &&
183 $stateId = CRM_Utils_Array::value('default_value', $defaults)
184 ) {
185 $defaults['default_value'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_StateProvince', $stateId);
186 }
187 elseif ($defaults['data_type'] == 'Country' &&
188 $countryId = CRM_Utils_Array::value('default_value', $defaults)
189 ) {
190 $defaults['default_value'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Country', $countryId);
191 }
192
193 if ($defaults['data_type'] == 'ContactReference' && CRM_Utils_Array::value('filter', $defaults)) {
194 $contactRefFilter = 'Advance';
195 if (strpos($defaults['filter'], 'action=lookup') !== FALSE &&
196 strpos($defaults['filter'], 'group=') !== FALSE
197 ) {
198 $filterParts = explode('&', $defaults['filter']);
199
200 if (count($filterParts) == 2) {
201 $contactRefFilter = 'Group';
202 foreach ($filterParts as $part) {
203 if (strpos($part, 'group=') === FALSE) {
204 continue;
205 }
206 $groups = substr($part, strpos($part, '=') + 1);
207 foreach (explode(',', $groups) as $grp) {
208 if (CRM_Utils_Rule::positiveInteger($grp)) {
209 $defaults['group_id'][] = $grp;
210 }
211 }
212 }
213 }
214 }
215 $defaults['filter_selected'] = $contactRefFilter;
216 }
217
218 if (CRM_Utils_Array::value('data_type', $defaults)) {
219 $defaultDataType = array_search($defaults['data_type'],
220 self::$_dataTypeKeys
221 );
222 $defaultHTMLType = array_search($defaults['html_type'],
223 self::$_dataToHTML[$defaultDataType]
224 );
225 $defaults['data_type'] = array(
226 '0' => $defaultDataType,
227 '1' => $defaultHTMLType,
228 );
229 $this->_defaultDataType = $defaults['data_type'];
230 }
231
232 $defaults['option_type'] = 2;
233
234 $this->assign('changeFieldType', CRM_Custom_Form_ChangeFieldType::fieldTypeTransitions($this->_values['data_type'], $this->_values['html_type']));
235 }
236 else {
237 $defaults['is_active'] = 1;
238 $defaults['option_type'] = 1;
239 }
240
241 // set defaults for weight.
242 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
243 $defaults['option_status[' . $i . ']'] = 1;
244 $defaults['option_weight[' . $i . ']'] = $i;
245 }
246
247 if ($this->_action & CRM_Core_Action::ADD) {
248 $fieldValues = array('custom_group_id' => $this->_gid);
249 $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_CustomField', $fieldValues);
250
251 $defaults['text_length'] = 255;
252 $defaults['note_columns'] = 60;
253 $defaults['note_rows'] = 4;
254 $defaults['is_view'] = 0;
255 }
256
257 if (CRM_Utils_Array::value('html_type', $defaults)) {
258 $dontShowLink = substr($defaults['html_type'], -14) == 'State/Province' || substr($defaults['html_type'], -7) == 'Country' ? 1 : 0;
259 }
260
261 if (isset($dontShowLink)) {
262 $this->assign('dontShowLink', $dontShowLink);
263 }
264 return $defaults;
265 }
266
267 /**
268 * Function to actually build the form
269 *
270 * @param null
271 *
272 * @return void
273 * @access public
274 */
275 public function buildQuickForm() {
276 if ($this->_gid) {
277 $this->_title = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'title');
f84151fd 278 CRM_Utils_System::setTitle($this->_title . ' - ' . ($this->_id ? ts('Edit Field') : ts('Add Field')));
6a488035
TO
279 }
280
281 // lets trim all the whitespace
282 $this->applyFilter('__ALL__', 'trim');
283
284 $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_CustomField');
285
286 // label
287 $this->add('text',
288 'label',
289 ts('Field Label'),
290 $attributes['label'],
291 TRUE
292 );
293
294 $dt = &self::$_dataTypeValues;
295 $it = array();
296 foreach ($dt as $key => $value) {
297 $it[$key] = self::$_dataToLabels[$key];
298 }
299 $sel = &$this->addElement('hierselect',
300 'data_type',
301 ts('Data and Input Field Type'),
302 'onclick="clearSearchBoxes();custom_option_html_type(this.form)"; onBlur="custom_option_html_type(this.form)";',
303 '&nbsp;&nbsp;&nbsp;'
304 );
305 $sel->setOptions(array($dt, $it));
306 if ($this->_action == CRM_Core_Action::UPDATE) {
307 $this->freeze('data_type');
308 }
309 $includeFieldIds = NULL;
310 if ($this->_action == CRM_Core_Action::UPDATE) {
311 $includeFieldIds = $this->_values['id'];
312 }
313 $optionGroups = CRM_Core_BAO_CustomField::customOptionGroup($includeFieldIds);
314 $emptyOptGroup = FALSE;
315 if (empty($optionGroups)) {
316 $emptyOptGroup = TRUE;
317 $optionTypes = array('1' => ts('Create a new set of options'));
318 }
319 else {
320 $optionTypes = array('1' => ts('Create a new set of options'),
321 '2' => ts('Reuse an existing set'),
322 );
323
324 $this->add('select',
325 'option_group_id',
326 ts('Multiple Choice Option Sets'),
327 array(
328 '' => ts('- select -')) + $optionGroups
329 );
330 }
331
332 $element = &$this->addRadio('option_type',
333 ts('Option Type'),
334 $optionTypes,
335 array(
336 'onclick' => "showOptionSelect();"), '<br/>'
337 );
338
339
340 $contactGroups = CRM_Core_PseudoConstant::group();
341 asort($contactGroups);
342
343 $this->add('select',
344 'group_id',
345 ts('Limit List to Group'),
346 $contactGroups,
347 FALSE,
348 array('multiple' => 'multiple')
349 );
350
351 $this->add('text',
352 'filter',
353 ts('Advanced Filter'),
354 $attributes['filter']
355 );
356
357 $this->add('hidden', 'filter_selected', 'Group', array('id' => 'filter_selected'));
358
359 //if empty option group freeze the option type.
360 if ($emptyOptGroup) {
361 $element->freeze();
362 }
363
364 // form fields of Custom Option rows
365 $defaultOption = array();
366 $_showHide = new CRM_Core_ShowHideBlocks('', '');
367 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
368
369 //the show hide blocks
370 $showBlocks = 'optionField_' . $i;
371 if ($i > 2) {
372 $_showHide->addHide($showBlocks);
373 if ($i == self::NUM_OPTION) {
374 $_showHide->addHide('additionalOption');
375 }
376 }
377 else {
378 $_showHide->addShow($showBlocks);
379 }
380
381 $optionAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue');
382 // label
383 $this->add('text', 'option_label[' . $i . ']', ts('Label'),
384 $optionAttributes['label']
385 );
386
387 // value
388 $this->add('text', 'option_value[' . $i . ']', ts('Value'),
389 $optionAttributes['value']
390 );
391
392 // weight
393 $this->add('text', "option_weight[$i]", ts('Order'),
394 $optionAttributes['weight']
395 );
396
397 // is active ?
398 $this->add('checkbox', "option_status[$i]", ts('Active?'));
399
400 $defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i);
401
402 //for checkbox handling of default option
403 $this->add('checkbox', "default_checkbox_option[$i]", NULL);
404 }
405
406 //default option selection
407 $this->addGroup($defaultOption, 'default_option');
408
409 $_showHide->addToTemplate();
410
411 // text length for alpha numeric data types
412 $this->add('text',
413 'text_length',
414 ts('Database field length'),
415 $attributes['text_length'],
416 FALSE
417 );
418 $this->addRule('text_length', ts('Value should be a positive number'), 'integer');
419
420 $this->add('text',
421 'start_date_years',
422 ts('Dates may be up to'),
423 $attributes['start_date_years'],
424 FALSE
425 );
426 $this->add('text',
427 'end_date_years',
428 ts('Dates may be up to'),
429 $attributes['end_date_years'],
430 FALSE
431 );
432
433 $this->addRule('start_date_years', ts('Value should be a positive number'), 'integer');
434 $this->addRule('end_date_years', ts('Value should be a positive number'), 'integer');
435
436 $this->add('select', 'date_format', ts('Date Format'),
437 array('' => ts('- select -')) + CRM_Core_SelectValues::getDatePluginInputFormats()
438 );
439
440 $this->add('select', 'time_format', ts('Time'),
441 array('' => ts('- none -')) + CRM_Core_SelectValues::getTimeFormats()
442 );
443
444 // for Note field
445 $this->add('text',
446 'note_columns',
447 ts('Width (columns)') . ' ',
448 $attributes['note_columns'],
449 FALSE
450 );
451 $this->add('text',
452 'note_rows',
453 ts('Height (rows)') . ' ',
454 $attributes['note_rows'],
455 FALSE
456 );
2f940a36
NG
457 $this->add('text',
458 'note_length',
459 ts('Maximum length') . ' ',
460 $attributes['text_length'], // note_length is an alias for the text-length field
461 FALSE
462 );
6a488035
TO
463
464 $this->addRule('note_columns', ts('Value should be a positive number'), 'positiveInteger');
465 $this->addRule('note_rows', ts('Value should be a positive number'), 'positiveInteger');
2f940a36 466 $this->addRule('note_length', ts('Value should be a positive number'), 'positiveInteger');
6a488035
TO
467
468 // weight
469 $this->add('text', 'weight', ts('Order'),
470 $attributes['weight'],
471 TRUE
472 );
473 $this->addRule('weight', ts('is a numeric field'), 'numeric');
474
475 // is required ?
476 $this->add('checkbox', 'is_required', ts('Required?'));
477
478 // checkbox / radio options per line
479 $this->add('text', 'options_per_line', ts('Options Per Line'));
480 $this->addRule('options_per_line', ts('must be a numeric value'), 'numeric');
481
482 // default value, help pre, help post, mask, attributes, javascript ?
483 $this->add('text', 'default_value', ts('Default Value'),
484 $attributes['default_value']
485 );
486 $this->add('textarea', 'help_pre', ts('Field Pre Help'),
487 $attributes['help_pre']
488 );
489 $this->add('textarea', 'help_post', ts('Field Post Help'),
490 $attributes['help_post']
491 );
492 $this->add('text', 'mask', ts('Mask'),
493 $attributes['mask']
494 );
495
496 // is active ?
497 $this->add('checkbox', 'is_active', ts('Active?'));
498
499 // is active ?
500 $this->add('checkbox', 'is_view', ts('View Only?'));
501
502 // is searchable ?
503 $this->addElement('checkbox',
504 'is_searchable',
505 ts('Is this Field Searchable?'),
506 NULL, array('onclick' => "showSearchRange(this)")
507 );
508
509 // is searchable by range?
510 $searchRange = array();
511 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('Yes'), '1');
512 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('No'), '0');
513
514 $this->addGroup($searchRange, 'is_search_range', ts('Search by Range?'));
515
516 // add buttons
517 $this->addButtons(array(
518 array(
519 'type' => 'next',
520 'name' => ts('Save'),
521 'isDefault' => TRUE,
522 ),
523 array(
524 'type' => 'next',
525 'name' => ts('Save and New'),
526 'subName' => 'new',
527 ),
528 array(
529 'type' => 'cancel',
530 'name' => ts('Cancel'),
531 ),
532 )
533 );
534
535 // add a form rule to check default value
536 $this->addFormRule(array('CRM_Custom_Form_Field', 'formRule'), $this);
537
538 // if view mode pls freeze it with the done button.
539 if ($this->_action & CRM_Core_Action::VIEW) {
540 $this->freeze();
541 $url = CRM_Utils_System::url('civicrm/admin/custom/group/field', 'reset=1&action=browse&gid=' . $this->_gid);
542 $this->addElement('button',
543 'done',
544 ts('Done'),
545 array('onclick' => "location.href='$url'")
546 );
547 }
548 }
549
550 /**
551 * global validation rules for the form
552 *
553 * @param array $fields (referance) posted values of the form
554 *
555 * @return array if errors then list of errors to be posted back to the form,
556 * true otherwise
557 * @static
558 * @access public
559 */
560 static function formRule($fields, $files, $self) {
561 $default = CRM_Utils_Array::value('default_value', $fields);
562
563 $errors = array();
564
565 //validate field label as well as name.
566 $title = $fields['label'];
567 $name = CRM_Utils_String::munge($title, '_', 64);
e1069955 568 $gId = $self->_gid; // CRM-7564
8ef12e64 569 $query = 'select count(*) from civicrm_custom_field where ( name like %1 OR label like %2 ) and id != %3 and custom_group_id = %4';
6a488035
TO
570 $fldCnt = CRM_Core_DAO::singleValueQuery($query, array(1 => array($name, 'String'),
571 2 => array($title, 'String'),
572 3 => array((int)$self->_id, 'Integer'),
e1069955 573 4 => array($gId, 'Integer'),
6a488035
TO
574 ));
575 if ($fldCnt) {
576 $errors['label'] = ts('Custom field \'%1\' already exists in Database.', array(1 => $title));
577 }
578
579 //checks the given custom field name doesnot start with digit
580 if (!empty($title)) {
581 // gives the ascii value
582 $asciiValue = ord($title{0});
583 if ($asciiValue >= 48 && $asciiValue <= 57) {
584 $errors['label'] = ts("Field's Name should not start with digit");
585 }
586 }
587
588 // ensure that the label is not 'id'
589 if (strtolower($title) == 'id') {
590 $errors['label'] = ts("You cannot use 'id' as a field label.");
591 }
592
593 if (!isset($fields['data_type'][0]) || !isset($fields['data_type'][1])) {
594 $errors['_qf_default'] = ts('Please enter valid - Data and Input Field Type.');
595 }
596
597 $dataType = self::$_dataTypeKeys[$fields['data_type'][0]];
598
599 if ($default || $dataType == 'ContactReference') {
600 switch ($dataType) {
601 case 'Int':
602 if (!CRM_Utils_Rule::integer($default)) {
603 $errors['default_value'] = ts('Please enter a valid integer as default value.');
604 }
605 break;
606
607 case 'Float':
608 if (!CRM_Utils_Rule::numeric($default)) {
609 $errors['default_value'] = ts('Please enter a valid number as default value.');
610 }
611 break;
612
613 case 'Money':
614 if (!CRM_Utils_Rule::money($default)) {
615 $errors['default_value'] = ts('Please enter a valid number value.');
616 }
617 break;
618
619 case 'Link':
620 if (!CRM_Utils_Rule::url($default)) {
621 $errors['default_value'] = ts('Please enter a valid link.');
622 }
623 break;
624
625 case 'Date':
626 if (!CRM_Utils_Rule::date($default)) {
627 $errors['default_value'] = ts('Please enter a valid date as default value using YYYY-MM-DD format. Example: 2004-12-31.');
628 }
629 break;
630
631 case 'Boolean':
632 if ($default != '1' && $default != '0') {
633 $errors['default_value'] = ts('Please enter 1 (for Yes) or 0 (for No) if you want to set a default value.');
634 }
635 break;
636
637 case 'Country':
638 if (!empty($default)) {
639 $query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
640 $params = array(1 => array($fields['default_value'], 'String'));
641 if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
642 $errors['default_value'] = ts('Invalid default value for country.');
643 }
644 }
645 break;
646
647 case 'StateProvince':
648 if (!empty($default)) {
649 $query = "
8ef12e64 650SELECT count(*)
6a488035
TO
651 FROM civicrm_state_province
652 WHERE name = %1
653 OR abbreviation = %1";
654 $params = array(1 => array($fields['default_value'], 'String'));
655 if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
656 $errors['default_value'] = ts('The invalid default value for State/Province data type');
657 }
658 }
659 break;
660
661 case 'ContactReference':
662 if ($fields['filter_selected'] == 'Advance' &&
663 CRM_Utils_Array::value('filter', $fields)
664 ) {
665 if (strpos($fields['filter'], 'entity=') !== FALSE) {
666 $errors['filter'] = ts("Please do not include entity parameter (entity is always 'contact')");
667 }
668 elseif (strpos($fields['filter'], 'action=') === FALSE) {
669 $errors['filter'] = ts("Please specify 'action' parameter, it should be 'lookup' or 'get'");
670 }
671 elseif (strpos($fields['filter'], 'action=get') === FALSE &&
672 strpos($fields['filter'], 'action=lookup') === FALSE
673 ) {
674 $errors['filter'] = ts("Only 'get' and 'lookup' actions are supported.");
675 }
676 }
677 $self->setDefaults(array('filter_selected', $fields['filter_selected']));
678 break;
679 }
680 }
681
682 if (self::$_dataTypeKeys[$fields['data_type'][0]] == 'Date') {
683 if (!$fields['date_format']) {
684 $errors['date_format'] = ts('Please select a date format.');
685 }
686 }
687
688 /** Check the option values entered
689 * Appropriate values are required for the selected datatype
690 * Incomplete row checking is also required.
691 */
692 $_flagOption = $_rowError = 0;
693 $_showHide = new CRM_Core_ShowHideBlocks('', '');
694 $dataType = self::$_dataTypeKeys[$fields['data_type'][0]];
695 if (isset($fields['data_type'][1])) {
696 $dataField = $fields['data_type'][1];
697 }
698 $optionFields = array('Select', 'Multi-Select', 'CheckBox', 'Radio', 'AdvMulti-Select');
699
36d1ff7f 700 if (isset($fields['option_type']) && $fields['option_type'] == 1) {
6a488035
TO
701 //capture duplicate Custom option values
702 if (!empty($fields['option_value'])) {
703 $countValue = count($fields['option_value']);
704 $uniqueCount = count(array_unique($fields['option_value']));
705
706 if ($countValue > $uniqueCount) {
707
708 $start = 1;
709 while ($start < self::NUM_OPTION) {
710 $nextIndex = $start + 1;
711 while ($nextIndex <= self::NUM_OPTION) {
712 if ($fields['option_value'][$start] == $fields['option_value'][$nextIndex] &&
713 !empty($fields['option_value'][$nextIndex])
714 ) {
715 $errors['option_value[' . $start . ']'] = ts('Duplicate Option values');
716 $errors['option_value[' . $nextIndex . ']'] = ts('Duplicate Option values');
717 $_flagOption = 1;
718 }
719 $nextIndex++;
720 }
721 $start++;
722 }
723 }
724 }
725
726 //capture duplicate Custom Option label
727 if (!empty($fields['option_label'])) {
728 $countValue = count($fields['option_label']);
729 $uniqueCount = count(array_unique($fields['option_label']));
730
731 if ($countValue > $uniqueCount) {
732 $start = 1;
733 while ($start < self::NUM_OPTION) {
734 $nextIndex = $start + 1;
735 while ($nextIndex <= self::NUM_OPTION) {
736 if ($fields['option_label'][$start] == $fields['option_label'][$nextIndex] &&
737 !empty($fields['option_label'][$nextIndex])
738 ) {
739 $errors['option_label[' . $start . ']'] = ts('Duplicate Option label');
740 $errors['option_label[' . $nextIndex . ']'] = ts('Duplicate Option label');
741 $_flagOption = 1;
742 }
743 $nextIndex++;
744 }
745 $start++;
746 }
747 }
748 }
749
750 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
751 if (!$fields['option_label'][$i]) {
752 if ($fields['option_value'][$i]) {
753 $errors['option_label[' . $i . ']'] = ts('Option label cannot be empty');
754 $_flagOption = 1;
755 }
756 else {
757 $_emptyRow = 1;
758 }
759 }
760 else {
761 if (!strlen(trim($fields['option_value'][$i]))) {
762 if (!$fields['option_value'][$i]) {
763 $errors['option_value[' . $i . ']'] = ts('Option value cannot be empty');
764 $_flagOption = 1;
765 }
766 }
767 }
768
769 if ($fields['option_value'][$i] && $dataType != 'String') {
770 if ($dataType == 'Int') {
771 if (!CRM_Utils_Rule::integer($fields['option_value'][$i])) {
772 $_flagOption = 1;
773 $errors['option_value[' . $i . ']'] = ts('Please enter a valid integer.');
774 }
775 }
776 elseif ($dataType == 'Money') {
777 if (!CRM_Utils_Rule::money($fields['option_value'][$i])) {
778 $_flagOption = 1;
779 $errors['option_value[' . $i . ']'] = ts('Please enter a valid money value.');
780 }
781 }
782 else {
783 if (!CRM_Utils_Rule::numeric($fields['option_value'][$i])) {
784 $_flagOption = 1;
785 $errors['option_value[' . $i . ']'] = ts('Please enter a valid number.');
786 }
787 }
788 }
789
790 $showBlocks = 'optionField_' . $i;
791 if ($_flagOption) {
792 $_showHide->addShow($showBlocks);
793 $_rowError = 1;
794 }
795
796 if (!empty($_emptyRow)) {
797 $_showHide->addHide($showBlocks);
798 }
799 else {
800 $_showHide->addShow($showBlocks);
801 }
802 if ($i == self::NUM_OPTION) {
803 $hideBlock = 'additionalOption';
804 $_showHide->addHide($hideBlock);
805 }
806
807 $_flagOption = $_emptyRow = 0;
808 }
809 }
810 elseif (isset($dataField) &&
811 in_array($dataField, $optionFields) &&
812 !in_array($dataType, array('Boolean', 'Country', 'StateProvince'))
813 ) {
814 if (!$fields['option_group_id']) {
815 $errors['option_group_id'] = ts('You must select a Multiple Choice Option set if you chose Reuse an existing set.');
816 }
817 else {
818 $query = "
819SELECT count(*)
820FROM civicrm_custom_field
821WHERE data_type != %1
822AND option_group_id = %2";
823 $params = array(
824 1 => array(self::$_dataTypeKeys[$fields['data_type'][0]],
825 'String',
826 ),
827 2 => array($fields['option_group_id'], 'Integer'),
828 );
829 $count = CRM_Core_DAO::singleValueQuery($query, $params);
830 if ($count > 0) {
831 $errors['option_group_id'] = ts('The data type of the multiple choice option set you\'ve selected does not match the data type assigned to this field.');
832 }
833 }
834 }
835
836 $assignError = new CRM_Core_Page();
837 if ($_rowError) {
838 $_showHide->addToTemplate();
839 $assignError->assign('optionRowError', $_rowError);
840 }
841 else {
842 if (isset($fields['data_type'][1])) {
843 switch (self::$_dataToHTML[$fields['data_type'][0]][$fields['data_type'][1]]) {
844 case 'Radio':
845 $_fieldError = 1;
846 $assignError->assign('fieldError', $_fieldError);
847 break;
848
849 case 'Checkbox':
850 $_fieldError = 1;
851 $assignError->assign('fieldError', $_fieldError);
852 break;
853
854 case 'Select':
855 $_fieldError = 1;
856 $assignError->assign('fieldError', $_fieldError);
857 break;
858
859 default:
860 $_fieldError = 0;
861 $assignError->assign('fieldError', $_fieldError);
862 }
863 }
864
865 for ($idx = 1; $idx <= self::NUM_OPTION; $idx++) {
866 $showBlocks = 'optionField_' . $idx;
867 if (!empty($fields['option_label'][$idx])) {
868 $_showHide->addShow($showBlocks);
869 }
870 else {
871 $_showHide->addHide($showBlocks);
872 }
873 }
874 $_showHide->addToTemplate();
875 }
876
877 // we can not set require and view at the same time.
878 if (CRM_Utils_Array::value('is_required', $fields) &&
879 CRM_Utils_Array::value('is_view', $fields)
880 ) {
881 $errors['is_view'] = ts('Can not set this field Required and View Only at the same time.');
882 }
883
884 return empty($errors) ? TRUE : $errors;
885 }
886
887 /**
888 * Process the form
889 *
890 * @param null
891 *
892 * @return void
893 * @access public
894 */
895 public function postProcess() {
896 // store the submitted values in an array
897 $params = $this->controller->exportValues($this->_name);
898 if ($this->_action == CRM_Core_Action::UPDATE) {
899 $dataTypeKey = $this->_defaultDataType[0];
900 $params['data_type'] = self::$_dataTypeKeys[$this->_defaultDataType[0]];
901 $params['html_type'] = self::$_dataToHTML[$this->_defaultDataType[0]][$this->_defaultDataType[1]];
902 }
903 else {
904 $dataTypeKey = $params['data_type'][0];
905 $params['html_type'] = self::$_dataToHTML[$params['data_type'][0]][$params['data_type'][1]];
906 $params['data_type'] = self::$_dataTypeKeys[$params['data_type'][0]];
907 }
908
909 //fix for 'is_search_range' field.
910 if (in_array($dataTypeKey, array(
911 1, 2, 3, 5))) {
912 if (!CRM_Utils_Array::value('is_searchable', $params)) {
913 $params['is_search_range'] = 0;
914 }
915 }
916 else {
917 $params['is_search_range'] = 0;
918 }
919
920 $filter = 'null';
921 if ($dataTypeKey == 11 && CRM_Utils_Array::value('filter_selected', $params)) {
922 if ($params['filter_selected'] == 'Advance' && trim(CRM_Utils_Array::value('filter', $params))) {
923 $filter = trim($params['filter']);
924 }
925 elseif ($params['filter_selected'] == 'Group' && CRM_Utils_Array::value('group_id', $params)) {
926
927 $filter = 'action=lookup&group=' . implode(',', $params['group_id']);
928 }
929 }
930 $params['filter'] = $filter;
931
932 // fix for CRM-316
933 $oldWeight = NULL;
934 if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
935 $fieldValues = array('custom_group_id' => $this->_gid);
936 if ($this->_id) {
937 $oldWeight = $this->_values['weight'];
938 }
939 $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_CustomField', $oldWeight, $params['weight'], $fieldValues);
940 }
941
942 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
943
944 //store the primary key for State/Province or Country as default value.
945 if (strlen(trim($params['default_value']))) {
946 switch ($params['data_type']) {
947 case 'StateProvince':
948 $fieldStateProvince = $strtolower($params['default_value']);
949 $query = "
950SELECT id
8ef12e64 951 FROM civicrm_state_province
952 WHERE LOWER(name) = '$fieldStateProvince'
6a488035
TO
953 OR abbreviation = '$fieldStateProvince'";
954 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
955 if ($dao->fetch()) {
956 $params['default_value'] = $dao->id;
957 }
958 break;
959
960 case 'Country':
961 $fieldCountry = $strtolower($params['default_value']);
962 $query = "
963SELECT id
964 FROM civicrm_country
8ef12e64 965 WHERE LOWER(name) = '$fieldCountry'
6a488035
TO
966 OR iso_code = '$fieldCountry'";
967 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
968 if ($dao->fetch()) {
969 $params['default_value'] = $dao->id;
970 }
971 break;
972 }
973 }
974
2f940a36
NG
975 // The text_length attribute for Memo fields is in a different input as there
976 // are different label, help text and default value than for other type fields
977 if ($params['data_type'] == "Memo") {
978 $params['text_length'] = $params['note_length'];
979 }
980
6a488035
TO
981 // need the FKEY - custom group id
982 $params['custom_group_id'] = $this->_gid;
983
984 if ($this->_action & CRM_Core_Action::UPDATE) {
985 $params['id'] = $this->_id;
986 }
987
988 $customField = CRM_Core_BAO_CustomField::create($params);
f84151fd 989 $this->_id = $customField->id;
6a488035
TO
990
991 // reset the cache
992 CRM_Core_BAO_Cache::deleteGroup('contact fields');
993
0b1bae4a 994 $msg = '<p>' . ts("Custom field '%1' has been saved.", array(1 => $customField->label)) . '</p>';
6a488035
TO
995
996 $buttonName = $this->controller->getButtonName();
997 $session = CRM_Core_Session::singleton();
998 if ($buttonName == $this->getButtonName('next', 'new')) {
0b1bae4a 999 $msg += '<p>' . ts("Ready to add another.") . '</p>';
6a488035
TO
1000 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field/add',
1001 'reset=1&action=add&gid=' . $this->_gid
1002 ));
1003 }
1004 else {
1005 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field',
1006 'reset=1&action=browse&gid=' . $this->_gid
1007 ));
1008 }
0b1bae4a
CW
1009 $session->setStatus($msg, ts('Saved'), 'success');
1010
1011 // Add data when in ajax contect
1012 $this->ajaxResponse['customField'] = $customField->toArray();
6a488035
TO
1013 }
1014}
1015