php - 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());
条线只会让我回到更新表格。我要重定向到的地方是刚刚更新的帖子。我怎么做?
解决方案
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()
推荐阅读
- java - 使用任何 JavaFX 指令时 Gradle 项目中的 IllegalAccessError
- java - Spring Batch:处理块后发送通知
- matlab - 如何在MATLAB中为矩阵的列向量生成所有可能的组合?
- .net-core - 错误消息“在更新模式下无法多次打开条目。” 在电子表格精简版另存为功能
- android - EditText 的内置滚动在键盘显示时不会滚动到最后 - 键盘隐藏底部的文本
- c# - BinaryReader 读取值列表 C#
- python-3.x - 如何定义可调用的导数函数
- r - ggplot2按形状分隔图例
- terraform - Terraform:为什么不接受扩展运算符?
- javascript - 将滚动条添加到 div 而不是滚动整个页面