How to pass validation error data through redirect

2019-03-28 12:11发布

问题:

I have a page that contains a form and when any user submits it, the data goes to a controller and the controller checks the validation, if there is any error it redirects the user to the previous page( the page that contains the form), otherwise it sends data to models.

To redirect to the previous page from controller (if there is any validation error), I have the following code

        redirect($this->input->post('redirect'));

The above code is working fine but the problem is after it redirects the user to the previous page(The page that contains the form) it is not displaying the validation errors.

So would you please kindly tell me how to pass the validation error information through this "redirect" code I posted above and show the validation error message on that page?

Thanks in Advance :)

Solution:

In my controller:

   $redirect=$this->input->post('redirect'); //  << for this I have- <input name="redirect" type="hidden" value="<?= $this->uri->uri_string() ?>" />         in my view file

   $this->session->set_flashdata('errors', validation_errors());
   redirect($this->input->post('redirect')); 

In my view file:

   <?php

    if ($this->session->flashdata('errors')){ //change!
    echo "<div class='error'>";
    echo $this->session->flashdata('errors');
    echo "</div>";
    }

    ?>

Thus I can pass validation error data through redirect from controller to previous page

回答1:

You can try flashdata from CI's session library. It makes the data available for the next server request.

$this->session->set_flashdata('errors', validation_errors());

redirect($this->input->post('redirect'));