2

您好,我是 Codeigniter 的新手。我正在通过开发一个测试应用程序来学习这个框架。我正在显示用户列表,并在每条记录前面有一个锚标记来编辑该记录。那个锚标签看起来像

echo(anchor('first/edit_user/'.$value->id,'Edit'));

它将浏览器重定向到第一个控制器和 edit_user 函数。在 edit_user 函数中,我像这样加载编辑视图。

$this->load->view('edit_user',$data);

它加载关于所选记录的视图以编辑记录,并且 url 看起来像

http://localhost/CodeIgniter/index.php/first/edit_user/9 

每件事都很好。但是,当用户单击更新按钮时,它再次出现相同的功能。它更新记录,然后再次尝试加载相同的视图,但这里出现问题。现在更新记录后它会加载视图和 url 变成这样

http://localhost/CodeIgniter/index.php/first/edit_user

它会产生错误,因为它没有所选记录的 id。如果我像这样更改我的函数的加载视图代码

          $this->load->view('edit_user/'$this->uri->segment(3)),$data);

它会产生一个错误,edit_user/.php 未定义,诸如此类。现在我想问我如何将用户重定向到相同的编辑表单,告诉他他的记录已经更新?如何从控制器的功能中加载所选记录的视图?

4

2 回答 2

2

要重定向到与当前 URL 相同的 URL:

redirect(current_url());

否则,请具体说明您要重定向的位置。

$this->load->view('edit_user/'$this->uri->segment(3)),$data);

它会产生一个错误,edit_user/.php 未定义,诸如此类。

不要使用特定的 URL 段,而是使用传递给控制器​​的参数并设置默认值,以及处理传递的参数(url 段)可能不存在或无效的情况。例子:

function edit_user($id = NULL)
{
    if ( ! $id) // handle error (redirect with message probably)

    $user = $this->user_model->get($id);

    if ( ! $user) // User not found, handle the error

    // If user found, load the view and data

}

请记住,控制器仍然只是 php 类和函数,并接受用户输入(我可以在地址栏中输入的任何内容) - 所以永远不要假设 URL 中的内容,如果您需要的数据不存在,请始终做出适当的响应。

于 2011-06-18T09:35:09.977 回答
2

首先加载 URL 助手“config/autoload.php”

/*
| -------------------------------------------------------------------
|  Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
|   $autoload['helper'] = array('url', 'file');
*/

$autoload['helper'] = array('url');

或者在您的函数本身中加载 URL 帮助程序

public function edit_user($user_id = '')
{
    if(!is_numeric($user_id) {
        // user id is not here redirect somewhere //
        redirect('home/index');
    }

    if(isset($_POST['submit'])) {
        // proceed to model // @param is optional // you can pass hidden field from form also //
        $this->user_model->edit_user($user_id)
    }

    $this->load->helper('url');
    $this->load->view('first/edit_user', $data);
}

现在转到您的表格:

<form method="post" action="<?php echo current_url(); ?>">

</form>

这将在提交后返回到相同的编辑页面。

希望这对您有所帮助,如果有什么,请告诉我们...谢谢!

于 2011-06-18T10:10:45.490 回答