我有一个带有嵌入式表单的父表单。在嵌入式(子)表单中,我希望创建一个下拉字段,其中包含从数据库中查询的另一个实体的选项。作为查询的一部分,我需要引用父实体,但不确定如何从子表单类访问该父对象。
例如,父级是一个 $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 来制作我自己的能够采用额外选项的类型?
我的父表单如下所示:
$builder->add('child', CollectionType::class, array(
"entry_type"=> ChildType::class,
“允许添加”=> 真,
"by_reference"=> 错误,
"allow_delete"=> true));
如果我将订阅者添加为上面的选项,我会收到一条错误消息,基本上是说它不是一个有效的选项。我试着让我的 ChildType 扩展 CollectionType,但我认为这不是我需要做的,并收到一条错误消息:
表单的 View 数据应该是类 AppBundle\Entity\Child 的一个实例,但却是类 Doctrine\ORM\PersistentCollection 的一个实例。您可以通过将“data_class”选项设置为 null 或添加一个 View 转换器来避免此错误,该 View 转换器将类 Doctrine\ORM\PersistentCollection 的实例转换为 AppBundle\Entity\Child 的实例。
我想我需要另一个类来扩展 CollectionType 只是为了放入上面的添加方法,但我仍然希望我的条目类型是 ChildType::class
最佳答案
由于 $subscriber
是您的父表单的主题,您可以这样做的一种方法是将 $subscriber
作为表单选项传递给子表单。
你可以在 child 中这样定义它:
class ChildForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$subscriber = $options['subscriber'];
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setRequired(['subscriber']);
}
}
然后从父级传给它。
如果您的父表单是根表单,您可以从 $options['data']
中获取 $subscriber
:
$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,
]);
});
关于forms - 我如何从子表单中获取父 Symfony3 表单的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34839145/