0

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

模型(在 news_model.php)

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

控制器(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" /> 
4

1 回答 1

1

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

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

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

编辑:

创建更新/插入(upsert)控制器更改如下:

控制器:

        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) ?>
于 2013-02-17T14:48:59.140 回答