user393964
user393964

Reputation:

Make form remember earlier submitted values with CodeIgniter

I have this contact form with codeigniter, and what I want to do is, when the form is submitted but does not pass validation, I want the fields to contain earlier submitted values.

There's one thing though: when the form is loaded all the fields already have a certain value assigned, so for example the "name field" shows "name" inside the field. And I want this to stay that way, unless "name" is changed and the form is submitted, in that case it should have the new value.

So for the moment I have this:

<?php echo form_input('name', 'Name*');?>

<?php echo form_input('email', 'Email*');?>

But I don't know how to make the form remember any new submitted values.

Anyone any idea?

Upvotes: 3

Views: 5333

Answers (3)

Mitchell McKenna
Mitchell McKenna

Reputation: 2276

If you are submitting to the same controller, you can get the previously submitted variables through $_POST (or $_GET depending on which form method you chose).

// use $_POST['name'] if set, else use 'Name*'
<?= form_input('name', (!empty($_POST['name']) ? $_POST['name'] : 'Name*'); ?>

Upvotes: 0

Repox
Repox

Reputation: 15476

I think the answer lies in the controller.

Personally, I started letting the forms controller function handling the validation:

<?php

class Page extends Controller
{

    ...

    function showform()
    {
      $this->load->helper(array('form', 'url'));
      $data = array("name" => "Name*", "email" => "Email*");
      $failure = false;

      if( $this->input->post("name") )
      {
        $data["name"] = $this->input->post("name");
        $data["email"] = $this->input->post("email");

        if( !valid_email($data["email"]) )
        {
            $failure = true;
            $data["error_message"] = "E-mail couldn't validate";
        }

        if( !$failure )
             redirect('/page/thankyou/', 'refresh');
      }



        $this->load->vars($data);
        $this->load->view("theform");   

    }

    ...

}

And in your view, you would do something like this:

<?php echo form_input('name', $name);?>
<?php echo form_input('email', $email);?>

Upvotes: 0

Mischa
Mischa

Reputation: 43298

I'd recommend using CodeIgniter's set_value method.

<?php echo form_input('name', set_value('name', 'Name*')); ?>

Upvotes: 5

Related Questions