codeigniter - Codeigniter表单验证: How to redirect to the previous page if found any validation error?

标签 codeigniter codeigniter-2

我正在使用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/

相关文章:

php - 在 codeigniter 中一次制作 2 个缩略图

codeigniter - 使用 tank auth 设置 Codeigniter HMVC

php - 无法从 MySQL 数据库表中检索公司名称

mysql - 如何解决 CI_DB_mysql_result

mysql - 从3个表一对多选择sql

php - 如何在一个表中获取多语言数据(codeigniter,Mysql,Php)

CodeIgniter:为 max_length[x] 设置消息

javascript - 我的数据插入但数据表不会重新加载(codeigniter)

php - 如何连接每一行的输入并保存到数据库

codeigniter - Codeigniter 中的图像文件、css、js 等放在哪里?