【问题标题】:loading views in editing record in codeigniter在 codeigniter 的编辑记录中加载视图
【发布时间】:2011-06-18 07:43:45
【问题描述】:

您好,我是 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 is not defined 和类似的东西。现在我想问我如何将用户重定向到相同的编辑表单,告诉他他的记录已经更新?如何加载视图 从控制器的功能中选择记录?

【问题讨论】:

    标签: php codeigniter frameworks views codeigniter-url


    【解决方案1】:

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

    redirect(current_url());
    

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

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

    它会产生一个错误,edit_user/.php is not defined 之类的。

    不要使用特定的 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 中的内容,如果您需要的数据不是,请始终做出适当的响应在那里。

    【讨论】:

      【解决方案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>
      

      这将返回相同的编辑页面,提交后也。

      希望这对您有所帮助,如果有任何问题请告诉我们...谢谢!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-14
        • 2014-03-28
        • 2011-10-07
        • 2015-06-25
        • 2014-10-18
        相关资源
        最近更新 更多