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