views:

302

answers:

3

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?

+1  A: 

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'); ?>" />
bschaeffer
A: 

The set_value function fetches its value from the Form_validation object and not from the $_POST array. The Form_validation object stores its own copy of the posted values in a variable called $_field_data.

Its a hack, but you could clear this variable after handling a successful submission :

class Item extends Controller
{
    function Item()
    {
        parent::Controller();
        $this->load->model('item_model');
    }

    function add()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('name', 'name', 'required');

        $success = false;

        if ($this->form_validation->run())
        {
            $this->item_model->add_item($this->input->post('name'));
            $success = true;

            // Look away now. Hack coming up!
            // Clear the form validation field data
            $this->form_validation->_field_data = array();
        }

        $this->load->view('item/add', array('success' => $success));
    }
}
Stephen Curran
You need not 'hack' anything. Just redirect it to itself, that way there will be no submissions made.
Thorpe Obazee
Yeah thats the obvious approach. But OP stated he didn't want to do this.
Stephen Curran
+2  A: 

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);
Thorpe Obazee
Absolutely the best way to handle this.
Zack