Codeigniter Form Validation - how to unset form values after success? Codeigniter Form Validation - how to unset form values after success? codeigniter codeigniter

Codeigniter Form Validation - how to unset form values after success?


Redirect to itself. This way, no submissions have been run... This also gives you a way to show the flash_data.

    $this->load->library('form_validation');    $this->form_validation->set_rules('firstname', 'First Name', 'required');    $this->form_validation->set_rules('surname', 'Sur Name', 'required');    if ($this->form_validation->run() === TRUE)    {                    // save data        $this->session->set_flashdata('message', 'New Contact has been added');        redirect(current_url());    }    $this->load->view('contacts/add', $this->data);


Another solution, extend the library CI_Form_validation. The property $_field_data is protected, so we can acces it:

class MY_Form_validation extends CI_Form_validation {    public function __construct()    {        parent::__construct();    }    public function clear_field_data() {        $this->_field_data = array();        return $this;    }}

And call the new method. This way, you can pass data without storing data in session.

    class Item extends Controller    {        function Item()        {            parent::Controller();        }        function add()        {            $this->load->library('form_validation');            $this->form_validation->set_rules('name', 'name', 'required');            $success = false;            if ($this->form_validation->run())            {                $success = true;                $this->form_validation->clear_field_data();            }            $this->load->view('item/add', array('success' => $success));        }    }


Pass a TRUE/FALSE variable to your views that conditionally sets the values of the form.

The Controller

if($this->form_validation->run()){    $data['reset'] = TRUE;}else{    $data['reset'] = FALSE:}$this->load->view("form", $data);

The View:

<input type="text" name="email" value="<?php echo ($reset) ? "" : set_value('email'); ?>" /><input type="text" name="first_name" value="<?php echo ($reset) ? "" : set_value('first_name'); ?>" />