非映射表单、Ent​​ityType 和数据属性

Non-mapped form, EntityType and data attribute

我使用 EntityType 创建表单,但未映射到实体。表单很长,用户多次重复使用相同的选项,然后当他验证表单时,如果有效,我将 $form->getData() 存储在会话中。

当我生成表单时,我注入了 $data。它适用于所有选项,除了 EntityType,我不明白为什么...

$data 中,我有一个 ArrayCollection 对象 select 在 EntityType 中编辑,但表格没有 select它。我使用了 mapped = false,因为如果我删除它,我会出现错误:

Entities passed to the choice field must be managed. Maybe persist them in the entity manager?

有人知道怎么做吗?

Settings mapped = false 应该不是这种情况下的解决方案,因为你需要将存储的数据写入这个字段,对吧?所以 mapped = false 避免它(查看更多关于 mapped 选项 here

这里的问题是 EntityType 需要从每个 item 中获取 id 值并且它要求这些 items 实际由EntityManager管理:

Entities passed to the choice field must be managed. Maybe persist them in the entity manager?

当实体的持久性由 EntityManager 管理时,实体处于 MANAGED 状态。换句话说,如果实体是从数据库中获取的或通过 EntityManager#persist.

注册为新实体,则该实体是受管理的

在你的例子中,这些实体来自会话,所以你有两个选择:

  • 从数据库中重新查询存储的实体:

    if (isset($data['foo']) && $data['foo'] instanceof Collection) {
        $data['foo'] = $this->getDoctrine()->getRepository(Foo::class)->findBy([
            'id' => $data['foo']->toArray(),
        ]);
    }
    
  • 或者,设置自定义 choice_value 选项以避免默认选项:

    $form->add('foo', EntityType::class, [
        'class' => Foo::class,
        'choice_value' => 'id', // <--- default IdReader::getIdValue()
    ]);