cakephp 3 and view cells with use of Cookie

1.3k views Asked by At

I can't find any info about using $this->Cookie in view cells. When i wrote code like this, error will arise:

namespace App\View\Cell;

use Cake\View\Cell;

class CityCell extends Cell {

  public function display() {
      $this->Cookie->config('encryption', false);
      $cookie = $this->Cookie->read('city');
  }
}

and the error is: Error: Call to a member function read() on null

So can we use cookie in view cells ?

Thank You.

1

There are 1 answers

1
ndm On BEST ANSWER

That of course won't work, view cells do not support the use of components, altough they can be thought of like "mini-controllers", they are not actually controllers in the terms of CakePHPs MVC system.

Depending on whether the cookies are encrypted, you can either use the request object to fetch them in your cell

$this->request->cookie('cookieName')

or

$this->request->cookies

see also API > \Cake\Network\Request::cookie()

or, in case they are encrypted, you have grab them via the Cookie component, and then for example pass them down from your controller to the view, and finally into the cell like

controller

public function controllerAction() {
    // ...
    $this->set('cookie', $this->Cookie->read('cookieName'));
}

cell

public function display($cookie) {
    // ...
}

view

$this->cell('CellName', ['cookie' => $cookie]);

see also Cookbook > Views > View Cells > Passing Arguments to a Cell