Я пытаюсь передать данные из контроллера для просмотра, но когда я передал данные, я получаю следующую ошибку
Variable "products" does not exist.
Пожалуйста, найдите мой код контроллера ниже
<?php
namespace App\Controller;
USE App\Entity\Product;
use App\Repository\ProductRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class ProductController extends AbstractController
{
//#[Route('/product', name: 'app_product')]
public function index(): Response
{
return $this->render('product/index.html.twig', [
'controller_name' => 'ProductController',
]);
}
public function show(EntityManagerInterface $entityManager): Response
{
$products = $entityManager->getRepository(Product::class)->findAll();
if (!$products) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
else{
return $this->render('product/index.html.twig', ['product' => $products]);
}
}
}
Пожалуйста, найдите мой код шаблона ветки ниже
<form action = "{{ path('home') }}">
<fieldset>
<label class = "all-label">Product</label>
<div class = "input-group mb-3 select-down">
<select class = "form-select form-control" aria-label = "Default select example" name = "product">
{% for product in products %}
<option value = "{{ product.id }}">{{ product.name }}</option>
{% endfor %}
</select>
</div>
</fieldset>
</form>
Коды в файле route.yaml
controllers:
resource:
path: ../src/Controller/
namespace: App\Controller
type: attribute
home:
path: /
controller: App\Controller\HomeController::index
create:
path: /create
controller: App\Controller\MainController::create
test:
path: /xavier
controller: App\Controller\HomeController::index
product:
path: /product
controller: App\Controller\ProductController::index
Почему я получаю эту ошибку, когда я пытался получить значение $ product, я также получаю данные. Почему он показывает ошибку Variable "products" does not exist
Пытаюсь загрузить страницу
http://127.0.0.1:8000/product
@rickroyce Я отредактировал файл и получил ту же ошибку
@ Робби оба одинаковы, в чем разница между ними. Я также добавил URL-адрес, который пытаюсь загрузить в вопросе
@XavierIssac Чем они похожи? Вы явно опечатались: ['product' => $products] VS ['products' => $products]





Вот ваш ответ:
вы звоните по этому маршруту /product
ваша конфигурация здесь говорит, что используйте ProductController с методом index():
product:
path: /product
controller: App\Controller\ProductController::index
контроллер индекса отображает шаблон ветки со следующими переменными (controller_name):
return $this->render('product/index.html.twig', [
'controller_name' => 'ProductController',
]);
измените свой маршрут продукта на метод show, чтобы вызвать правильный метод контроллера:
product:
path: /product
controller: App\Controller\ProductController::show
или поместите «продукты» в качестве переменной в методе index():
//#[Route('/product', name: 'app_product')]
public function index(): Response
{
$products = []; // insert products here
return $this->render('product/index.html.twig', [
'controller_name' => 'ProductController',
'products' => $products,
]);
}
Это не имеет ничего общего с маршрутизацией. ОП сделал опечатку, смотрите комментарии
или поместите «продукты» в качестве переменной в метод index(): это не сработает
пожалуйста, поделитесь конфигурацией маршрута, чтобы увидеть, какой маршрут вы вызываете и какой контроллер используется для рендеринга ваших шаблонов. затем вы должны назвать и показать оба файла ветки. кажется, есть
product/index.html.twigиindex.html.twig. и в вашем контроллере есть запах кода. просто верните продукты из репозитория. и используйте twig, чтобы реагировать, если переменная products пуста.