如何使用Symfony检索搜索表单中提供的数据?错误:变量不存在

eufgjt7s  于 2022-11-16  发布在  其他
关注(0)|答案(3)|浏览(101)

我尝试显示用户根据以下两个功能选择的事件列表:大城市和类别。所以他需要在登陆活动页面之前用搜索表单选择“大城市”和“类别”。
首先,我成功地在标签中显示选定的信息,但当我试图显示事件列表时,我得到了这个错误Variable "category" does not exist.,就像我的小枝或我的控制器“忘记”什么是大城市和类别。
我不明白这有什么问题。

事件控制器.php

<?php

namespace App\Controller\Front;

use App\Form\SearchType;
use App\Repository\EventsRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class EventsController extends AbstractController
{
    #[Route('/search', name: 'search')]
    public function search(
        Request $request, 
        SessionInterface $sessionInterface,
    ){   
        $data = $request->request->all();
        $sessionSearchFormData  = $sessionInterface->get('searchFormData');

        $form = $this->createForm(SearchType::class, ['data' => $sessionSearchFormData]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $data = $form->getData();
            $sessionInterface->set('searchFormData', $data);
            return $this->redirectToRoute('events', [$data]);
        }
        return $this->renderForm('front/search.html.twig', [ 
            'form' => $form,
        ]);
    }

    #[Route('/events', name: 'events')]
    public function events(
        EventsRepository $eventsRepository, 
    ){
        $events = $eventsRepository->findAll();
        return $this->render("front/events.html.twig", ['events' => $events]);
    }
}

搜索.html.twig

{% extends 'base.html.twig' %}

{% block title %}Liste des sorties et des activités !{% endblock %}

{% block main %}

{{ form_start(form) }}

    <p>Où souhaites-tu faire une sortie ou une activité ?</p>
    {{ form_widget(form.bigcity) }}

    <p>Quel type de sortie ou d’activité t’intéresse ?</p>
    {{ form_widget(form.category) }}

    {{ form_widget(form.save, {'label': 'Je valide') }}

{{ form_end(form) }}

</div>

{% endblock %}

事件.html.twig

{% extends 'base.html.twig' %}

{% block title %}Liste des activités {{ category.title }} à {{ bigcity.name }}{% endblock %}

{% block main %}

<div class="events">

    <h1 class="display-6 pt-3">
        <img src="{{ asset('img/logos/') }}{{ category.image }}" alt="{{ category.title }}" width="auto" height="40">
        à <b class="me-1">{{ bigcity.name }}</b>
    </h1>

    <div class="vr fixed-top start-50"></div>

    <div class="row">

        <div class="col-12 col-md-6">

            <h2 class="text-center my-4">
                <img src="{{ asset('img/titres/zpeak-sorties.svg') }}" alt="Les Zpeak Sorties !">
            </h2>

            <ul class="list-group">

            {% for event in events %}
                    
            {% if event and event.organizer.status == 'organizer' %}

                <a class="list-group-item list-group-item-action">
                    <img src="{{ asset('img/flag_images/' ~ event.spokenlanguage.image) }}" alt="Drapeau {{ event.spokenlanguage.name }}" class="me-2"> {{ event.title }}
                </a>

            {% else %}

                <p>Il n'y a pas de zpeak sortie organisée.</p>

            {% endif %}

            {% endfor %}

            </ul>

        </div>

        <div class="col-12 col-md-6">

            <h2 class="text-center my-4">
                <img src="{{ asset('img/titres/zpeak-idees.svg') }}" alt="Les Zpeak Idées !">
            </h2>

            <ul class="list-group">

            {% for event in events %}
            
            {% if event and event.organizer.status == 'member' %}
                    
                <a class="list-group-item list-group-item-action">
                    <img src="{{ asset('img/flag_images/' ~ event.spokenlanguage.image) }}" alt="Drapeau {{ event.spokenlanguage.name }}" class="me-2"> {{ event.title }}
                </a>

            {% else %}

                <p>Il n'y a pas de zpeak idée proposée.</p>

            {% endif %}

            {% endfor %}

            </ul>
            
        </div>
    
    </div>

</div>

{% endblock %}

搜索类型.php

<?php

namespace App\Form;

use App\Entity\BigCity;
use App\Entity\Categories;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class SearchType extends AbstractType
{
    private EntityManagerInterface $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $bigcity = $options['sessionSearchFormData'] !== null ? $options['sessionSearchFormData']['bigcity'] : '';
        $category = $options['sessionSearchFormData'] !== null ? $options['sessionSearchFormData']['category'] : '';

        $builder
            ->add('bigcity', EntityType::class, [
                'class' => BigCity::class,
                'choice_label' => 'name',
                'placeholder' => 'Sélectionne une grande ville',
                'data'=> $bigcity !== null ? $this->entityManager->getRepository(BigCity::class)->find($bigcity) : '',
            ])
            ->add('category', EntityType::class, [
                'class' => Categories::class,
                'choice_label' => 'image',
                'expanded' => true,
                'multiple' => false,
                'data'=> $category !== null ? $this->entityManager->getRepository(Categories::class)->find($category) : '',
            ])
            ->add('save', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => null,
            'sessionSearchFormData' => null,
        ]);
    }
}
bxjv4tth

