0

我有一个模态表单,用于对记录进行更新。表单似乎可以提交,浏览器中的 URL 指向正确的位置(domain.net/cities/update_city/1),但没有显示视图,并且记录从未更新。我搜索了互联网,但大多数教程似乎都略过更新或硬编码要更新的 id。我只使用 CI 一个星期。

型号代码

// Edit City
function edit_city($city_id) {
    $data = array('city_name' => $this->input->post('city_name'));
    $this->db->where('city_id', $city_id);
    $this->db->update('cities', $data);
}

查看代码(表单处于模态并获取由 jQuery 添加的 city_id)

<div class="modal-body">
    <?php $this->load->helper('form'); ?>
        <?php echo form_open('/cities/update_city/'); ?>
        <label class="control-label" for="name">City</label>
        <input type="text" name="city_name" id="city_name" value=""/><br />
        <input type="submit" name="submit" class="btn-small btn-primary" value="Edit City" />
        <button class="btn-small" data-dismiss="modal">Cancel</button>
    <?php echo form_close(); ?>
</div>
<script>
  // scripts for modal windows
      $(document).on("click", ".edit-modal", function () {
      var city_name = $(this).data('name');
      var city_id = $(this).data('id');
      $(".modal-body #city_name").val( city_name );
      //set the forms action to include the city_id
      $(".modal-body form").attr('action','/cities/update_city/'+city_id);
      $('#editCityDialog').modal('show');
  });       

控制器代码

// Update City
function update_city($city_id) {
$this->load->model('cities_model');

    if ($this->input->post('submit')) {
        $data = array('city_name' => $this->input->post('city_name'));

        $this->cities_model->edit_city('cities', array('city_id' => $city_id),$data);
        redirect('/cities');
    }
}
4

1 回答 1

1

这是一个示例,您可以使用它轻松更新(我的英语不好,对不起)。

模型:

class Cities_model extends CI_Model{
    function edit($table,$where,$data){
       foreach ($where as $key => $value){
            $this->db->where($key,$value);
        }
        $this->db->update($table,$data);        
    }
}

控制器:

    function update_city($city_id){
    $this->load->model('cities_model');
         if($this->input->post('submit'){
         $data = array('city_name' => $this->input->post('city_name'));

         $this->cities_model->edit('cities',array('city_id' => $city_id),$data); //(table,where,data); see in model.
         redirect(''); 
         }
     }

*如果你去一个链接为“http://......update_city/2”和一个函数 update_city($city_id),$city_id 将接收为“2”,你不需要写 uri_segment 来获取 $city_id . 希望对你有帮助

编辑 :

控制器:

function update_city($city_id) {
$this->load->model('cities_model');

if ($this->input->post('submit')) {
    $this->cities_model->edit_city($city_id);
    redirect('/cities');
}

}

于 2012-11-14T02:09:18.480 回答