代码之家  ›  专栏  ›  技术社区  ›  Joao Victor Souza

将EntityType选项另存为字符串-symfony 4

  •  0
  • Joao Victor Souza  · 技术社区  · 7 年前

    我有实体1和实体2。

    在Entity1的表单中,我显示了一个选项列表,其中选项是从Entity2混合而来的。 我希望将所选选项保存为Entity1表中列内的字符串,但不希望在表之间创建任何关系。

    我该怎么做?

    class Entity1 {
    /**
     * @ORM\Column(type="string")
     */
    private $historico;
    }
    
    class Entity2 {
    /**
     * @ORM\Column(type="string")
     */
    private $description;
    }
    

    entity1formtype.php文件

    $builder->add('historico', EntityType::class, [
                    'class' => Entity2::class,
                    'choice_label' => 'description',
                    'choice_value' => 'description',
                    'placeholder' => ''
                ]);
    

    选项显示良好,但提交时会出现以下错误:

    Expected argument of type "string", "App\Entity\Entity2" given.
    

    如果使用'mapped'=>false,则输入提交为空。

    如何将实体对象转换为字符串? 帮助一个symfony noob:)

    1 回复  |  直到 7 年前
        1
  •  0
  •   Daniele Fois    7 年前

    如果使用mapped=>false,则必须在提交表单后在控制器中手动提取数据。

    所以你会得到这样的东西:

    public function postYourFormAction(Request $request)
    {
        $entity1 = new Entity1();
        $form = $this->createForm(Entity1Type::class $entity1);
        $form->handleRequest($request);
        if($form->isSubmitted() && $form->isValid()) {
            $entity1 = $form->getData;
            $historico = $form->get('historico')->getData();
            $entity1->setHistorico($historico);
            $em->persist($entity1);
            $em->flush();
        }
    }