views:

48

answers:

3

Hey guys,

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?

+1  A: 

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')) ? $_GET('name) : 'Name*');?>
Mitchell McKenna
+2  A: 

I'd recommend using CodeIgniter's set_value method.

<?php echo form_input('name', set_value('name', 'Name*')); ?>
captaintokyo
thanks, i didn't notice this on the form helper page, but it's exactly what I was looking for!
Sled
+1  A: 

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);?>
Repox
The functionality you are rebuilding here is provided in the framework... the form validation class provides functionality, so you don't have to do this manually. http://codeigniter.com/user_guide/libraries/form_validation.html
captaintokyo
Well, if the OP want's to use the Form Validation class he is most welcome - I, personally, don't like that particular library hence my suggestion.
Repox