fleeting
fleeting

Reputation: 123

CakePHP - Set viewVar from within EventListener

I have the following event listener but want to set a viewVar from it and having some issues figuring out how. If I can't or shouldn't, what would be the best way when I need $products available to the View?

File is ./Products/Lib/Event/Products.php.

<?php
App::uses('CakeEventListener', 'Event');

class Products implements CakeEventListener {
    public function implementedEvents() {
        return array(
            'View.beforeRender' => 'get_products',
        );
    }

    public function get_products($event) {
        $this->Product = ClassRegistry::init('Products.Product');

        $products = $this->Product->find('all', array(
            'fields' => array('Product.*', 'Content.title')
        ));

        $this->set('products', $products);
    }
}

Returns Fatal error: Uncaught Error: Call to undefined method Products::set().

Upvotes: 1

Views: 136

Answers (1)

ndm
ndm

Reputation: 60473

You are subscribing to an event triggered by a View object, hence the subject of the event will be that object, and you can access it in your listener method via the event objects subject() method, like:

$event->subject()->set('products', $products);

See also

Upvotes: 1

Related Questions