3

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);
print_r($request->request->all());
$userForm->handleRequest($request);

print_r($userForm->getData());

The output I get is:

Array
(
    [firstName] => test
    [last_name] => test
    [email] => test@test.test
    [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?

overburn
  • 1,194
  • 9
  • 27
  • When are you doing `$userForm->getData()` it should be done after request has been handled and after checking `$userForm->isValid()`. – Samundra Sep 01 '16 at 13:12
  • Ok, it reports that it's not valid. But I have no idea how to get the errors. – overburn Sep 01 '16 at 13:22
  • see my example code below and try to match your code structure like the one I have shown. Once you get the idea, you can tweak however you like it. Let us know if you have any confusions. – Samundra Sep 01 '16 at 13:30
  • JSON: as this comes up when searching for JSON data input - for JSON, you have to manually decode the data `json_decode($request->getContent(), true)` and manually submit them if decoded properly `$form->submit($data);` – jave.web Oct 12 '22 at 10:45

1 Answers1

2

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)
    {
        $resolver->setDefaults(array(
            '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);

    $form->handleRequest($request);

    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(),
    ]);
}
Samundra
  • 1,869
  • 17
  • 28
  • thanks. it works. Btw, any idea why form get data returns multiple entries of type User? I'm dumbfounded – overburn Sep 01 '16 at 13:52
  • If it works for you then please mark my answer as accepted answer. I didn't get what do you mean by multiple entries of type User ? – Samundra Sep 01 '16 at 13:58
  • Hey @Samundra ! Could you help me with this problem too, please? I've stuck for weeks, but my form is a bit more complicated built that this one. How is it better to discuss with avoiding possible duplication of the question on the website? Thanks – Paul Burilichev Jun 16 '19 at 20:58
  • Hi @PaulBurilichev I would suggest to pen a new thread and link this question. That way you would have reference as well. – Samundra Jun 17 '19 at 14:53
  • @Samundra that's my question https://stackoverflow.com/questions/56639112/symfony-4-why-submitted-does-form-just-partially-populate-the-model – Paul Burilichev Jun 17 '19 at 21:30