overburn overburn - 2 years ago 301
PHP Question

Symfony form handleRequest not populating

I have a symfony 3 form. And I'm trying to populate it with handleRequest like this:

$user = new User();
$userForm = $this->createForm(UserType::class, $user);


The output I get is:

[firstName] => test
[last_name] => test
[email] => [email protected]
[password] => erkeferke
[gender] => F
[supervisor] => 1
AppBundle\Entity\User Object
[id:AppBundle\Entity\User:private] =>
[firstName] =>
[lastName:AppBundle\Entity\User:private] =>
[email:AppBundle\Entity\User:private] =>
[password:AppBundle\Entity\User:private] =>
[photo:AppBundle\Entity\User:private] =>
[gender:AppBundle\Entity\User:private] =>
[supervisor:AppBundle\Entity\User:private] =>
[duties:AppBundle\Entity\User:private] =>
[lastLogin:AppBundle\Entity\User:private] =>
[createdAt:AppBundle\Entity\User:private] =>
[updatedAt:AppBundle\Entity\User:private] =>
[deletedAt:AppBundle\Entity\User:private] =>

Any idea why it's not populating?

Answer Source

To automatically populate entity from form request, you have to bind your entity to the FormType class. You might be missing this bind from your UserType class. In form UserType you should add a method configureOptions inside it you specify the entity class name in data_class key. To have more insights into it see Symfony Forms and scroll down to Setting the data_class topic. Also See example below where I have listed the usage.

<?php namespace AppBundle\Form;


class SiteType extends AbstractType
    public function buildForm(FormBuilderInterface $builder, array $options)
       // define form fields

    public function configureOptions(OptionsResolver $resolver)
            'data_class' => 'AppBundle\Entity\Site', // Entity to resolve to

Now, when you use the form, your entity is resolved from the request as shown below $site = $form->getData() will return Site entity. This is quite tricky to get right at the first time. You have to practice it a lot until you get hang of it. Let us know if you have confusions following it.

 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\Response
 * @Route("/sites/create", name="_create_site")
public function createSite(Request $request)
    $site = new Site;
    $form = $this->createForm(SiteType::class, $site);


    if ($form->isSubmitted() && $form->isValid()) {           
        $site = $form->getData();  // It will return Site Entity


        $this->addFlash('success', 'Record added successfully.');

    return $this->render('sites/create.html.twig', [
        'site_form' => $form->createView(),
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download