如何在 Symfony 4 中从数组中的实体中创建新条目?

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

这是我的数组 $data:

array(7) {
  ["form[username]"]=>
  string(4) "test"
  ["form[email]"]=>
  string(11) "test@123.sw"
  ["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"
}

我将此数据存储到现有实体 User 中,如下所示:

$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();

效果很好!

但现在我其实不想更新一个激动人心的用户,我想创建一个新用户。这是我的方法:

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

我收到错误:

Call to a member function setUsername() on array

删除 $entity = $data; 并保留实体。

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

建议使用symfony 表单类型而不是直接使用原始数据。这将使您免于噩梦。控制器中的 newAction() 和 editAction() 将使用相同的表单类型。

下面我post给你举个例子:

表单类型

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'
        ));
    }
}

控制器

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
    }
}

这样,您就不需要明确设置任何内容。数据自动处理和提交。

更多相关信息:https://symfony.com/doc/current/best_practices/forms.html