For the API that I am creating now, I would like to send a request with a JSON body with the following contents
{"title": "foo"}
to create a new database entry for an object called Project .
I created a controller that subclasses FOSRestController . To create a project, I took an action
public function createProjectAction(Request $request) { $project = new Project(); $form = $this->createForm(ProjectType::class, $project); $form->submit(($request->request->get($form->getName()))); if ($form->isSubmitted() && $form->isValid()) { return $project; } return View::create($form, 400); }
ProjectType as follows
class ProjectType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('title'); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\Project' )); } }
However, when I try to publish JSON in the API, it responds that the title property cannot be empty, which is good because it has a validation rule set. However, it is installed. I suddenly realized that I had to send JSON with a prefix of the actual name of the object to make this work:
{"project":{"title": "bla"}}
Which seems a little strange to be fair, that should be enough to just post the properties.
So, based on this information, I just have 2 questions:
- Why do I need to "submit" this form using
($request->request->get($form->getName())) rather than $request being enough? - What do I need to change for FormType to check the object as is, instead of prefixing it with the name of the entity?
Edit 1: adding or removing data_class in the default settings does not change the behavior at all.
source share