I want to get the list of all the customers to put it in a global variable.
For that, I configure the twig.yaml file:
twig:
default_path: '%kernel.project_dir%/templates'
globals:
orders: '@App\Twig\OrderExtension'
Then, I create a file OrderExtension.php in the folder src>Twig
<?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();
}
}
But I have this error: Call to a member function getRepository() on null
I tested the global "orders" by changing the getOrders function and asking it to return a simple string.
I called the global in my base.html.twig file and it displayed the desired string.
How do I make sure I get an array of my orders?
First of all dump $this->em inside your function and make sure that the connection with database exists.
Maybe do not define it as globals, but just call it as a function
{{ orders() }}
Then you can iterate through this
{% for order in orders() %}
{% endfor %}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.