Search code examples
mysqlsymfonydoctrineentityentitymanager

How can I create new entry in entity from array in Symfony 4?


This is my array $data:

array(7) {
  ["form[username]"]=>
  string(4) "test"
  ["form[email]"]=>
  string(11) "[email protected]"
  ["form[is_active]"]=>
  string(1) "1"
  ["form[plainPassword][first]"]=>
  string(0) ""
  ["form[plainPassword][second]"]=>
  string(0) ""
  ["form[id]"]=>
  string(1) "9"
  ["form[_token]"]=>
  string(43) "A"
}

I store this data into my existing entity User like this:

$entity = $this->getDoctrine()->getRepository(User::class)->find($data['form[id]']);
$em = $this->getDoctrine()->getManager();
$entity->setUsername($data['form[username]']);
$entity->setEmail($data['form[email]']);
$em->flush();

This is working well!

But now I actually do not want to update an exicting user, I want to create a new user. This is my approach:

      $entity = new User();
      $entity = $data;
      $em = $this->getDoctrine()->getManager();
      $entity->setUsername($data['form[username]']);
      $entity->setEmail($data['form[email]']);
      $em->flush();

I get the error:

Call to a member function setUsername() on array


Solution

  • It is recommended to use symfony form types and not the raw data directly. This will save you from nightmares. The same form type will be used for newAction() and editAction() in your controllers.

    I post an example for you below:

    Form Type

    class UserType extends AbstractType
    {
        /**
         * {@inheritdoc}
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('username')
                ->add('email');
        }
    
        /**
         * {@inheritdoc}
         */
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'your User entity reference'
            ));
        }
    }
    

    Controller

    public function newAction(Request $request)
    {
        try
        {
            $user = new User();
            $form = $this->createForm('path to your UserType', $user);
            $form->handleRequest($request);
            $form->submit($request->request->all());
            if ($form->isSubmitted())
            {
                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->flush();
    
            //your code
        }
        catch (\Exception $exception)
        {
            // return your exception
        }
    }
    

    This way, you dont need to set anything explicitly. Data is automatically handled and submitted.

    More on this here : https://symfony.com/doc/current/best_practices/forms.html