如何在CAKEPHP 2.10.15中显示index.ctp中帖子的已存储会话列表

时间:2019-06-21 12:06:31

标签: cakephp-2.3 cakephp-2.1 cakephp-2.5

我想将保存的会话“ POSTS”存储在一个数组中,以便可以在Index.ctp中显示它们。 我通过单击Index.ctp中的链接将我的帖子保存在会话中。 我不知道如何在Index.ctp中显示会话中所有已保存的帖子。

我创建了index.ctp中的“添加到收藏夹”链接,以及PostsController中的2个功能。

PostsController.php

public function addToFavourites($id = null){
        if(!$id) {
            throw new NotFoundException(__('Invalid post'));
        }
        $post = $this->Post->findById($id);
        if(!$post){
            throw new NotFoundException(__('Invalid post'));
        }
        $this->Session->write('sa', array($post));
        $data=$this->Session->read('sa');
        if(!empty($data)){
            $this->Session->setFlash('Your stuff has been saved.');
        }
        $this->redirect('/posts/index');
    }
    public function viewFavourites(){
        $data = $this->Session->read('sa');
        $data[] = // I want to store my saved session posts in an array; 
    }

Index.ctp

//It starts with a loop "foreach ($posts as $post) 
   <?php foreach ($posts as $post): ?>
    <tr>
        <td>
            <?php echo $this->Html->link($post['Post']['title'],
            array('action' => 'view', $post['Post']['id']))
            ; ?>
        </td>
        <td>
        <span>
            <?php echo $this->Html->link(
                    'Add to favourites',
                    array('controller' => 'posts',
                       'action' => 'addToFavourites',
                       $post['Post']['id']
                   ))
            ?>
        </span>
      </td>
      </tr>
   <?php endforeach; ?>

“我希望5/2的输出为2.5,但实际输出为0.5。

1 个答案:

答案 0 :(得分:0)

我没有测试整体构想,但是至少保存喜欢的代码应该是:

// Reads current favorites
$data=$this->Session->read('sa');
// Add the new one
$data[] = $post;
// Saves it back into the session
$this->Session->write('sa', $data);

以上内容不会检查/阻止同一帖子是否多次保存。