Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I realise this request goes against the example provided in the CI documentation (which advises a separate 'success' page view), but I would like to reutilise a given form view after a form has been successfully submitted - displaying a success message then displaying a blank form. I've tried a few ways unsuccessfully to clear the validation set values (unsetting $_POST, setting rules / fields to an empty array and rerunning validation).

I could redirect to the same page, but then I'd have to set a session variable to display a success message - which is a messy approach.

Any ideas how to best achieve the above?

like image 511
BrynJ Avatar asked May 10 '10 10:05

BrynJ


2 Answers

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);
like image 153
Teej Avatar answered Nov 19 '22 01:11

Teej


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));
        }
    }
like image 12
d5avard Avatar answered Nov 19 '22 03:11

d5avard