Implementing a Symfony form with a one-to-many relationship shown in a dropdown involves using Symfony's EntityType field type. In this example, we'll create a simple task management application with a Task entity related to a Category entity in a one-to-many relationship. We'll display the categories in a dropdown when creating or editing a task.

 

Create the Entity Classes: Assuming you already have a Task entity class and a Category entity class, make sure they are correctly related with a one-to-many relationship.

// src/Entity/Task.php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class Task
{
    // ... other properties and annotations ...

    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="tasks")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    private $category;

    // ... getters and setters ...
}

// src/Entity/Category.php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class Category
{
    // ... other properties and annotations ...

    /**
     * @ORM\OneToMany(targetEntity="Task", mappedBy="category")
     */
    private $tasks;

    // ... getters and setters ...
}

 

Create the Form Type Class:
Now, create the form type class for the Task entity, including the EntityType field for the Category relationship.

// src/Form/TaskType.php
namespace App\Form;

use App\Entity\Task;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class)
            // Add the EntityType field for the "category" property
            ->add('category', EntityType::class, [
                'class' => 'App\Entity\Category', // Replace with your Category entity class
                'choice_label' => 'name', // Replace with the property to display in the dropdown
                'placeholder' => 'Select a category', // Optional placeholder text
            ]);
    }

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

 

Use the Form in a Controller:
Now, use the form in a controller to handle task creation and editing.

// src/Controller/TaskController.php
namespace App\Controller;

use App\Entity\Task;
use App\Form\TaskType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class TaskController extends AbstractController
{
    /**
     * @Route("/task/create", name="task_create")
     */
    public function createTask(Request $request): Response
    {
        $task = new Task();
        $form = $this->createForm(TaskType::class, $task);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            // Save the task to the database
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($task);
            $entityManager->flush();

            // Redirect to the task list page or show a success message
            return $this->redirectToRoute('task_list');
        }

        return $this->render('task/create_task.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    // ... other actions ...
}

 

Render the Form in a Twig Template:
Finally, render the form in a Twig template.

{# templates/task/create_task.html.twig #}
{% extends 'base.html.twig' %}

{% block content %}
    <h1>Create Task</h1>
    {{ form_start(form) }}
    {{ form_row(form.name) }}
    {{ form_row(form.category) }}
    <button type="submit">Create Task</button>
    {{ form_end(form) }}
{% endblock %}

When you access the /task/create route, you'll see the "Create Task" form with a dropdown to select a category. The categories will be loaded from the database and displayed with their names as options in the dropdown. When you submit the form, the selected category will be associated with the created task.