【问题标题】:How to display a stored session list of posts in index.ctp in CAKEPHP 2.10.15如何在 CAKEPHP 2.10.15 中的 index.ctp 中显示存储的帖子会话列表
【发布时间】:2019-06-21 12:06:31
【问题描述】:

我想将保存的会话“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.3 cakephp-2.1 cakephp-2.5


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多