Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter Form Validation: How to redirect to the previous page if found any validation error?

I am using Codeigniter's validation class to validate my form. Could you please tell me how to redirect to the previous page from controller if found any validation error?

In my controller:

if ($this->form_validation->run() == FALSE){

  //**** Here is where I need to redirect  

} else  {
     // code to send data to model...           

  }                             
like image 226
black_belt Avatar asked Oct 28 '11 18:10

black_belt


2 Answers

I extended the URL helper for this.

https://github.com/jonathanazulay/CodeIgniter-extensions/blob/master/MY_url_helper.php

In your controller:

$this->load->helper('url');
redirect_back();

Just put the MY_url_helper.php in application/helpers and you're good to go.

like image 198
Jonathan Avatar answered Nov 04 '22 10:11

Jonathan


UPDATE

You want to post a form, validate it, then show the form again with the validation errors if validation fails, or show something entirely different if validation passes.

The best way to do this is to post a form back to itself. So the action of your form would be action="". This way, in your method, you can check to see if the form was submitted, and determine what to do there:

// in my form method
if ($this->input->post('submit')) // make sure your submit button has a value of submit
{
     // the form was submitted, so validate it
     if ($this->form_validation->run() == FALSE)
     {
         $this->load->view('myform');
 }
 else
 {
         $this->load->view('formsuccess');
 }
}
else
{
    // the form wasn't submitted, so we need to see the form
    $this->load->view('myform');
}

OLD ANSWER

You can always pass the current URI in a hidden field in the form:

<input name="redirect" type="hidden" value="<?= $this->uri->uri_string() ?>" />

And then redirect if the validation fails:

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

Or you can set the redirect url in a flashdata session variable:

// in the method that displays the form
$this->session->set_flashdata('redirect', $this->uri->uri_string());

And then redirect if the validation fails:

redirect($this->session->flashdata('redirect'));
like image 36
swatkins Avatar answered Nov 04 '22 10:11

swatkins