我有一个带有嵌入表单的父表单。在嵌入(子)表单中,我希望创建一个下拉字段,其中包含从数据库查询的另一个实体的选项。作为查询的一部分,我需要引用父实体,但不确定如何从子表单类访问该父对象。
例如,父级是$subscriber实体。就我而言,父表单实际上不显示与订阅者相关的任何属性,仅允许您添加或删除子实体表单。每个子表单必须具有如上所述的字段,但选择需要限制为订阅者已经与之建立关系的值。
但这就是我的问题所在。如何$subscriber从子窗体中使用的代码访问下面的变量?:
$builder->add('otherEntity', EntityType::class, array(
'class' => "AppBundle:YetAnotherEntity",
'label' => "Other Entity",
'query_builder' => $this->manager->getRepository("AppBundle:OtherEntity")->getOtherEntityBySubscriber($subscriber)
));
Run Code Online (Sandbox Code Playgroud)
它又在我的存储库中调用此函数:
public function getOtherEntityBySubscriber($subscriber)
{
return $this->getEntityManager()
->createQuery(
'SELECT o FROM AppBundle:OtherEntity o JOIN n.subscriberOtherEntity so WHERE o.subscriber = :subscriber'
)
->setParameter("subscriber", $subscriber)
->getResult();
}
Run Code Online (Sandbox Code Playgroud)
在 jbafford 的建议之后:我尝试了您的第一个选项,但我的问题是我的父表单调用的类型CollectionType::class不是我的自定义类型...因为我计划制作一个可以添加多个子项目的表单。我无法将任何自定义选项传递给CollectionType. 我是否需要扩展CollectionType以创建能够接受额外选项的自己的类型?
我的父表单如下所示:
$builder->add('child', CollectionType::class, array(
"entry_type" => ChildType::class,
"allow_add" => true,
"by_reference" => false,
"allow_delete" => true)
);
Run Code Online (Sandbox Code Playgroud)
如果我将订阅者添加为上面的选项,我会收到一个错误,基本上说它不是有效的选项。我尝试让我的 ChildType 扩展 CollectionType 但我不认为这是我需要做的,并收到一条错误消息:
表单的视图数据应该是类 AppBundle\Entity\Child …