CodeIgniter更新页面 - 需要简单的CRUD网站帮助

时间:2013-02-17 03:48:46

标签: codeigniter

浏览论坛并开始尝试创建一个基本的CRUD网站后,我正在努力建立一个更新文章的页面,如下所示。如果有人能够告诉我哪里出错了,我会非常感激。我在“新闻/输入”中收到404错误

模型(在news_model.php)

public function update($id, $data)
 {
   $this->db->where('id', $id);
   $this->db->update('news', $data); 
 }

controller(news.php)

public function update($id){

    $data = array(
    'title' => $this->input->post('title'),
    'slug' => $this->input->post('slug'),
    'text' => $this->input->post('text'));

 if($this->news_model->exists($id)) {
  $this->news_model->update($id, $data);
} 
   else {
     $this->news_model->insert($data);
  }
}

html(views / news / input.php)

   <h2>Update a news item</h2>

   <?php echo validation_errors(); ?>

   <?php echo form_open('news/update') ?>

   <label for="title">Title</label> 
   <input type="input" name="title" /><br />

   <label for="slug">Slug</label> 
   <input type="input" name="slug" /><br />

   <label for="text">Text</label>
   <textarea name="text"></textarea><br />

   <input type="submit" name="submit" value="Update an item" /> 

1 个答案:

答案 0 :(得分:1)

你得到404因为你的新闻控制器似乎没有方法'输入'。尝试添加以下内容:

public function input(){
   // load the form 
   $this->load->view('/news/input');
}

请注意,要更新数据,您需要先获取数据并将其传递到视图中,然后使用set_val()和其他CI函数渲染(填充)表单。
目前,您正在“硬编码”HTML表单,这使得填充和维护状态(验证失败时)变得困难。我建议您通过CI网站上的表单教程进行操作。

编辑:

要创建更新/插入(插入)控制器更改,如下所示:

控制器:

        function upsert($id = false){

          $data['id'] = $id;    // create a data array so that you can pass the ID into the view.

                 // you need to differntiate the bevaviour depending on 1st load (insert) or re-load (update):

           if(isset($_POST('title'))){  // or any other means by which you can determine if data's been posted. I generally look for the value of my submit buttons

                if($id){
                     $this->news_model->update($id,  $this->input->post()); // there's post data AND an id -> it's an update        
                } else {
                     $this->news_model->insert($id,  $this->input->post()); // there's post data but NO id -> it's an insert        
                }


            } else { // nothing's been posted -> it's an initial load. If the id is set, it's an update, so we need data to populate the form, if not it's an insert and we can pass an empty array (or an array of default values) 

                if($id){
                     $data['news'] = $this->news_model->getOne($id); // this should return an array of the news item. You need to iterate through this array in the view and create the appropriate, populated HTML input fields.       
                } else {
                     $data['news'] = $this->news_model->getDefaults(); // ( or just array();)  no id -> it's an insert 
                }

            }

            $this->load->view('/news/input',$data);
    }

并将$ id修改为您视图中的action-url:

    <?php echo form_open('news/upsert/'.$id) ?>