【问题标题】:How to display data from another controller in pages? CakePHP 4.x如何在页面中显示来自另一个控制器的数据? CakePHP 4.x
【发布时间】:2023-03-22 18:19:01
【问题描述】:

我想将文章连接到页面,但在最后一屏出现错误。

【问题讨论】:

标签: php cakephp cakephp-4.x


【解决方案1】:

在您的主页操作中

public function homepage() {
    $this->loadModel('Articles');
    $lastArticles = $this->Articles->find('all', ['limit' => 3, 'order' => 'Articles.created DESC'])->toArray();

$this->set('lastArticles', $lastArticles);

}

View::set 需要 2 个参数,一个是视图中变量的名称,第二个是视图中该变量的值。

【讨论】:

    【解决方案2】:

    您在 PageController.php 中,除了 display() 方法之外,我从未将该控制器用于其他用途。我不知道你这样做是否是预期用途。

    如果您想列出您的文章,我建议您在 ArticlesController.php 中进行设置。

    //in src/Controller/ArticlesController.php
    public function home() {
    $lastArticles = $this->Articles->find('all', ['limit' => 3, 'order' => 'Articles.created DESC']);
      $this->set('lastArticles', $lastArticles);
    } 
    

    然后您需要创建一个视图模板,名称对应于控制器(see Naming Conventions) 中的方法名称 - 对于我发布的方法,它是“home.php”。

    //in templates/Articles/home.php
    <?php foreach ($lastArticles as $lastArticle): ?>
    //.. your fields ..
     <?php endforeach; ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 2022-06-15
      相关资源
      最近更新 更多