Rytis
Rytis

Reputation: 1445

CakePHP 3 Component in a Cell

I created my own CakePHP 3 component. I am including it in a Controller using $this->loadComponent() and it works fine; however, I also need to include it in a Cell, which does not have a loadComponent() method.

How can I include a Component in a Cell?

Upvotes: 1

Views: 2319

Answers (2)

Dieter Gribnitz
Dieter Gribnitz

Reputation: 5208

Would not say this is best practice but here is a quick workaround if you need to access a component from a cell.

In your AppController

use Cake\Core\Configure;

class PageController extends AppController
{
    public function initialize()
    {
        Configure::write('controller', $this);
    }
}

In your Cell

<?php
namespace App\View\Cell;

use Cake\Core\Configure;

class ExampleCell extends Cell
{
    public function getController(){
        return Configure::read('controller');
    }
    public function display()
    {
        $data = $this->getController()->ComponentName->method();
        $this->set('data', $data);
    }

}

Upvotes: 4

floriank
floriank

Reputation: 25698

You don't use a component there. Because a cell is a cell and not a controller. A cell doesn't even know about the controller, check the source. http://api.cakephp.org/3.3/source-class-Cake.View.Cell.html

I think your architecture is wrong designed if you need / want to use a component inside a cell any way. Since you "forgot" to share the code it is not possible to give any further advice. Refactor your app architecture for whatever you try to do there.

Upvotes: 3

Related Questions