I want to store my saved session "POSTS" in an array so I can display them in Index.ctp. I save my posts in session by clicking on a link from Index.ctp. I don't know how to display all my saved posts from session in Index.ctp.
I made the link " add To Favourites" from index.ctp, and the 2 functions in PostsController.
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; ?>
“I expect the output of 5/2 to be 2.5, but the actual output is 0.5.
I did not test the overall idea, but at least code that saves the favorite should be:
The above does NOT check/prevent if the same post is saved multiple times.