cakephp-2.3 - 如何在 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。
解决方案
我没有测试整体思路,但至少保存收藏夹的代码应该是:
// 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);
如果多次保存同一个帖子,上述内容不会检查/防止。
推荐阅读
- kubernetes - 如何使用文件升级 helm chart 部署
- c# - 尝试使用 Ionic4 连接到 WCF Web 服务器
- macos - /bin/bash: --timeout: 在 macOS 上找不到命令
- java - 如何通过反射从父类调用子类方法
- android - 任务“:app:transformClassesWithDesugarForDebug”执行失败
- javascript - 使用量角器在 Safari 上的 iframe 中找不到元素
- hibernate - spring data 和 hibernate 将字符串参数更改为 unicode\ASCII
- machine-learning - 如何向 keras Retina 网络添加 dropout 技术?
- javascript - 我应该如何在前端处理 tslint no-null-keyword?
- html - 下拉菜单只在每个按钮悬停时打开一个下拉框