Using the Code Igniter Validation Class to set default form values

Monday July 23rdCodeIgniter Category

Quite often when your using CodeIgniter Validation Class you require forms that have validation and default values for example a users profile. Unfortunately this is cannot be handled by this class but with extending the validation class can resolve this issue simply and effectively.

By extending the the validation class it is possible to set the default values. The Validation class takes the values to display from the $_POST variable but for the inital page load these are empty. Also dependingt on the form input type the values are collected at different times. For example an input field is taken at the call to set_field but checkboxes etc have their values reread at the call to set_checkbox. To easily account for both these cases the $_POST variables must have the values to use as the default values set after the call to set_fields.

So now to the practical part. Sub classing the Code Igniter Validation class. Create a file application/libraries/My_Validation.php if the folder is not present create it. Then copy the following code:


01.   <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
02.
03.   class MY_Validation extends CI_Validation {
04.
05.       function My_Validation()
06.       {
07.           parent::CI_Validation();
08.       }
09.
10.       function set_default_values($data, $value = null)
11.       {
12.           if (is_array($data) == TRUE)
13.           {
14.               foreach($data as $field => $value)
15.               {
16.                   $this->$field   = $value;
17.                   $_POST[$field]  = $value;
18.               }
19.           }
20.           else
21.           {
22.               $this->$data    = $value;
23.               $_POST[$data]   = $value;
24.           }
25.       }
26.   }
27.   ?>

This new function can be called with:


01.  $this->validation->set_default_values('fieldname', 'value');

or

01.  $data = array ('fieldname'=>'value');
02.  $this->validation->set_default_values($data);

or using a model

01.  $query = $this->some_model->read();
02.  if($query->num_rows() > 0)
03.  {
04.       $this->validation->set_default_values($query->row_query());
05.  }

That’s basically it, remember to call teh set_default_values after the call to $this->validation->set_fields() if there are no values stored in $_POST set the default values required. An example has been included to show the functionality.

HTML:

01.  <?=form_open('/form');?>
02.  <div>
03.    Text:
04.    <input type="text" name="text" value="<?=$this->validation->text;?>" id="text" />
05.  </div>
06.  <div>
07.    Selection:
08.    <select id="select" name="select">
08.      <option value="select1" <?= $this->validation->set_select('select', 'select1');?> >select1</option>
10.      <option value="select2" <?= $this->validation->set_select('select', 'select2');?> >select2</option>
11.      <option value="select3" <?= $this->validation->set_select('select', 'select3');?> >select3</option>
12.    </select>
13.  </div>
14.  <div>
15.    <input type="checkbox" name="check" value="check1" <?= $this->validation->set_checkbox('check', 'check1'); ?> />
16.    <input type="checkbox" name="check" value="check2" <?= $this->validation->set_checkbox('check', 'check2'); ?> />
17.    <input type="checkbox" name="check" value="check3" <?= $this->validation->set_checkbox('check', 'check3'); ?> />
18.  </div>
19.  <div>
20.    <input type="radio" name="radio" value="1" <?= $this->validation->set_radio('radio', 'radio1'); ?> />
21.    <input type="radio" name="radio" value="2" <?= $this->validation->set_radio('radio', 'radio2'); ?> />
22.    <input type="radio" name="radio" value="3" <?= $this->validation->set_radio('radio', 'radio3'); ?> />
23.  </div>
24.  <div>
25.    <button type="submit">Update</button>
26.  </div>
27.  </form>

Controller

01.  <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
02.
03.  class Form extends Controller {
04.
05.      function index()
06.      {
07.         $this->load->library('validation');
08.         $this->load->helper('form');
09.
10.         $rules['text'] = ‘required’;
11.  	    $rules['option'] = ‘required’;
12.  	    $rules['select'] = ‘required’;
13.  	    $rules['radio'] = ‘required’;
14.  	    $this->validation->set_rules($rules);
15.
16.         $fields['text'] = ‘text field’;
17.  	    $fields['select'] = ’select field’;
18.  	    $fields['check'] = ‘check box field’;
19.  	    $fields['radio'] = ‘radio field’;
20.  	    $this->validation->set_fields($fields);
21.
22.  	    if (count($_POST) == 0)
23.  	    {  // For initial load set defualt values
24.  		$this->validation->set_default_values(’text’, ‘hello world’);
25.  		$this->validation->set_default_values(’select’, ’select2′);
26.  		$this->validation->set_default_values(’check’, ‘check2′);
27.  		$this->validation->set_default_values(’radio’, ‘radio3′);
28.  	    }
29.
30.         if ($this->validation->run() == FALSE)
31.  	    {
32.  		$this->load->view(’form’);
33.  	    }
34.  	    else
35.  	    {
36.  		$this->load->view(’form’);
37.  	    }
38.      }
39.
40.  }
41.  ?>

