Skip to content

Form validation helpers support prepopulation

Derek Jones edited this page Jul 5, 2012 · 6 revisions

When working with the Form validator I always missed a feature to pre-populate a form (most commonly seen when editing an item) with some checkboxes and radio buttons already checked.

I modified the set_radio, set_checkbox and set_select helpers a bit so they accept different input in the $default parameter besides only true or false.

You can:

  • pass an array as the third argument to all helpers, it then performs an in_array() search for the second argument (value)
  • pass a string or integer as the third parameter to all helpers, it then performs a litteral comparison between value and default
  • all of this is only done when there is still no POST information known (pre population only). When POST is present, that takes preference
  • the default behavior of TRUE/FALSE is preserved, but you have to pass it as a true boolean. So be sure to cast the argument correctly (see example below)

Casting example:

//default behavior of true/false can still be used, when done correctly.

//wrong, is an integer and could generate unwanted outcome
set_select('field', $value, 1);

//good, is an boolean and will be selected by default 
set_select('field', $value, TRUE);

Some examples of how to use these modifications:

Controller:

        $this->load->library("Form_validation");
        
        $set = new stdClass();
        $set->defaults = array(4, 21, 72);
        
        $this->form_validation->set_rules('sector[]', 'Sector');
        $this->form_validation->set_rules('license', 'License');
        $this->form_validation->set_rules('country', 'Country');

        $this->load->view("header");
        
        if($this->form_validation->run() === FALSE)
            $this->load->view("form", array("set" => $set));

        $this->load->view("footer");

View:

    <?php
    
        for($i = 0; $i <= 10; $i++):
            $id = $i * 3;
    ?&gt;
    <p>&lt;input &lt;?= set_checkbox('sector[]', $id, (isset($set-&gt;defaults)) ? $set->defaults : FALSE); ?&gt; type="checkbox" name="sector[]" value="&lt;?=$id?&gt;" />Sector &lt;?=$id?&gt;</p>
    &lt;?php
        endfor;
    ?&gt;

    &lt;?php
    
        for($i = 0; $i <= 10; $i++):
            $id = $i * 8;
    ?&gt;
    <p>&lt;input &lt;?= set_radio('license', $id, (isset($set-&gt;defaults)) ? $set->defaults : FALSE); ?&gt; type="radio" name="license" value="&lt;?=$id?&gt;" />License &lt;?=$id?&gt;</p>
    &lt;?php
        endfor;
    ?&gt;
    
    <select name="country">
    &lt;?php
    
        for($i = 0; $i <= 10; $i++):
            $id = $i * 2;
    ?&gt;
    <option value="&lt;?=$id?&gt;" &lt;?= set_select('country', $id, (isset($set->defaults)) ? $set->defaults : FALSE); ?&gt;>Country &lt;?=$id?&gt;</option>
    &lt;?php
        endfor;
    ?&gt;    
    </select>

And here's the source code. Just name it MY_Form_validation.php and place it into your application/libraries folder to be used automatically when loading the Form_validation library.

Update 24-01-2010: Added check on existence of POST data. The pre population will only kick in if there aren't any, so when you'd deselect all of one group, it will return as being turned all off, instead of being pre populated again.

&lt;?php

/*
    @author: Coen de Jong <co.dejong@gmail.com>

*/


/*
    This extension of the CI validation class is intended to improve the working of the
    set_select, set_radio and set_checkbox functions to support a second 'source' to check if POST doesn't exist yet
*/


class MY_Form_validation extends CI_Form_validation
{

    // --------------------------------------------------------------------
    
