簡體   English   中英

Symfony:創建 Twig 分機時出錯 function:調用成員 function findAll() on null

[英]Symfony : Error when create a Twig Extension function : Call to a member function findAll() on null

我想獲取所有客戶的列表以將其放入全局變量中。

為此,我配置了 twig.yaml 文件:

twig:
default_path: '%kernel.project_dir%/templates'
globals:
    orders: '@App\Twig\OrderExtension'

然后,我在文件夾 src>Twig 中創建一個文件 OrderExtension.php

<?php

namespace App\Twig;

use App\Entity\Orders;
use Twig\TwigFunction;
use Twig\Extension\AbstractExtension;
use Doctrine\Persistence\ManagerRegistry;

class OrderExtension extends AbstractExtension {
    private $em;

    public function __construt(ManagerRegistry $em) {
        $this->em = $em;
    }

    public function getFunctions(): array {
        return [
            new TwigFunction('orders', [$this, 'getOrders'])
        ];
    }

    public function getOrders() {
        return $this->em->getRepository(Orders::class)->findAll();

    }

    
}

但是我有這個錯誤:在 null 上調用成員 function getRepository()

我通過更改 getOrders function 並要求它返回一個簡單的字符串來測試全局“訂單”。

我在我的 base.html.twig 文件中調用了 global,它顯示了所需的字符串。

我如何確保收到一系列訂單?

首先將 $this->em 轉儲到您的 function 中,並確保與數據庫的連接存在。

也許不要將其定義為全局變量,而將其稱為 function

{{ orders() }}

然后你可以遍歷這個

{% for order in orders() %}
{% endfor %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM