I'm testing some "API developing" methods in Symfony 3.3
I just run through a tutorial, which told me that I could use Symfony Forms to:
Automatically validate JSON;
Automatically fill the new entity with the JSON data.
So I created a method "POST", which I use to create a resource, say USER.
I POST to that method with the following rawbody: {"name": "foo", "surname": "bar", "userType": 1}
The tutorial said I could do those two "automatic things" with form, by writing the following lines of code:
$data = json_decode($request->getContent(), true); $user = new User(); $form = $this->createForm(UserType::class, $user ); $form->submit($data); $em = $this->getDoctrine()->getManager(); $em->persist($user); $em->flush();
The form class "UserType" has the following lines of code:
namespace FooBundle\Form;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('surname', TextType::class)
->add('userType', ChoiceType::class, array(
'choices' => array(
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
5 => 'five',
6 => 'six',
)
)
)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
array(
"data_class" => "FooBundle\Entity\User"
)
);
}
}
When I post to that endpoint, however, I have the following error:
An exception occurred while executing 'INSERT INTO user(name, surname, user_type) VALUES (?, ?, ?)' with params ["foo", "bar", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_type' cannot be null
Why does the form does not automatically fill in the "user type" field?
Did I do something wrong in the "ChoiceType" field of the form?
Thanks :)