Symfony – How to create entity with a form and DTO

I want to create entity with symfony form and DTO. I tried to do DTO and form like I’ve seen on symfonycast. But there’s something wrong and I can’t figure it out.

After sending json file via postman I get an error:

Typed property AppFormModelCreateFacilityDTO::$pitchTypes must not be accessed before initialization (500 Internal Server Error)

postman body:

"name": "legia",
"pitchTypes": ["basketball"],
"address": "kosynierów"

Can You tell me what I’m doing wrong?


namespace AppController;

use AppEntityFacility;
use AppFormCreateFacilityFormType;
use AppFormModelCreateFacilityDTO;
use DoctrineORMEntityManagerInterface;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;

 * @method saveEntities(array $array)
class CreateFacilityAction extends AbstractController
     * @Route("/api/create/facility", name="create_facility")
     * @param Request $request
     * @return Response
    public function __invoke(Request $request, EntityManagerInterface $em)
        $form = $this->createForm(CreateFacilityFormType::class);
        $data = json_decode($request->getContent(), true);
//        if ($form->isSubmitted() && $form->isValid()) {
            /** @var CreateFacilityDTO $facilityDto */
            $facilityDto = $form->getData();
            $createFacility = new Facility($facilityDto->name, $facilityDto->pitchTypes,

            $em = $this->getDoctrine()->getManager();
//            return new Response($data, 201);
//        }
        return new Response($createFacility, 201);


namespace AppForm;

use AppFormModelCreateFacilityDTO;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;

class CreateFacilityFormType extends AbstractType
    public function buildForm(FormBuilderInterface $builder, array $options)

    public function configureOptions(OptionsResolver $resolver)
            'data_class' => CreateFacilityDTO::class,


namespace AppFormModel;

 class CreateFacilityDTO
    public string $name;

    public array $pitchTypes;

    public string $address;

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *