Как отобразить список сохраненных сеансов сообщений в index.ctp в CAKEPHP 2.10.15 - PullRequest
0 голосов
/ 21 июня 2019

Я хочу сохранить свою сохраненную сессию "POSTS" в массиве, чтобы я мог отобразить их в Index.ctp. Я сохраняю свои сообщения в сессии, нажимая на ссылку из Index.ctp. Я не знаю, как отобразить все мои сохраненные сообщения из сессии в Index.ctp.

Я сделал ссылку «добавить в избранное» из index.ctp, а две функции в 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; ?>

«Я ожидаю, что выход 5/2 будет 2,5, но фактический выход составляет 0,5.

1 Ответ

0 голосов
/ 25 июня 2019

Я не проверял общую идею, но по крайней мере код, который сохраняет избранное, должен быть:

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

Вышеприведенное НЕ проверяет / не предотвращает сохранение одного и того же сообщения несколько раз.

...