Home > Blockchain >  Convert POST Request to Doctrine Entity
Convert POST Request to Doctrine Entity

Time:04-22

Coming from a NodeJS environment, this seems like a nobrainer but I somehow did not figured it out.

given the function:

    /**
     * @Route("/", name="create_stuff", methods={"POST"})
     */
    public function createTouristAttraction($futureEntity): JsonResponse
    {
      ...
     }

Let futureEntity have the same structure as my PersonEntity.

What is the best way of mapping that $futureEntity to a PersonEntity?

I tried to assign it manually, and then run my validations which seems to work, but i think this is cumbersome if a model has more than 30 fields...

Hint: Im on Symfony 4.4

Thank you!

CodePudding user response:

Doc: How to process forms in Symfony

  1. You need to install the Form bundle: composer require symfony/form (or composer require form if you have the Flex bundle installed)

  2. Create a new App\Form\PersonType class to set the fields of your form and more: doc

  3. In App\Controller\PersonController, when you instanciate the Form, just pass PersonType::class as a first parameter, and an new empty Person entity as a second one (the Form bundle will take care of the rest):


$person = new Person();
$form = $this->createForm(PersonType::class, $person);

The whole controller code:

<?php

namespace App\Controller;

use App\Entity\Person;
use App\Form\PersonType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class PersonController extends AbstractController
{

    private $entityManager;

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

    /**
     * @Route("/person/new", name="person_new")
     */
    public function new(Request $request): Response
    {
        $person = new Person(); // <- new empty entity
        $form = $this->createForm(PersonType::class, $person);

        // handle request (check if the form has been submited and is valid)
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) { 

            $person = $form->getData(); // <- fill the entity with the form data

            // persist entity
            $this->entityManager->persist($person);
            $this->entityManager->flush();

            // (optionnal) success notification
            $this->addFlash('success', 'New person saved!');

            // (optionnal) redirect
            return $this->redirectToRoute('person_success');
        }

        return $this->renderForm('person/new.html.twig', [
            'personForm' => $form->createView(),
        ]);
    }
}
  1. The minimum to display your form in templates/person/new.html.twig: just add {{ form(form) }} where you want.
  • Related