我正在使用Codeigniter的验证类来验证我的表单。如果发现任何验证错误,您能告诉我如何从 Controller 重定向到上一页吗?
在我的 Controller 中:
if ($this->form_validation->run() == FALSE){
//**** Here is where I need to redirect
} else {
// code to send data to model...
}
最佳答案
更新
您要发布一个表单,对其进行验证,然后如果验证失败,则再次显示该表单并显示验证错误,或者如果通过验证,则显示完全不同的内容。
做到这一点的最好方法是将表单回发给自己。因此,表单的操作将是action=""
。这样,在您的方法中,您可以检查表单是否已提交,并确定该怎么做:
// 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');
}
旧答案
您始终可以将当前URI的形式传递给隐藏字段:
<input name="redirect" type="hidden" value="<?= $this->uri->uri_string() ?>" />
如果验证失败,则重定向:
redirect($this->input->post('redirect'));
或者,您可以在flashdata session 变量中设置重定向网址:
// in the method that displays the form
$this->session->set_flashdata('redirect', $this->uri->uri_string());
如果验证失败,则重定向:
redirect($this->session->flashdata('redirect'));
关于codeigniter - Codeigniter表单验证: How to redirect to the previous page if found any validation error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7933298/