bxjv4tth1#

错误就在这里

{% block title %}Liste des activités {{ category.title }} à {{ bigcity.name }}{% endblock %}

当你说{{ category.title }}或{{bigcity.name}}时,这意味着你调用一个变量类别,基本上(并非总是)变量在控制器中声明,并在返回render...
在你的例子中,你把一个变量类别作为一个对象来调用,变量类别和对象都不存在,那么细枝怎么知道它们呢?
第二件事,category可能作为参数而不是完整的对象存在于url中,我猜是category的id(例如&category=5&...)
所以你应该做的是在events函数中检索这个参数,如果它存在,你必须从数据库中选择具有这个id的类别,或者如果你只需要他的名字,就选择他的名字,然后你在return render中传递这个变量,不要忘记做一些测试,如果存在的话,不要出错

#[Route('/events', name: 'events')]
public function events(Request $request, EventsRepository $eventsRepository, CategoriesRepository $categoriesRepository)
{
    $data = $request->request->all();
    $events = $eventsRepository->findAll();
    $categories = $categoriesRepository->findAll();

     $category = null;
    if($request->query->has('category'))
     {
       $categoryId = $request->query->get('category');
       // or
       // $categoryId = $data['category'];
      
      $category = $categoriesRepository->find($categoryId);
     }

    return $this->render("front/events.html.twig", [
       'data' => $data, 
       'events' => $events, 
       'categories' => $categories,
       'category' => $category // pass category to view
   ]);
}

{% if category is not null %}
    {% block title %}Liste des activités {{ category.title }} à {{ bigcity.name }}{% endblock %}
{% endif %}
lvmkulzt

lvmkulzt2#

我终于在这里得到了令人满意的解决办法:

事件控制器.php

<?php

namespace App\Controller\Front;

use App\Form\SearchType;
use App\Repository\BigCityRepository;
use App\Repository\EventsRepository;
use App\Repository\CategoriesRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class EventsController extends AbstractController
{
    #[Route('/search', name: 'search')]
    public function search(
        Request $request, 
        SessionInterface $sessionInterface,
        EventsRepository $eventsRepository,
    ){   
        $data = $request->request->all();
        $sessionSearchFormData  = $sessionInterface->get('searchFormData');

        $form = $this->createForm(SearchType::class, ['data' => $sessionSearchFormData]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $data = $form->getData();
            $sessionInterface->set('searchFormData', $data);
            
            $events = $eventsRepository->findAll();
            
            return $this->render("front/events.html.twig", [
                'bigcity'=> $form->get('bigcity')->getData(), 
                'category'=> $form->get('category')->getData(), 
                'events' => $events
            ]);

        }
        return $this->renderForm('front/search.html.twig', [ 
            'form' => $form,
        ]);
    }
}
zf9nrax1

zf9nrax13#

这是我目前的代码。所有我想做的是传递来自搜索表单的$data中设置的值。我相信有一个解决方案可以做到这一点...非常感谢。

事件控制器.php文件

<?php

namespace App\Controller\Front;

use App\Form\SearchType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class EventsController extends AbstractController
{
    #[Route('/search', name: 'search')]
    public function search(
        Request $request, 
        SessionInterface $sessionInterface,
    ){   
        $data = $request->request->all();
        $sessionSearchFormData  = $sessionInterface->get('searchFormData');

        $form = $this->createForm(SearchType::class, ['data' => $sessionSearchFormData]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $data = $form->getData();
            $sessionInterface->set('searchFormData', $data);

            $dataRequest = [
               'bigcity'=> $form->get('bigcity')->getData() ,
               'category'=> $form->get('category')->getData() 
               ];

            $queryStringParameters = http_build_query($dataRequest);

            $url = $this->generateUrl("events").'?'.$queryStringParameters;
            return $this->redirect($url);
        }
        return $this->render('front/search.html.twig', [ 
            'form' => $form->createView() 
        ]);
    }

    #[Route('/events', name: 'events')]
    public function events(
        EventsRepository $eventsRepository, 
    ){
        $events = $eventsRepository->findAll();
        return $this->render("front/events.html.twig", ['events' => $events]);
    }
}

搜索.html.twig文件

{% extends 'base.html.twig' %}

{% block title %}Liste des sorties et des activités !{% endblock %}

{% block main %}

{{ form_start(form) }}

    <p>Où souhaites-tu faire une sortie ou une activité ?</p>
    {{ form_widget(form.bigcity) }}

    <p>Quel type de sortie ou d’activité t’intéresse ?</p>
    {{ form_widget(form.category) }}

    {{ form_widget(form.save, {'label': 'Je valide') }}

{{ form_end(form) }}

</div>

{% endblock %}

相关问题