我正在尝试将一个城市添加到从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()”。 可能会发生什么?
答案 0 :(得分:0)
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
$builder->add('state', EntityType::class, array(
'class' => 'AppBundle\Entity\State',
'mapped' => false,
'placeholder' => '', #
));
$formModifier = function (FormInterface $form, State $state= null) {
$cities = null === $state? array() : $state->getCities();
$form->add('city', EntityType::class, array(
'class' => 'AppBundle\Entity\City',
'placeholder' => '-Choose a state-',
'choices' => $cities,
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$data = $event->getData();
if($data === null || !method_exists($data, 'getState')) {
$formModifier($event->getForm(), null);
} else {
$formModifier($event->getForm(), $data->getProvincia());
}
}
);
$builder->get('state')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$state = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $provincia);
}
);
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
}
public function getBlockPrefix()
{
return 'app_user_registration';
}
public function getName()
{
return $this->getBlockPrefix();
}
}
真正让我发疯的是$ event-> getData(),根据官方doc示例带来的东西,在我的情况下是空的。我已经成功地解决了这个注册表格的问题,但现在我在配置文件编辑表格中遇到了同样的问题argggghhhhh