Codeigniter form validation set_value and set_checkbox problem fixed

For example, I have two fields in my form first_name and last_name
I have set the validation rule only for first_name. 'set_value' should work for both the fields regardless of rule ? Right ?
- No, set_value or set_checkbox or set_select only works against the items you have chosen to validate using the form_validation class.

Solution
Simple way to fix this problem is to overwrite the core 'MY_form_helper.php' with some functions.
- Copy the following code and save it and name it as 'My_form_helper.php' and placed under 'application/helpers' folder. It will overwrite the core functions.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
/**
* Form Value
*
* Grabs a value from the POST array for the specified field so you can
* re-populate an input field or textarea.  If Form Validation
* is active it retrieves the info from the validation class
*
* @access   public
* @param   string
* @return   mixed
*/
if (!function_exists('set_value')) {
 
        function set_value($field = '', $default = '') {
                $OBJ = & _get_validation_object();
 
                if ($OBJ === TRUE && isset($OBJ->_field_data[$field])) {
                        return form_prep($OBJ->set_value($field, $default));
                } else {
                        if (!isset($_POST[$field])) {
                                return $default;
                        }
 
                        return form_prep($_POST[$field]);
                }
        }
 
}
 
if (!function_exists('set_checkbox')) {
 
        function set_checkbox($field = '', $value = '', $default = '') {
                $OBJ = & _get_validation_object();
 
                if ($OBJ === TRUE && isset($OBJ->_field_data[$field])) {
                        return form_prep($OBJ->set_checkbox($field, $value, $default));
                } else {
                        if (!isset($_POST[$field])) {
                                return '';
                        }
                        else{
                                if($_POST[$field] == $value)
                                {
                                        return 'checked=\'checked\'';
                                }
                        }
                }
        }
 
}
 
/* End of file MY_form_helper.php */
/* Location: ./application/helpers/MY_form_helper.php */ 
This will overwrite the core functions MY_form_helper.php and will work with all the fields regardless of validation rules.
Enjoy :)
Source: http://pastebin.com/h70F9esF

Comments

  1. Nice Tutorial...i got useful information from this tutorial,here is a way to findsimple registration form using codeigniter

    ReplyDelete

Post a Comment

Popular Posts