开发者

Make form remember earlier submitted values with CodeIgniter

开发者 https://www.devze.com 2023-01-22 03:58 出处:网络
I have this contact form with codeigniter, and what I want to do is, when the form is submitted but does not 开发者_StackOverflow社区pass validation, I want the fields to contain earlier submitted val

I have this contact form with codeigniter, and what I want to do is, when the form is submitted but does not 开发者_StackOverflow社区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?


I'd recommend using CodeIgniter's set_value method.

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


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);?>


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*'); ?>
0

精彩评论

暂无评论...
验证码 换一张
取 消