guibs35
guibs35

Reputation: 297

Symfony with API Platform + Form and controller

I have started a Symfony 6 project using the classic RegitrationController (that inherits from AbstractController), RegistrationFormType and User entity obtained from:

symfony console make:registration-form

I can now create a user through the form that adds a new entity in my database.

I also wanted to create an API using API Plateform. I have then added a couple modifications to my User schema and the API is working, I can create a user through the API too.

I now wonder how to properly couple the form/controller and the API. Indeed, in order not to have redondant code and use the same User schema, I would like to find a way that my RegistrationFormType works with the API. Also note that on the one hand I have code in my RegitrationController that, e.g., hashes the user password before saving it to the database. On the other hand this is achieved by a UserDataPersister on the API side.

What is the good practice to factorize that code and structure my architecture in order to be able to create users from both the form and the API? (I would like to keep the cool things that the Symfony AbstractController provides like createForm, handleRequest, renderForm, etc.)

I cannot find examples using both Form/Controller and API Plateform.

Is it a bad idea to have the Form/Controller and API in the same project?

Upvotes: 1

Views: 946

Answers (2)

Smoky McPot
Smoky McPot

Reputation: 87

i think it could be done by using Form instance as DTO and feeding it into State processor with a validator, like in this Validating delete operations example. however, i am not sure it will work out of the box with the ApiPlatform validator. writing a custom one which handles Form properly could be required.

Upvotes: 0

Jovan Perovic
Jovan Perovic

Reputation: 20201

When it comes to switching to API Platform, you first have to unlearn what you have learned with more traditional apps :)

Things like creating/rendering forms, and handing requests, are possible, BUT keep in mind that your API accepts, among others, the application/json and not the application/x-www-form-urlencoded.

It all really depends on your choice of client-side code. If you stick to more traditional forms with no React, Angular, or Vue, you send the data in application/x-www-form-urlencoded and your API Platform needs a way to denormalize that.

There is an official article on that topic: https://api-platform.com/docs/core/form-data/, but it has its own perks (such as CSRF handling)

A more common approach is to create a form entirely from scratch using some modern JS framework and just submit the object (in JSON format)

Upvotes: 1

Related Questions