如何从 PHP 预填充 EntityType 类型的字段

How to prefill field of type EntityType from PHP

在我的表单中,我有一个类型为 EntityClass:

的字段
$builder
    ->add(
        'user',
        EntityType::class,
        [
            'required' => false,
            'label' => 'User',
            'placeholder' => 'Please choose',
            'choice_label' => 'email',
            'choice_value' => 'id',
            'class' => 'AppBundle:User',
        ]
    )
;

这个字段工作正常 - 直到我尝试从我的 PHP 代码中预填充它。然后它保持为空,只显示 "Please choose".

预填充看起来像这样:

$user = $this->userRepository->find(...);
$form->get('user')->setData($user);

但是如果我调用 ->setData($user->getId()) 甚至 ->setData($user->getEmail()).

它也不起作用

那么如何预填充类型为 EntityType 的字段?

您不应该预填 Form,如果需要,您应该预填 Model

$user = $this->userRepository->find(...);

$entity = new YourEntity();
$entity->setUser($user);

$form = $this->createForm(YourEntity::class, $entity);

这与 EntityType 无关。它与 Symfony 中的任何类型有关——没有办法为它们绑定默认值。数据绑定在模型上。

来自评论的 UPD:事实并非如此,Form 可以在没有 Model 的情况下使用。它可以在没有 Doctrine 实体或任何其他 ORM(或非 ORM)实体的情况下使用。但他们仍然使用数据进行操作,i.o。与模型。

\Symfony\Component\Form\FormFactoryInterface 有定义

public function create($type = 'form', $data = null, array $options = array());

所以当您使用表单组件时,某种 $data 总是存在。