Merge branch '4.4' of https://github.com/civicrm/civicrm-core
[civicrm-core.git] / CRM / Custom / Form / Field.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_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
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 }
123
124 if ($isReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid, 'is_reserved', 'id')) {
125 CRM_Core_Error::fatal("You cannot add or edit fields in a reserved custom field-set.");
126 }
127
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
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');
278 CRM_Utils_System::setTitle($this->_title . ' - ' . ($this->_id ? ts('Edit Field') : ts('Add Field')));
279 $this->assign('gid', $this->_gid);
280 }
281
282 // lets trim all the whitespace
283 $this->applyFilter('__ALL__', 'trim');
284
285 $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_CustomField');
286
287 // label
288 $this->add('text',
289 'label',
290 ts('Field Label'),
291 $attributes['label'],
292 TRUE
293 );
294
295 $dt = &self::$_dataTypeValues;
296 $it = array();
297 foreach ($dt as $key => $value) {
298 $it[$key] = self::$_dataToLabels[$key];
299 }
300 $sel = &$this->addElement('hierselect',
301 'data_type',
302 ts('Data and Input Field Type'),
303 'onclick="clearSearchBoxes();custom_option_html_type(this.form)"; onBlur="custom_option_html_type(this.form)";',
304 '&nbsp;&nbsp;&nbsp;'
305 );
306 $sel->setOptions(array($dt, $it));
307 if ($this->_action == CRM_Core_Action::UPDATE) {
308 $this->freeze('data_type');
309 }
310 $includeFieldIds = NULL;
311 if ($this->_action == CRM_Core_Action::UPDATE) {
312 $includeFieldIds = $this->_values['id'];
313 }
314 $optionGroups = CRM_Core_BAO_CustomField::customOptionGroup($includeFieldIds);
315 $emptyOptGroup = FALSE;
316 if (empty($optionGroups)) {
317 $emptyOptGroup = TRUE;
318 $optionTypes = array('1' => ts('Create a new set of options'));
319 }
320 else {
321 $optionTypes = array('1' => ts('Create a new set of options'),
322 '2' => ts('Reuse an existing set'),
323 );
324
325 $this->add('select',
326 'option_group_id',
327 ts('Multiple Choice Option Sets'),
328 array(
329 '' => ts('- select -')) + $optionGroups
330 );
331 }
332
333 $element = &$this->addRadio('option_type',
334 ts('Option Type'),
335 $optionTypes,
336 array(
337 'onclick' => "showOptionSelect();"), '<br/>'
338 );
339
340
341 $contactGroups = CRM_Core_PseudoConstant::group();
342 asort($contactGroups);
343
344 $this->add('select',
345 'group_id',
346 ts('Limit List to Group'),
347 $contactGroups,
348 FALSE,
349 array('multiple' => 'multiple')
350 );
351
352 $this->add('text',
353 'filter',
354 ts('Advanced Filter'),
355 $attributes['filter']
356 );
357
358 $this->add('hidden', 'filter_selected', 'Group', array('id' => 'filter_selected'));
359
360 //if empty option group freeze the option type.
361 if ($emptyOptGroup) {
362 $element->freeze();
363 }
364
365 // form fields of Custom Option rows
366 $defaultOption = array();
367 $_showHide = new CRM_Core_ShowHideBlocks('', '');
368 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
369
370 //the show hide blocks
371 $showBlocks = 'optionField_' . $i;
372 if ($i > 2) {
373 $_showHide->addHide($showBlocks);
374 if ($i == self::NUM_OPTION) {
375 $_showHide->addHide('additionalOption');
376 }
377 }
378 else {
379 $_showHide->addShow($showBlocks);
380 }
381
382 $optionAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue');
383 // label
384 $this->add('text', 'option_label[' . $i . ']', ts('Label'),
385 $optionAttributes['label']
386 );
387
388 // value
389 $this->add('text', 'option_value[' . $i . ']', ts('Value'),
390 $optionAttributes['value']
391 );
392
393 // weight
394 $this->add('text', "option_weight[$i]", ts('Order'),
395 $optionAttributes['weight']
396 );
397
398 // is active ?
399 $this->add('checkbox', "option_status[$i]", ts('Active?'));
400
401 $defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i);
402
403 //for checkbox handling of default option
404 $this->add('checkbox', "default_checkbox_option[$i]", NULL);
405 }
406
407 //default option selection
408 $this->addGroup($defaultOption, 'default_option');
409
410 $_showHide->addToTemplate();
411
412 // text length for alpha numeric data types
413 $this->add('text',
414 'text_length',
415 ts('Database field length'),
416 $attributes['text_length'],
417 FALSE
418 );
419 $this->addRule('text_length', ts('Value should be a positive number'), 'integer');
420
421 $this->add('text',
422 'start_date_years',
423 ts('Dates may be up to'),
424 $attributes['start_date_years'],
425 FALSE
426 );
427 $this->add('text',
428 'end_date_years',
429 ts('Dates may be up to'),
430 $attributes['end_date_years'],
431 FALSE
432 );
433
434 $this->addRule('start_date_years', ts('Value should be a positive number'), 'integer');
435 $this->addRule('end_date_years', ts('Value should be a positive number'), 'integer');
436
437 $this->add('select', 'date_format', ts('Date Format'),
438 array('' => ts('- select -')) + CRM_Core_SelectValues::getDatePluginInputFormats()
439 );
440
441 $this->add('select', 'time_format', ts('Time'),
442 array('' => ts('- none -')) + CRM_Core_SelectValues::getTimeFormats()
443 );
444
445 // for Note field
446 $this->add('text',
447 'note_columns',
448 ts('Width (columns)') . ' ',
449 $attributes['note_columns'],
450 FALSE
451 );
452 $this->add('text',
453 'note_rows',
454 ts('Height (rows)') . ' ',
455 $attributes['note_rows'],
456 FALSE
457 );
458 $this->add('text',
459 'note_length',
460 ts('Maximum length') . ' ',
461 $attributes['text_length'], // note_length is an alias for the text-length field
462 FALSE
463 );
464
465 $this->addRule('note_columns', ts('Value should be a positive number'), 'positiveInteger');
466 $this->addRule('note_rows', ts('Value should be a positive number'), 'positiveInteger');
467 $this->addRule('note_length', ts('Value should be a positive number'), 'positiveInteger');
468
469 // weight
470 $this->add('text', 'weight', ts('Order'),
471 $attributes['weight'],
472 TRUE
473 );
474 $this->addRule('weight', ts('is a numeric field'), 'numeric');
475
476 // is required ?
477 $this->add('checkbox', 'is_required', ts('Required?'));
478
479 // checkbox / radio options per line
480 $this->add('text', 'options_per_line', ts('Options Per Line'));
481 $this->addRule('options_per_line', ts('must be a numeric value'), 'numeric');
482
483 // default value, help pre, help post, mask, attributes, javascript ?
484 $this->add('text', 'default_value', ts('Default Value'),
485 $attributes['default_value']
486 );
487 $this->add('textarea', 'help_pre', ts('Field Pre Help'),
488 $attributes['help_pre']
489 );
490 $this->add('textarea', 'help_post', ts('Field Post Help'),
491 $attributes['help_post']
492 );
493 $this->add('text', 'mask', ts('Mask'),
494 $attributes['mask']
495 );
496
497 // is active ?
498 $this->add('checkbox', 'is_active', ts('Active?'));
499
500 // is active ?
501 $this->add('checkbox', 'is_view', ts('View Only?'));
502
503 // is searchable ?
504 $this->addElement('checkbox',
505 'is_searchable',
506 ts('Is this Field Searchable?'),
507 NULL, array('onclick' => "showSearchRange(this)")
508 );
509
510 // is searchable by range?
511 $searchRange = array();
512 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('Yes'), '1');
513 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('No'), '0');
514
515 $this->addGroup($searchRange, 'is_search_range', ts('Search by Range?'));
516
517 // add buttons
518 $this->addButtons(array(
519 array(
520 'type' => 'next',
521 'name' => ts('Save'),
522 'isDefault' => TRUE,
523 ),
524 array(
525 'type' => 'next',
526 'name' => ts('Save and New'),
527 'subName' => 'new',
528 ),
529 array(
530 'type' => 'cancel',
531 'name' => ts('Cancel'),
532 ),
533 )
534 );
535
536 // add a form rule to check default value
537 $this->addFormRule(array('CRM_Custom_Form_Field', 'formRule'), $this);
538
539 // if view mode pls freeze it with the done button.
540 if ($this->_action & CRM_Core_Action::VIEW) {
541 $this->freeze();
542 $url = CRM_Utils_System::url('civicrm/admin/custom/group/field', 'reset=1&action=browse&gid=' . $this->_gid);
543 $this->addElement('button',
544 'done',
545 ts('Done'),
546 array('onclick' => "location.href='$url'")
547 );
548 }
549 }
550
551 /**
552 * global validation rules for the form
553 *
554 * @param array $fields (referance) posted values of the form
555 *
556 * @return array if errors then list of errors to be posted back to the form,
557 * true otherwise
558 * @static
559 * @access public
560 */
561 static function formRule($fields, $files, $self) {
562 $default = CRM_Utils_Array::value('default_value', $fields);
563
564 $errors = array();
565
566 //validate field label as well as name.
567 $title = $fields['label'];
568 $name = CRM_Utils_String::munge($title, '_', 64);
569 $gId = $self->_gid; // CRM-7564
570 $query = 'select count(*) from civicrm_custom_field where ( name like %1 OR label like %2 ) and id != %3 and custom_group_id = %4';
571 $fldCnt = CRM_Core_DAO::singleValueQuery($query, array(1 => array($name, 'String'),
572 2 => array($title, 'String'),
573 3 => array((int)$self->_id, 'Integer'),
574 4 => array($gId, 'Integer'),
575 ));
576 if ($fldCnt) {
577 $errors['label'] = ts('Custom field \'%1\' already exists in Database.', array(1 => $title));
578 }
579
580 //checks the given custom field name doesnot start with digit
581 if (!empty($title)) {
582 // gives the ascii value
583 $asciiValue = ord($title{0});
584 if ($asciiValue >= 48 && $asciiValue <= 57) {
585 $errors['label'] = ts("Field's Name should not start with digit");
586 }
587 }
588
589 // ensure that the label is not 'id'
590 if (strtolower($title) == 'id') {
591 $errors['label'] = ts("You cannot use 'id' as a field label.");
592 }
593
594 if (!isset($fields['data_type'][0]) || !isset($fields['data_type'][1])) {
595 $errors['_qf_default'] = ts('Please enter valid - Data and Input Field Type.');
596 }
597
598 $dataType = self::$_dataTypeKeys[$fields['data_type'][0]];
599
600 if ($default || $dataType == 'ContactReference') {
601 switch ($dataType) {
602 case 'Int':
603 if (!CRM_Utils_Rule::integer($default)) {
604 $errors['default_value'] = ts('Please enter a valid integer as default value.');
605 }
606 break;
607
608 case 'Float':
609 if (!CRM_Utils_Rule::numeric($default)) {
610 $errors['default_value'] = ts('Please enter a valid number as default value.');
611 }
612 break;
613
614 case 'Money':
615 if (!CRM_Utils_Rule::money($default)) {
616 $errors['default_value'] = ts('Please enter a valid number value.');
617 }
618 break;
619
620 case 'Link':
621 if (!CRM_Utils_Rule::url($default)) {
622 $errors['default_value'] = ts('Please enter a valid link.');
623 }
624 break;
625
626 case 'Date':
627 if (!CRM_Utils_Rule::date($default)) {
628 $errors['default_value'] = ts('Please enter a valid date as default value using YYYY-MM-DD format. Example: 2004-12-31.');
629 }
630 break;
631
632 case 'Boolean':
633 if ($default != '1' && $default != '0') {
634 $errors['default_value'] = ts('Please enter 1 (for Yes) or 0 (for No) if you want to set a default value.');
635 }
636 break;
637
638 case 'Country':
639 if (!empty($default)) {
640 $query = "SELECT count(*) FROM civicrm_country WHERE name = %1 OR iso_code = %1";
641 $params = array(1 => array($fields['default_value'], 'String'));
642 if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
643 $errors['default_value'] = ts('Invalid default value for country.');
644 }
645 }
646 break;
647
648 case 'StateProvince':
649 if (!empty($default)) {
650 $query = "
651 SELECT count(*)
652 FROM civicrm_state_province
653 WHERE name = %1
654 OR abbreviation = %1";
655 $params = array(1 => array($fields['default_value'], 'String'));
656 if (CRM_Core_DAO::singleValueQuery($query, $params) <= 0) {
657 $errors['default_value'] = ts('The invalid default value for State/Province data type');
658 }
659 }
660 break;
661
662 case 'ContactReference':
663 if ($fields['filter_selected'] == 'Advance' &&
664 CRM_Utils_Array::value('filter', $fields)
665 ) {
666 if (strpos($fields['filter'], 'entity=') !== FALSE) {
667 $errors['filter'] = ts("Please do not include entity parameter (entity is always 'contact')");
668 }
669 elseif (strpos($fields['filter'], 'action=') === FALSE) {
670 $errors['filter'] = ts("Please specify 'action' parameter, it should be 'lookup' or 'get'");
671 }
672 elseif (strpos($fields['filter'], 'action=get') === FALSE &&
673 strpos($fields['filter'], 'action=lookup') === FALSE
674 ) {
675 $errors['filter'] = ts("Only 'get' and 'lookup' actions are supported.");
676 }
677 }
678 $self->setDefaults(array('filter_selected', $fields['filter_selected']));
679 break;
680 }
681 }
682
683 if (self::$_dataTypeKeys[$fields['data_type'][0]] == 'Date') {
684 if (!$fields['date_format']) {
685 $errors['date_format'] = ts('Please select a date format.');
686 }
687 }
688
689 /** Check the option values entered
690 * Appropriate values are required for the selected datatype
691 * Incomplete row checking is also required.
692 */
693 $_flagOption = $_rowError = 0;
694 $_showHide = new CRM_Core_ShowHideBlocks('', '');
695 $dataType = self::$_dataTypeKeys[$fields['data_type'][0]];
696 if (isset($fields['data_type'][1])) {
697 $dataField = $fields['data_type'][1];
698 }
699 $optionFields = array('Select', 'Multi-Select', 'CheckBox', 'Radio', 'AdvMulti-Select');
700
701 if (isset($fields['option_type']) && $fields['option_type'] == 1) {
702 //capture duplicate Custom option values
703 if (!empty($fields['option_value'])) {
704 $countValue = count($fields['option_value']);
705 $uniqueCount = count(array_unique($fields['option_value']));
706
707 if ($countValue > $uniqueCount) {
708
709 $start = 1;
710 while ($start < self::NUM_OPTION) {
711 $nextIndex = $start + 1;
712 while ($nextIndex <= self::NUM_OPTION) {
713 if ($fields['option_value'][$start] == $fields['option_value'][$nextIndex] &&
714 !empty($fields['option_value'][$nextIndex])
715 ) {
716 $errors['option_value[' . $start . ']'] = ts('Duplicate Option values');
717 $errors['option_value[' . $nextIndex . ']'] = ts('Duplicate Option values');
718 $_flagOption = 1;
719 }
720 $nextIndex++;
721 }
722 $start++;
723 }
724 }
725 }
726
727 //capture duplicate Custom Option label
728 if (!empty($fields['option_label'])) {
729 $countValue = count($fields['option_label']);
730 $uniqueCount = count(array_unique($fields['option_label']));
731
732 if ($countValue > $uniqueCount) {
733 $start = 1;
734 while ($start < self::NUM_OPTION) {
735 $nextIndex = $start + 1;
736 while ($nextIndex <= self::NUM_OPTION) {
737 if ($fields['option_label'][$start] == $fields['option_label'][$nextIndex] &&
738 !empty($fields['option_label'][$nextIndex])
739 ) {
740 $errors['option_label[' . $start . ']'] = ts('Duplicate Option label');
741 $errors['option_label[' . $nextIndex . ']'] = ts('Duplicate Option label');
742 $_flagOption = 1;
743 }
744 $nextIndex++;
745 }
746 $start++;
747 }
748 }
749 }
750
751 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
752 if (!$fields['option_label'][$i]) {
753 if ($fields['option_value'][$i]) {
754 $errors['option_label[' . $i . ']'] = ts('Option label cannot be empty');
755 $_flagOption = 1;
756 }
757 else {
758 $_emptyRow = 1;
759 }
760 }
761 else {
762 if (!strlen(trim($fields['option_value'][$i]))) {
763 if (!$fields['option_value'][$i]) {
764 $errors['option_value[' . $i . ']'] = ts('Option value cannot be empty');
765 $_flagOption = 1;
766 }
767 }
768 }
769
770 if ($fields['option_value'][$i] && $dataType != 'String') {
771 if ($dataType == 'Int') {
772 if (!CRM_Utils_Rule::integer($fields['option_value'][$i])) {
773 $_flagOption = 1;
774 $errors['option_value[' . $i . ']'] = ts('Please enter a valid integer.');
775 }
776 }
777 elseif ($dataType == 'Money') {
778 if (!CRM_Utils_Rule::money($fields['option_value'][$i])) {
779 $_flagOption = 1;
780 $errors['option_value[' . $i . ']'] = ts('Please enter a valid money value.');
781 }
782 }
783 else {
784 if (!CRM_Utils_Rule::numeric($fields['option_value'][$i])) {
785 $_flagOption = 1;
786 $errors['option_value[' . $i . ']'] = ts('Please enter a valid number.');
787 }
788 }
789 }
790
791 $showBlocks = 'optionField_' . $i;
792 if ($_flagOption) {
793 $_showHide->addShow($showBlocks);
794 $_rowError = 1;
795 }
796
797 if (!empty($_emptyRow)) {
798 $_showHide->addHide($showBlocks);
799 }
800 else {
801 $_showHide->addShow($showBlocks);
802 }
803 if ($i == self::NUM_OPTION) {
804 $hideBlock = 'additionalOption';
805 $_showHide->addHide($hideBlock);
806 }
807
808 $_flagOption = $_emptyRow = 0;
809 }
810 }
811 elseif (isset($dataField) &&
812 in_array($dataField, $optionFields) &&
813 !in_array($dataType, array('Boolean', 'Country', 'StateProvince'))
814 ) {
815 if (!$fields['option_group_id']) {
816 $errors['option_group_id'] = ts('You must select a Multiple Choice Option set if you chose Reuse an existing set.');
817 }
818 else {
819 $query = "
820 SELECT count(*)
821 FROM civicrm_custom_field
822 WHERE data_type != %1
823 AND option_group_id = %2";
824 $params = array(
825 1 => array(self::$_dataTypeKeys[$fields['data_type'][0]],
826 'String',
827 ),
828 2 => array($fields['option_group_id'], 'Integer'),
829 );
830 $count = CRM_Core_DAO::singleValueQuery($query, $params);
831 if ($count > 0) {
832 $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.');
833 }
834 }
835 }
836
837 $assignError = new CRM_Core_Page();
838 if ($_rowError) {
839 $_showHide->addToTemplate();
840 $assignError->assign('optionRowError', $_rowError);
841 }
842 else {
843 if (isset($fields['data_type'][1])) {
844 switch (self::$_dataToHTML[$fields['data_type'][0]][$fields['data_type'][1]]) {
845 case 'Radio':
846 $_fieldError = 1;
847 $assignError->assign('fieldError', $_fieldError);
848 break;
849
850 case 'Checkbox':
851 $_fieldError = 1;
852 $assignError->assign('fieldError', $_fieldError);
853 break;
854
855 case 'Select':
856 $_fieldError = 1;
857 $assignError->assign('fieldError', $_fieldError);
858 break;
859
860 default:
861 $_fieldError = 0;
862 $assignError->assign('fieldError', $_fieldError);
863 }
864 }
865
866 for ($idx = 1; $idx <= self::NUM_OPTION; $idx++) {
867 $showBlocks = 'optionField_' . $idx;
868 if (!empty($fields['option_label'][$idx])) {
869 $_showHide->addShow($showBlocks);
870 }
871 else {
872 $_showHide->addHide($showBlocks);
873 }
874 }
875 $_showHide->addToTemplate();
876 }
877
878 // we can not set require and view at the same time.
879 if (CRM_Utils_Array::value('is_required', $fields) &&
880 CRM_Utils_Array::value('is_view', $fields)
881 ) {
882 $errors['is_view'] = ts('Can not set this field Required and View Only at the same time.');
883 }
884
885 return empty($errors) ? TRUE : $errors;
886 }
887
888 /**
889 * Process the form
890 *
891 * @param null
892 *
893 * @return void
894 * @access public
895 */
896 public function postProcess() {
897 // store the submitted values in an array
898 $params = $this->controller->exportValues($this->_name);
899 if ($this->_action == CRM_Core_Action::UPDATE) {
900 $dataTypeKey = $this->_defaultDataType[0];
901 $params['data_type'] = self::$_dataTypeKeys[$this->_defaultDataType[0]];
902 $params['html_type'] = self::$_dataToHTML[$this->_defaultDataType[0]][$this->_defaultDataType[1]];
903 }
904 else {
905 $dataTypeKey = $params['data_type'][0];
906 $params['html_type'] = self::$_dataToHTML[$params['data_type'][0]][$params['data_type'][1]];
907 $params['data_type'] = self::$_dataTypeKeys[$params['data_type'][0]];
908 }
909
910 //fix for 'is_search_range' field.
911 if (in_array($dataTypeKey, array(
912 1, 2, 3, 5))) {
913 if (!CRM_Utils_Array::value('is_searchable', $params)) {
914 $params['is_search_range'] = 0;
915 }
916 }
917 else {
918 $params['is_search_range'] = 0;
919 }
920
921 $filter = 'null';
922 if ($dataTypeKey == 11 && CRM_Utils_Array::value('filter_selected', $params)) {
923 if ($params['filter_selected'] == 'Advance' && trim(CRM_Utils_Array::value('filter', $params))) {
924 $filter = trim($params['filter']);
925 }
926 elseif ($params['filter_selected'] == 'Group' && CRM_Utils_Array::value('group_id', $params)) {
927
928 $filter = 'action=lookup&group=' . implode(',', $params['group_id']);
929 }
930 }
931 $params['filter'] = $filter;
932
933 // fix for CRM-316
934 $oldWeight = NULL;
935 if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD)) {
936 $fieldValues = array('custom_group_id' => $this->_gid);
937 if ($this->_id) {
938 $oldWeight = $this->_values['weight'];
939 }
940 $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_CustomField', $oldWeight, $params['weight'], $fieldValues);
941 }
942
943 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
944
945 //store the primary key for State/Province or Country as default value.
946 if (strlen(trim($params['default_value']))) {
947 switch ($params['data_type']) {
948 case 'StateProvince':
949 $fieldStateProvince = $strtolower($params['default_value']);
950 $query = "
951 SELECT id
952 FROM civicrm_state_province
953 WHERE LOWER(name) = '$fieldStateProvince'
954 OR abbreviation = '$fieldStateProvince'";
955 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
956 if ($dao->fetch()) {
957 $params['default_value'] = $dao->id;
958 }
959 break;
960
961 case 'Country':
962 $fieldCountry = $strtolower($params['default_value']);
963 $query = "
964 SELECT id
965 FROM civicrm_country
966 WHERE LOWER(name) = '$fieldCountry'
967 OR iso_code = '$fieldCountry'";
968 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
969 if ($dao->fetch()) {
970 $params['default_value'] = $dao->id;
971 }
972 break;
973 }
974 }
975
976 // The text_length attribute for Memo fields is in a different input as there
977 // are different label, help text and default value than for other type fields
978 if ($params['data_type'] == "Memo") {
979 $params['text_length'] = $params['note_length'];
980 }
981
982 // need the FKEY - custom group id
983 $params['custom_group_id'] = $this->_gid;
984
985 if ($this->_action & CRM_Core_Action::UPDATE) {
986 $params['id'] = $this->_id;
987 }
988
989 $customField = CRM_Core_BAO_CustomField::create($params);
990 $this->_id = $customField->id;
991
992 // reset the cache
993 CRM_Core_BAO_Cache::deleteGroup('contact fields');
994
995 $msg = '<p>' . ts("Custom field '%1' has been saved.", array(1 => $customField->label)) . '</p>';
996
997 $buttonName = $this->controller->getButtonName();
998 $session = CRM_Core_Session::singleton();
999 if ($buttonName == $this->getButtonName('next', 'new')) {
1000 $msg += '<p>' . ts("Ready to add another.") . '</p>';
1001 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field/add',
1002 'reset=1&action=add&gid=' . $this->_gid
1003 ));
1004 }
1005 else {
1006 $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/custom/group/field',
1007 'reset=1&action=browse&gid=' . $this->_gid
1008 ));
1009 }
1010 $session->setStatus($msg, ts('Saved'), 'success');
1011
1012 // Add data when in ajax contect
1013 $this->ajaxResponse['customField'] = $customField->toArray();
1014 }
1015 }
1016