    /**
     * Set Select
     *
     * Enables pull-down lists to be set to the value the user
     * selected in the event of an error
     *
     * @access    public
     * @param    string
     * @param    string
     * @return    string
     */    
    function set_select($field = '', $value = '', $default = FALSE)
    {        
        if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
        {
            //To not disturb the standard behavior of the function, we check if there is a bool or array in the $default param

            if(is_bool($default))
            {
                //Do the standard behavior of the function

                if ($default === TRUE AND count($this->_field_data) === 0)
                {
                    return ' selected="selected"';
                }
                return '';

            }
            else
            {
                if(count($_POST) === 0)    //only execute this part if there hasn't been any $_POST data yet
                {
                    if(is_array($default))
                    //An array means there is a set of default values we need to check against
                    if(in_array($value, $default))    
                        return ' selected="selected"';
                    else
                        return '';
                }
                elseif(is_int($default) || is_string($default))
                {
                    //An integer or string means we can litteraly compare the two values with each other
                    if($value == $default)
                        return ' selected="selected"';
                    else
                        return '';
                }
    
                return '';
            }

        }
    
        $field = $this->_field_data[$field]['postdata'];
        
        if (is_array($field))
        {
            if ( ! in_array($value, $field))
            {
                return '';
            }
        }
        else
        {
            if (($field == '' OR $value == '') OR ($field != $value))
            {
                return '';
            }
        }
            
        return ' selected="selected"';
    }
    
    // --------------------------------------------------------------------
    
    /**
     * Set Radio
     *
     * Enables radio buttons to be set to the value the user
     * selected in the event of an error
     *
     * @access    public
     * @param    string
     * @param    string
     * @return    string
     */    
    function set_radio($field = '', $value = '', $default = FALSE)
    {
        if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
        {
            //To not disturb the standard behavior of the function, we check if there is a bool or array in the $default param

            if(is_bool($default))
            {
                //Do the standard behavior of the function

                if ($default === TRUE AND count($this->_field_data) === 0)
                {
                    return ' checked="checked"';
                }
                return '';

            }
            else
            {
                if(count($_POST) === 0)    //only execute this part if there hasn't been any $_POST data yet
                {
                    if(is_array($default))
                    //An array means there is a set of default values we need to check against
                    if(in_array($value, $default))    
                        return ' checked="checked"';
                    else
                        return '';
                }
                elseif(is_int($default) || is_string($default))
                {
                    //An integer or string means we can litteraly compare the two values with each other
                    if($value == $default)
                        return ' checked="checked"';
                    else
                        return '';
                }
    
                return '';
            }

        }
    
        $field = $this->_field_data[$field]['postdata'];
        
        if (is_array($field))
        {
            if ( ! in_array($value, $field))
            {
                return '';
            }
        }
        else
        {
            if (($field == '' OR $value == '') OR ($field != $value))
            {
                return '';
            }
        }
            
        return ' checked="checked"';
    }
    
    // --------------------------------------------------------------------
    
    /**
     * Set Checkbox
     *
     * Enables checkboxes to be set to the value the user
     * selected in the event of an error
     *
     * @access    public
     * @param    string
     * @param    string
     * @return    string
     */    
    function set_checkbox($field = '', $value = '', $default = FALSE)
    {
        if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
        {
            //To not disturb the standard behavior of the function, we check if there is a bool or array in the $default param

            if(is_bool($default))
            {
                //Do the standard behavior of the function

                if ($default === TRUE AND count($this->_field_data) === 0)
                {
                    return ' checked="checked"';
                }
                return '';

            }
            else
            {
                if(count($_POST) === 0)    //only execute this part if there hasn't been any $_POST data yet
                {
                    if(is_array($default))
                    //An array means there is a set of default values we need to check against
                    if(in_array($value, $default))    
                        return ' checked="checked"';
                    else
                        return '';
                }
                elseif(is_int($default) || is_string($default))
                {
                    //An integer or string means we can litteraly compare the two values with each other
                    if($value == $default)
                        return ' checked="checked"';
                    else
                        return '';
                }
    
                return '';
            }

        }
    
        $field = $this->_field_data[$field]['postdata'];
        
        if (is_array($field))
        {
            if ( ! in_array($value, $field))
            {
                return '';
            }
        }
        else
        {
            if (($field == '' OR $value == '') OR ($field != $value))
            {
                return '';
            }
        }
            
        return ' checked="checked"';
    }

}


/* End of file MY_Form_validation.php */
/* Location: ./system/application/libraries/MY_Form_validation.php */
Clone this wiki locally