3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
37 * form to process actions on the field aspect of Custom
39 class CRM_Custom_Form_Field
extends CRM_Core_Form
{
42 * Constants for number of options for data types of multiple option.
44 const NUM_OPTION
= 11;
47 * The custom group id saved to the session for an update.
54 * The field id, used when editing the field
61 * The default custom data/input types, when editing the field
65 protected $_defaultDataType;
68 * Array of custom field values if update mode.
73 * Array for valid combinations of data_type & html_type
77 private static $_dataTypeValues = NULL;
78 private static $_dataTypeKeys = NULL;
80 private static $_dataToHTML = NULL;
82 private static $_dataToLabels = NULL;
85 * Set variables up before form is built.
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());
95 if (!self
::$_dataToHTML) {
96 self
::$_dataToHTML = CRM_Core_BAO_CustomField
::dataToHtml();
100 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
102 $this->_values
= array();
103 //get the values form db if update.
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
);
110 $this->_gid
= $this->_values
['custom_group_id'];
114 $this->_gid
= CRM_Utils_Request
::retrieve('gid', 'Positive', $this);
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.");
122 $url = CRM_Utils_System
::url('civicrm/admin/custom/group/field',
123 "reset=1&action=browse&gid={$this->_gid}"
126 $session = CRM_Core_Session
::singleton();
127 $session->pushUserContext($url);
130 if (self
::$_dataToLabels == NULL) {
131 self
::$_dataToLabels = 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'),
142 'Text' => ts('Text'),
143 'Select' => ts('Select'),
144 'Radio' => ts('Radio'),
147 'Text' => ts('Text'),
148 'Select' => ts('Select'),
149 'Radio' => ts('Radio'),
152 'Text' => ts('Text'),
153 'Select' => ts('Select'),
154 'Radio' => ts('Radio'),
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')),
169 * Set default values for the form. Note that in edit/view mode
170 * the default values are retrieved from the database
173 * array of default values
175 public function setDefaultValues() {
176 $defaults = $this->_values
;
179 $this->assign('id', $this->_id
);
180 $this->_gid
= $defaults['custom_group_id'];
182 //get the value for state or country
183 if ($defaults['data_type'] == 'StateProvince' &&
184 $stateId = CRM_Utils_Array
::value('default_value', $defaults)
186 $defaults['default_value'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_StateProvince', $stateId);
188 elseif ($defaults['data_type'] == 'Country' &&
189 $countryId = CRM_Utils_Array
::value('default_value', $defaults)
191 $defaults['default_value'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Country', $countryId);
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
199 $filterParts = explode('&', $defaults['filter']);
201 if (count($filterParts) == 2) {
202 $contactRefFilter = 'Group';
203 foreach ($filterParts as $part) {
204 if (strpos($part, 'group=') === FALSE) {
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;
216 $defaults['filter_selected'] = $contactRefFilter;
219 if (!empty($defaults['data_type'])) {
220 $defaultDataType = array_search($defaults['data_type'],
223 $defaultHTMLType = array_search($defaults['html_type'],
224 self
::$_dataToHTML[$defaultDataType]
226 $defaults['data_type'] = array(
227 '0' => $defaultDataType,
228 '1' => $defaultHTMLType,
230 $this->_defaultDataType
= $defaults['data_type'];
233 $defaults['option_type'] = 2;
235 $this->assign('changeFieldType', CRM_Custom_Form_ChangeFieldType
::fieldTypeTransitions($this->_values
['data_type'], $this->_values
['html_type']));
238 $defaults['is_active'] = 1;
239 $defaults['option_type'] = 1;
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;
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);
253 $defaults['text_length'] = 255;
254 $defaults['note_columns'] = 60;
255 $defaults['note_rows'] = 4;
256 $defaults['is_view'] = 0;
259 if (!empty($defaults['html_type'])) {
260 $dontShowLink = substr($defaults['html_type'], -14) == 'State/Province' ||
substr($defaults['html_type'], -7) == 'Country' ?
1 : 0;
263 if (isset($dontShowLink)) {
264 $this->assign('dontShowLink', $dontShowLink);
266 if ($this->_action
& CRM_Core_Action
::ADD
&&
267 CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'is_multiple', 'id')
269 $defaults['in_selector'] = 1;
276 * Build the form object.
280 public function buildQuickForm() {
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
);
287 // lets trim all the whitespace
288 $this->applyFilter('__ALL__', 'trim');
290 $attributes = CRM_Core_DAO
::getAttribute('CRM_Core_DAO_CustomField');
296 $attributes['label'],
300 $dt = &self
::$_dataTypeValues;
302 foreach ($dt as $key => $value) {
303 $it[$key] = self
::$_dataToLabels[$key];
305 $sel = &$this->addElement('hierselect',
307 ts('Data and Input Field Type'),
308 'onclick="clearSearchBoxes();custom_option_html_type(this.form)"; onBlur="custom_option_html_type(this.form)";',
311 $sel->setOptions(array($dt, $it));
313 if (CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $this->_gid
, 'is_multiple')) {
314 $this->add('checkbox', 'in_selector', ts('Display in Table?'));
317 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
318 $this->freeze('data_type');
320 $includeFieldIds = NULL;
321 if ($this->_action
== CRM_Core_Action
::UPDATE
) {
322 $includeFieldIds = $this->_values
['id'];
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'));
331 $optionTypes = array(
332 '1' => ts('Create a new set of options'),
333 '2' => ts('Reuse an existing set'),
338 ts('Multiple Choice Option Sets'),
340 '' => ts('- select -'),
345 $element = &$this->addRadio('option_type',
349 'onclick' => "showOptionSelect();",
353 $contactGroups = CRM_Core_PseudoConstant
::group();
354 asort($contactGroups);
358 ts('Limit List to Group'),
361 array('multiple' => 'multiple')
366 ts('Advanced Filter'),
367 $attributes['filter']
370 $this->add('hidden', 'filter_selected', 'Group', array('id' => 'filter_selected'));
372 //if empty option group freeze the option type.
373 if ($emptyOptGroup) {
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++
) {
382 //the show hide blocks
383 $showBlocks = 'optionField_' . $i;
385 $_showHide->addHide($showBlocks);
386 if ($i == self
::NUM_OPTION
) {
387 $_showHide->addHide('additionalOption');
391 $_showHide->addShow($showBlocks);
394 $optionAttributes = CRM_Core_DAO
::getAttribute('CRM_Core_DAO_OptionValue');
396 $this->add('text', 'option_label[' . $i . ']', ts('Label'),
397 $optionAttributes['label']
401 $this->add('text', 'option_value[' . $i . ']', ts('Value'),
402 $optionAttributes['value']
406 $this->add('text', "option_weight[$i]", ts('Order'),
407 $optionAttributes['weight']
411 $this->add('checkbox', "option_status[$i]", ts('Active?'));
413 $defaultOption[$i] = $this->createElement('radio', NULL, NULL, NULL, $i);
415 //for checkbox handling of default option
416 $this->add('checkbox', "default_checkbox_option[$i]", NULL);
419 //default option selection
420 $this->addGroup($defaultOption, 'default_option');
422 $_showHide->addToTemplate();
424 // text length for alpha numeric data types
427 ts('Database field length'),
428 $attributes['text_length'],
431 $this->addRule('text_length', ts('Value should be a positive number'), 'integer');
435 ts('Dates may be up to'),
436 $attributes['start_date_years'],
441 ts('Dates may be up to'),
442 $attributes['end_date_years'],
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');
449 $this->add('select', 'date_format', ts('Date Format'),
450 array('' => ts('- select -')) + CRM_Core_SelectValues
::getDatePluginInputFormats()
453 $this->add('select', 'time_format', ts('Time'),
454 array('' => ts('- none -')) + CRM_Core_SelectValues
::getTimeFormats()
460 ts('Width (columns)') . ' ',
461 $attributes['note_columns'],
466 ts('Height (rows)') . ' ',
467 $attributes['note_rows'],
472 ts('Maximum length') . ' ',
473 $attributes['text_length'], // note_length is an alias for the text-length field
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');
482 $this->add('text', 'weight', ts('Order'),
483 $attributes['weight'],
486 $this->addRule('weight', ts('is a numeric field'), 'numeric');
489 $this->add('checkbox', 'is_required', ts('Required?'));
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');
495 // default value, help pre, help post, mask, attributes, javascript ?
496 $this->add('text', 'default_value', ts('Default Value'),
497 $attributes['default_value']
499 $this->add('textarea', 'help_pre', ts('Field Pre Help'),
500 $attributes['help_pre']
502 $this->add('textarea', 'help_post', ts('Field Post Help'),
503 $attributes['help_post']
505 $this->add('text', 'mask', ts('Mask'),
510 $this->add('checkbox', 'is_active', ts('Active?'));
513 $this->add('checkbox', 'is_view', ts('View Only?'));
516 $this->addElement('checkbox',
518 ts('Is this Field Searchable?'),
519 NULL, array('onclick' => "showSearchRange(this)")
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');
527 $this->addGroup($searchRange, 'is_search_range', ts('Search by Range?'));
530 $this->addButtons(array(
533 'name' => ts('Save'),
538 'name' => ts('Save and New'),
543 'name' => ts('Cancel'),
548 // add a form rule to check default value
549 $this->addFormRule(array('CRM_Custom_Form_Field', 'formRule'), $this);
551 // if view mode pls freeze it with the done button.
552 if ($this->_action
& CRM_Core_Action
::VIEW
) {
554 $url = CRM_Utils_System
::url('civicrm/admin/custom/group/field', 'reset=1&action=browse&gid=' . $this->_gid
);
555 $this->addElement('button',
558 array('onclick' => "location.href='$url'")
564 * Global validation rules for the form.
566 * @param array $fields
567 * Posted values of the form.
573 * if errors then list of errors to be posted back to the form,
576 public static function formRule($fields, $files, $self) {
577 $default = CRM_Utils_Array
::value('default_value', $fields);
581 self
::clearEmptyOptions($fields);
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'),
595 $errors['label'] = ts('Custom field \'%1\' already exists in Database.', array(1 => $title));
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");
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.");
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.');
616 $dataType = self
::$_dataTypeKeys[$fields['data_type'][0]];
618 if ($default ||
$dataType == 'ContactReference') {
621 if (!CRM_Utils_Rule
::integer($default)) {
622 $errors['default_value'] = ts('Please enter a valid integer.');
627 if (!CRM_Utils_Rule
::numeric($default)) {
628 $errors['default_value'] = ts('Please enter a valid number.');
633 if (!CRM_Utils_Rule
::money($default)) {
634 $errors['default_value'] = ts('Please enter a valid number.');
639 if (!CRM_Utils_Rule
::url($default)) {
640 $errors['default_value'] = ts('Please enter a valid link.');
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.');
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.');
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.');
666 case 'StateProvince':
667 if (!empty($default)) {
670 FROM civicrm_state_province
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');
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')");
685 elseif (strpos($fields['filter'], 'action=get') === FALSE) {
686 $errors['filter'] = ts("Only 'get' action is supported.");
689 $self->setDefaults(array('filter_selected', $fields['filter_selected']));
694 if (self
::$_dataTypeKeys[$fields['data_type'][0]] == 'Date') {
695 if (!$fields['date_format']) {
696 $errors['date_format'] = ts('Please select a date format.');
700 /** Check the option values entered
701 * Appropriate values are required for the selected datatype
702 * Incomplete row checking is also required.
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];
710 $optionFields = array('Select', 'Multi-Select', 'CheckBox', 'Radio', 'AdvMulti-Select');
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']));
718 if ($countValue > $uniqueCount) {
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])
727 $errors['option_value[' . $start . ']'] = ts('Duplicate Option values');
728 $errors['option_value[' . $nextIndex . ']'] = ts('Duplicate Option values');
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']));
743 if ($countValue > $uniqueCount) {
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])
751 $errors['option_label[' . $start . ']'] = ts('Duplicate Option label');
752 $errors['option_label[' . $nextIndex . ']'] = ts('Duplicate Option label');
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');
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');
781 if ($fields['option_value'][$i] && $dataType != 'String') {
782 if ($dataType == 'Int') {
783 if (!CRM_Utils_Rule
::integer($fields['option_value'][$i])) {
785 $errors['option_value[' . $i . ']'] = ts('Please enter a valid integer.');
788 elseif ($dataType == 'Money') {
789 if (!CRM_Utils_Rule
::money($fields['option_value'][$i])) {
791 $errors['option_value[' . $i . ']'] = ts('Please enter a valid money value.');
795 if (!CRM_Utils_Rule
::numeric($fields['option_value'][$i])) {
797 $errors['option_value[' . $i . ']'] = ts('Please enter a valid number.');
802 $showBlocks = 'optionField_' . $i;
804 $_showHide->addShow($showBlocks);
808 if (!empty($_emptyRow)) {
809 $_showHide->addHide($showBlocks);
812 $_showHide->addShow($showBlocks);
814 if ($i == self
::NUM_OPTION
) {
815 $hideBlock = 'additionalOption';
816 $_showHide->addHide($hideBlock);
819 $_flagOption = $_emptyRow = 0;
822 elseif (isset($dataField) &&
823 in_array($dataField, $optionFields) &&
824 !in_array($dataType, array('Boolean', 'Country', 'StateProvince'))
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.');
832 FROM civicrm_custom_field
833 WHERE data_type != %1
834 AND option_group_id = %2";
837 self
::$_dataTypeKeys[$fields['data_type'][0]],
840 2 => array($fields['option_group_id'], 'Integer'),
842 $count = CRM_Core_DAO
::singleValueQuery($query, $params);
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.');
849 $assignError = new CRM_Core_Page();
851 $_showHide->addToTemplate();
852 $assignError->assign('optionRowError', $_rowError);
855 if (isset($fields['data_type'][1])) {
856 switch (self
::$_dataToHTML[$fields['data_type'][0]][$fields['data_type'][1]]) {
859 $assignError->assign('fieldError', $_fieldError);
864 $assignError->assign('fieldError', $_fieldError);
869 $assignError->assign('fieldError', $_fieldError);
874 $assignError->assign('fieldError', $_fieldError);
878 for ($idx = 1; $idx <= self
::NUM_OPTION
; $idx++
) {
879 $showBlocks = 'optionField_' . $idx;
880 if (!empty($fields['option_label'][$idx])) {
881 $_showHide->addShow($showBlocks);
884 $_showHide->addHide($showBlocks);
887 $_showHide->addToTemplate();
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.');
895 return empty($errors) ?
TRUE : $errors;
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]];
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]];
918 //fix for 'is_search_range' field.
919 if (in_array($dataTypeKey, array(
925 if (empty($params['is_searchable'])) {
926 $params['is_search_range'] = 0;
930 $params['is_search_range'] = 0;
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']);
938 elseif ($params['filter_selected'] == 'Group' && !empty($params['group_id'])) {
940 $filter = 'action=lookup&group=' . implode(',', $params['group_id']);
943 $params['filter'] = $filter;
947 if ($this->_action
& (CRM_Core_Action
::UPDATE | CRM_Core_Action
::ADD
)) {
948 $fieldValues = array('custom_group_id' => $this->_gid
);
950 $oldWeight = $this->_values
['weight'];
952 $params['weight'] = CRM_Utils_Weight
::updateOtherWeights('CRM_Core_DAO_CustomField', $oldWeight, $params['weight'], $fieldValues);
955 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
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']);
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);
969 $params['default_value'] = $dao->id
;
974 $fieldCountry = $strtolower($params['default_value']);
978 WHERE LOWER(name) = '$fieldCountry'
979 OR iso_code = '$fieldCountry'";
980 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
982 $params['default_value'] = $dao->id
;
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'];
994 // need the FKEY - custom group id
995 $params['custom_group_id'] = $this->_gid
;
997 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
998 $params['id'] = $this->_id
;
1000 $customField = CRM_Core_BAO_CustomField
::create($params);
1001 $this->_id
= $customField->id
;
1004 CRM_Core_BAO_Cache
::deleteGroup('contact fields');
1006 $msg = '<p>' . ts("Custom field '%1' has been saved.", array(1 => $customField->label
)) . '</p>';
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
1017 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/admin/custom/group/field',
1018 'reset=1&action=browse&gid=' . $this->_gid
1021 $session->setStatus($msg, ts('Saved'), 'success');
1023 // Add data when in ajax contect
1024 $this->ajaxResponse
['customField'] = $customField->toArray();
1028 * Removes value from fields with no label.
1030 * This allows default values to be set in the form, but ignored in post-processing.
1032 * @param array $fields
1034 public static function clearEmptyOptions(&$fields) {
1035 foreach ($fields['option_label'] as $i => $label) {
1036 if (!strlen(trim($label))) {
1037 $fields['option_value'][$i] = '';