Cakephp博客tutoria-个别文章的评论部分

时间:2014-07-23 08:52:14

标签: jquery database cakephp show-hide

我是cakephp的新手,最近完成了博客教程,现在我想到了一个评论部分。我在那方面取得了成功。以下是我的控制器。

控制器

public function add_comment() {

        if ($this->request->is('post')) {

            $this->Comment->create();
            if ($this->Comment->save($this->request->data)) {
                $this->Session->setFlash(__('Your comment has been saved.'));
                $this->redirect(array('controller' => 'posts', 
                                      'action' => 'index', 
                                      'admin' => false));
            }
            $this->Session->setFlash(__('Unable to add your post.'));
        }
    }

查看

echo "<h1>Comments </h1>";

foreach ($post['Comment'] as $key => $the) {

echo"<div id='comment-{$post['Comment'][$key]['id']}'>";
echo "Name: ", $the['name'], '<br>';
echo "Comment: ", '<br />', $the['comment'], '<br>';
echo '</div>';

添加和显示评论是成功的。这是我陷入困境的部分。下面的代码是视图的延续。它的作用是呈现两个按钮,显示和隐藏。

if ($this->Session->read('Auth.User')) {
    echo $this->Form->button('Show', 
             array('type' => 'button',
                   'class' => 'show_comment',
                   'data-id' => $post['Comment'][$key]['id'],
                    ));

    echo $this->Form->button('Hide', 
             array('type' => 'button',
                   'class' => 'hide_comment',
                   'data-id' => $post['Comment'][$key]['id'],
                   ));
}

main.js - 下面是隐藏/显示点击评论的jquery函数

$(document).ready(function() {
    $(".hide_comment").click(function() {
        var id = $(this).data('id');
        console.log($(this).data('id'));
        $('#comment-' + id).hide();
    });

    $(".show_comment").click(function() {
        var id = $(this).data('id');
        console.log($(this).data('id'));
        $('#comment-' + id).show();
    });
});

我想要实现的是,当管理员登录时,他可以隐藏或显示评论?但是,一旦重新加载/刷新页面,隐藏的评论将再次显示。在单击“显示”按钮之前,如何使隐藏的注释保持隐藏状态。这是我隐藏/显示评论的方法,但我对你的建议非常开放。非常需要你的帮助,谢谢你

1 个答案:

答案 0 :(得分:0)

您需要在表格中添加一个字段,并确定是否隐藏了评论。 例如,假设您刚输入的字段为“隐藏”类型bool,则您的评论搜索应为:

$comments = $this->Comment->find('all', array(
    'conditions' => array(
        'Comment.hidden' => false
    )
)

使用该条件,隐藏的注释将不会显示。 您可以添加两个函数来隐藏和显示您的注释,并通过ajax请求em。

public function comment_show($id = null) {

    if ($this->request->is('ajax') {

        $this->Comment->id = $id;
        $this->Comment->saveField('hidden', false);

    }

}

public function comment_hide($id = null) {

    if ($this->request->is('ajax') {

        $this->Comment->id = $id;
        $this->Comment->saveField('hidden',true);

    }

}

请记住,它只是一个插图,没有验证,访问级别检查等。