14 Comments

  1. dgriffis
    August 20, 2007

    looks like a needed addition to the validation library. appears to work with text fields.

  2. Luci3n
    August 26, 2007

    @dgriffis: Yes your right, I think is more an oversight and would be very usefull if it was added to the library. The call to the set_default_values works for all form input fields checkboxes, radio buttons, selections and any type of text field.

  3. majik
    September 13, 2007

    I guess you should add the following for php4 users:
    $this->CI =& get_instance();
    or something like that :)

  4. Spheroid
    October 1, 2007

    How to get this working when your form has a [] in the name like:
    <input type=”checkbox” name=”check[]” value=”1″ validation->set_checkbox(’check[]‘, ‘1′); ?> />
    <input type=”checkbox” name=”check[]” value=”2″ validation->set_checkbox(’check[]‘, ‘2′); ?> />

  5. Alex Biddle
    October 15, 2007

    This seems to be for persistent default values?

    For a regular update, where you just want the default values displayed once, you need check whether the post superglobal has been set already:

    if (!isset($_POST[$field]))
    {
    $_POST[$field] = $data;
    $this->$field = $data;
    }

  6. noinput
    January 24, 2008

    good call on the validation extension, worked like a charm

  7. kenzie
    March 31, 2008

    This is great, thanks. Added is_object for my implementation:

    if ((is_array($data) == TRUE) or (is_object($data) == TRUE))

  8. Ruslan
    October 23, 2008

    Good job!

  9. Muhammad
    November 19, 2008

    great..it’s worked..

  10. CI_coder
    December 14, 2008

    The examples provided are for CI earlier than 1.7.0. Does this work okay with the new “form_validation” class that is used in 1.7.0?

  11. Luci3n
    December 14, 2008

    the example here doesn’t work with 1.7.0
    but it’s very similar see the code below, remember you can also use the helpers to set the default values see: http://codeigniter.com/user_guide/libraries/form_validation.html#helperreference
    so:

    < ?php echo set_value('quantity', ); ?>

    or use a similar as above but for 1.7.0 below

    < ?php if (!defined('BASEPATH')) exit('No direct script access allowed');

    class MY_Form_validation extends CI_Form_validation {

    function MY_Form_validation()
    {
    parent::CI_Form_validation();
    }

    /**
    * Get the value from a form
    *
    * Permits you to repopulate a form field with the value it was submitted
    * with, or, if that value doesn't exist, with the default
    *
    * @access public
    * @param string the field name
    * @param string
    * @return void
    */
    function set_default_value($field = '', $default = '')
    {
    if ( ! isset($this->_field_data[$field]))
    {
    //$this->_field_data[$field] = $default;
    }

    $this->_field_data[$field]['postdata'] = $default;
    }
    }
    ?>

    hope this helps

  12. Two Dubs
    December 18, 2008

    If your using CodeIgniters V1.2 FormValidation class, which I highly recommend, you can do this…

    function set_default($field, $data) {
    $this->_field_data[$field]['postdata'] = $data;
    }

    This will handle associative arrays by simply having the field be of the format $field = “Array[Array][fieldname]“; and the $data field being the value of the prefilled text.

  13. Two Dubs
    December 18, 2008

    When defining the constructor, also remember to add in the $rules=array(), otherwise the rules defined in config/form_validation.php will not be picked up.

    MY_Form_validation constructor should look like this…

    function MY_Form_validation($rules = array()){
    parent::CI_Form_validation($rules);
    }

  14. FADlinux
    September 12, 2009

    good..bro
    finally i find code it
    haha

Leave a comment

Size

Colors