【发布时间】:2016-10-03 16:23:56
【问题描述】:
我正在尝试将城市添加到从 FOSUserBundle 扩展 BaseUser 的 User 类中,并且我正在遵循此页面中的指南: http://symfony.com/doc/current/form/dynamic_form_modification.html#form-events-submitted-data
我创建了一个 RegistrationType 类,代码如下:
public function buildForm(FormBuilderInterface $builder, array $options)
{
/* i setted a name field just to check that this form builder is used then i try to create a user */
$builder->add('name');
$builder->add('provincia', EntityType::class, array(
'class' => 'AppBundle\Entity\State',
'placeholder' => '', #
));
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();
$state = $data->getState();
$cities = null === $state ? array() : $state->getCities();
$form->add('city', EntityType::class, array(
'class' => 'AppBundle\Entity\City',
'placeholder' => '',
'choices' => $cities,
));
}
);
//...
}
问题是,当它在 $data->getState() 中向我抛出错误时,它告诉我“错误:在 null 上调用成员函数 getState()”。 会发生什么?
【问题讨论】:
-
您能告诉我们您是如何在控制器中声明表单的吗?
-
嗨 Raphael,我想我不是在声明一个表单,因为我从 fosuserbundle 文档 (symfony.com/doc/current/bundles/FOSUserBundle/…) 中了解到,我所要做的就是创建一个继承自 bundle 的类RegistrationFormType,声明:public function getParent() { return 'FOS\UserBundle\Form\Type\RegistrationFormType';我的整个班级将是:(请看下面的回复,由于此回复中的字符限制,我无法将所有代码放在这里)