【问题标题】:Can't access controller from element无法从元素访问控制器
【发布时间】:2015-01-29 01:35:02
【问题描述】:

我正在尝试使用从元素内部的控制器填充的内容,以便我可以使用该内容来构建视图。

到目前为止,我有以下元素(.ctp 文件)

<?php $categories = $this->requestAction('categories/menu'); ?>

<ul class="hidden">
    <?php foreach ($categories as $categorie): ?>
    <li><?= $this->Html->link($categorie->name, '#'); ?></li>
    <?php endforeach; ?>
</ul>

用这个控制器

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

使用此处的代码时,日志中出现错误,Error: [Cake\View\Exception\MissingTemplateException] Template file "Categories\menu.ctp" is missing. 页面上没有显示任何内容。

如果我将这个$this-&gt;set('categories', $categories);更改为这个return $categories;,我的页面上会显示以下错误Error: Controller action can only return an instance of Response

我最初尝试了this tutorial 中的代码(抱歉滚动到缓存元素之前的最后一个示例),但它导致了第二条错误消息。

如何使用Element 中的Controller

【问题讨论】:

    标签: cakephp-3.0


    【解决方案1】:

    这是预期的行为,除非您通过将 Controller::$autoRender 设置为 false、使方法返回 Response 对象或使用serialized data views.

    后者是错误信息告诉你方法应该返回的内容,见http://book.cakephp.org/3.0/en/controllers.html#controller-actions

    当您使用带有Routing\RequestActionTrait::requestAction() 的控制器方法时,您通常会返回一个Response 实例。如果您有用于普通 Web 请求 + requestAction 的控制器方法,则应在返回前检查请求类型

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

    [...]

    查看单元格

    由于您似乎只想获取和渲染模型数据,我建议您查看视图单元格。

    http://book.cakephp.org/3.0/en/views/cells.html

    【讨论】:

    • 谢谢。今晚我会看看这个,我会回来给你反馈
    • 我正在寻找的单元格。非常感谢你为我节省了很多小时的头痛
    【解决方案2】:

    您应该拥有以下内容:

    public function menu()
    {
        $categories = $this->Categories->find('all');
        if($this->request->is('requested'):
            $this->response->body($categories);
        endif;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      相关资源
      最近更新 更多