Home > Back-end >  Symfony doesn't display form properly
Symfony doesn't display form properly

Time:09-19

I tried to display a simply form that I built in SearchType.php. In my controller, the form is supposed to be displayed with the route /search. But we we go there, I have just one input while I defined two input in SearchType.php. Note : this input is not even a selection, I only can enter text.

search.html.twig

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

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

{% block main %}

    {{ form(form) }}

{% endblock %}

SearchType.php

<?php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

class SearchType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('bigcity', ChoiceType::class, [
                'choices' => [
                    'Je sélectionne une ville' => '',
                    'Paris, France' => 'paris'
                ]
            ])
            ->add('category', ChoiceType::class, [
                'choices' => [
                    "Je sélectionne un type d'activité" => '',
                    'Eat Zpeak !' => 'eatzpeak',
                    'Party Zpeak !' => 'partyzpeak',
                    'Run Zpeak !' => 'runzpeak',
                    'Art Zpeak !' => 'artzpeak',
                ]
            ])
            ->add('save', SubmitType::class)
        ;
    }

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

EventsController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Form\Extension\Core\Type\SearchType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class EventsController extends AbstractController
{   
    #[Route('/search', name: 'search')]
    public function search(Request $request)
    {   
        $form = $this->createForm(SearchType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getData();
            return $this->render('front/events.html.twig', $data);
        }
        return $this->render('front/search.html.twig', [
            'form' => $form->createView()
        ]);
    }
}

CodePudding user response:

You are usinig a bad class import in your controller

use Symfony\Component\Form\Extension\Core\Type\SearchType;

You should use the namespace of your formType

App\Form\SearchType

  • Related