【发布时间】:2013-10-28 10:22:47
【问题描述】:
我需要一些帮助。我有一个包含完整帖子的帖子页面,在帖子下方有一个用于添加 cmets 的小表格。 post页面的uri是:site/posts/1,所以在posts控制器里,form action是form_open(site_url('comments/add/'.$post->post_id))。
这是我在 cmets 控制器中的 add() 函数:
public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$result = $this->comment_model->add($post_id);
if ($result !== false) {
redirect('posts/'.$post_id);
}
// TODO:load the view if required
}
这是注释模型中的 add() 函数
public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
if ($this->validate($post_data)) {
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
} else {
return false;
}
}
我想要做的是如果 $result = $this->comment_model->add($post_id);验证失败以在我的帖子视图中显示验证错误,否则插入评论并重定向到同一帖子页面(站点/帖子/1)。
问题是,当我点击提交时,表单操作按预期进入 cmets/add/1,但没有执行上述任何操作。
有什么办法可以解决这个问题吗?
编辑 我对代码做了一些小改动,但没有使用“令人困惑”的 validate() 函数。也许这更有帮助。
评论控制器:
public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$this->form_validation->set_rules($this->comment_model->rules);
if ($this->form_validation->run() == true) {
echo "Ok! TODO save the comment.";
// $this->comment_model->add($post_id);
// redirect('posts/'.$post_id);
} else {
echo "Validation Failed! TODO: show validation errors!";
}
// TODO:load the view if required
}
评论模型:
public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
}
【问题讨论】:
-
你的
function validate()在哪里? -
是的,这个函数执行验证。它在 MY_Model 里面见:github.com/jamierumbelow/codeigniter-base-model/blob/master/…
-
当您提交表单时,它是否进入了
if ($this->form_validation->run() == true) { ... }语句? -
是的,如果我提交正确的表单,它会进入 if 语句,否则会进入 else .. 问题是我无法弄清楚如何在帖子上显示验证错误页面(在我的示例中:site/posts/1)
标签: php codeigniter codeigniter-2 codeigniter-url