将 EntityType 选择保存为字符串 - Symfony 4

Save EntityType choice as string - Symfony 4

我有 entity1 和 entity2。

在 entity1 的表单中,我显示了一个选项列表,其中的选项来自 entity2。 我想将所选选项作为字符串保存在 entity1 的 table 的列中,但我不想在 table 之间创建任何关系。

我应该怎么做?

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 菜鸟 :)

如果您使用 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();
    }
}