我有一个带有嵌入式表单的父表单。在嵌入式(子)表单中,我希望创建一个下拉字段,其中包含从数据库中查询的另一个实体的选项。作为查询的一部分,我需要引用父实体,但不确定如何从子表单类访问该父对象。
例如,父母是一个$subscriber
实体。在我的情况下,父表单实际上不显示与订阅者相关的任何属性,只是允许您添加或删除子实体表单。每个子表单都必须具有如上所述的字段,但是选择必须限于订户已经与之关联的值。
但这是我的问题所在。如何$subscriber
从子表单中使用的代码访问以下变量?:
$builder->add('otherEntity', EntityType::class, array(
'class' => "AppBundle:YetAnotherEntity",
'label' => "Other Entity",
'query_builder' => $this->manager->getRepository("AppBundle:OtherEntity")->getOtherEntityBySubscriber($subscriber)
));
依次在我的存储库中调用此函数:
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();
}
在jbafford的建议之后:我尝试了您的第一个选择,但是我的问题是我的父窗体调用了CollectionType :: class类型而不是我的自定义类型...,因为我计划制作一个可以添加多个子项的窗体。我无法将任何自定义选项传递给CollectionType。我是否需要扩展CollectionType以使自己的Type能够接受额外的选择?
我的父表单如下所示:$ builder-> add('child',CollectionType :: class,array(“ entry_type” => ChildType :: class,“ allow_add” => true,“ by_reference” => false,“ allow_delete “ => true)); 如果我在上面添加订户作为选项,我会得到一个错误,基本上说它不是一个有效的选项。我开玩笑地让我的ChildType扩展了CollectionType,但是我不认为这是我需要做的,并且收到一条错误消息:
表单的视图数据应该是AppBundle \ Entity \ Child类的实例,但是是一个实例Doctrine \ ORM \ PersistentCollection类。您可以通过设置“ data_class”来避免此错误
我想我需要另一个类来扩展CollectionType只是为了放入上述add方法中,但我仍然希望我的输入类型为ChildType :: class
因为这$subscriber
是父表单的主题,所以您可以执行此操作的一种方法是将$subscriber
as as form选项传递给子表单。
您可以在子级中定义如下:
class ChildForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$subscriber = $options['subscriber'];
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setRequired(['subscriber']);
}
}
然后从父级传递。
如果您的父表单是根表单,则可以$subscriber
退出$options['data']
:
$builder->add('otherEntity', ChildForm::class, [
'subscriber' => $options['data'],
],
如果不是,则可能需要使用事件侦听器来获取表单数据:
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$subscriber = $event->getData();
$form = $event->getForm();
$form->add('otherEntity', ChildForm::class, [
'subscriber' => $subscriber,
]);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句