I am trying to use content filled from a controller inside an element so I can use the content to build a view.
So far I have the following element (.ctp file)
<?php $categories = $this->requestAction('categories/menu'); ?>
<ul class="hidden">
<?php foreach ($categories as $categorie): ?>
<li><?= $this->Html->link($categorie->name, '#'); ?></li>
<?php endforeach; ?>
</ul>
with this controller
class CategoriesController extends AppController
{
public function index()
{
$categories = $this->Categories->find('all');
$this->set(compact('categories'));
}
public function menu()
{
$categories = $this->paginate();
$this->set('categories', $categories);
}
}
When using the code from here I got an error in the log and nothing display on the page Error: [Cake\View\Exception\MissingTemplateException] Template file "Categories\menu.ctp" is missing.
.
If I change this ligne $this->set('categories', $categories);for this one return $categories; I have the following error displaying on my page Error: Controller action can only return an instance of Response.
I originally tryed the code from this tutorial (sorry for the scrolling just go to the last example before Caching Elements) but it lead to the second error message.
How can I use a Controller from an Element?
This is the expected behavior, a controller needs a view template to render unless you explicitly disabled/circumvent view rendering by either setting Controller::$autoRender to false, by making the method return a Response object, or by using serialized data views.
The latter is what the error message tells you the method is expected to return, see http://book.cakephp.org/3.0/en/controllers.html#controller-actions
When you use controller methods with
Routing\RequestActionTrait::requestAction()you will typcially return aResponseinstance. If you have controller methods that are used for normal web requests + requestAction, you should check the request type before returning// src/Controller/RecipesController.php class RecipesController extends AppController { public function popular() { $popular = $this->Recipes->find('popular'); if (!$this->request->is('requested')) { $this->response->body(json_encode($popular)); return $this->response; } $this->set('popular', $popular); } }[...]
As it looks like you just want to fetch and render model data, I'd suggest to check out view cells.
http://book.cakephp.org/3.0/en/views/cells.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With