首页 > 解决方案 > 如何在 CAKEPHP 2.10.15 中的 index.ctp 中显示存储的帖子会话列表

问题描述

我想将保存的会话“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; 
    }

索引.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。

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

解决方案


我没有测试整体思路,但至少保存收藏夹的代码应该是:

// 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);

如果多次保存同一个帖子,上述内容不会检查/防止。


推荐阅读