首页 > 解决方案 > Codeigniter 3 博客应用程序:重定向到更新的帖子失败

问题描述

我正在Codeigniter 3.1.8 中开发一个基本的(只有 2 个表:作者帖子)博客应用程序。

我有一个编辑帖子功能,使用更新表单:

<?php echo form_open("posts/update"); ?>
      <input type="hidden" name="id" id="pid" value="<?php echo $post->id; ?>">
      <div class="form-group <?php if(form_error('title')) echo 'has-error';?>">
        <input type="text" name="title" id="title" class="form-control" placeholder="Title" value="<?php echo $post->title; ?>">
        <?php if(form_error('title')) echo form_error('title'); ?> 
      </div>
      <div class="form-group <?php if(form_error('desc')) echo 'has-error';?>">
        <input type="text" name="desc" id="desc" class="form-control" placeholder="Short decription" value="<?php echo $post->description; ?>">
        <?php if(form_error('desc')) echo form_error('desc'); ?> 
      </div>
      <div class="form-group <?php if(form_error('body')) echo 'has-error';?>">
        <textarea name="body" id="body" cols="30" rows="5" class="form-control" placeholder="Add post body"><?php echo $post->content; ?></textarea>
        <?php if(form_error('body')) echo form_error('body'); ?> 
      </div>
      <div class="form-group">
        <input type="submit" value="Save" class="btn btn-block btn-md btn-success">
      </div>
<?php echo form_close(); ?>

Posts_model模型中,我有负责更新帖子的方法:

public function update_post() {
    $data = [
        'title' => $this->input->post('title'),
        'description' => $this->input->post('desc'),
        'content' => $this->input->post('body')
    ];
    $this->db->where('id', $this->input->post('id'));
    return $this->db->update('posts', $data);
}

在 Posts 控制器中,我有 2 种方法用于编辑和更新帖子:

public function edit($id) {
    $data = $this->Static_model->get_static_data();
    $data['post'] = $this->Posts_model->get_post($id);
    $data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
    $this->load->view('partials/header', $data);
    $this->load->view('edit');
    $this->load->view('partials/footer');
}

public function update() {
    $this->Posts_model->update_post();
    // Redirect to the updated post

}

在我的 update() 方法中,我无法重定向到更新的帖子。这redirect($this->agent->referrer());条线只会让我回到更新表格。我要重定向到的地方是刚刚更新的帖子。我怎么做?

标签: phpcodeigniterredirect

解决方案


Post vars 应该在你的控制器中处理:

public function update() {
    $id = $this->input->post('id');
    $data = [
        'title' => $this->input->post('title'),
        'description' => $this->input->post('desc'),
        'content' => $this->input->post('body')
    ];
    // Update post
    $this->Posts_model->update_post($id, $data);
    // Redirect to the updated post
    redirect('posts/post/' . $id);
}

模型:

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

注意:如果您想按照自己的方式进行操作,则只需在模型函数中返回 id 并根据函数的返回进行重定向update()


推荐阅读