我有一个实体形式与Symfony:
class MyType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
...
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'LogicielBundle'Entity'FichierGroup',
'intention' => $this->getName() . '_token'
));
}
但是在POstrongUBMIT事件中,我想返回null(没有实体)。我测试了这个,但不工作:
$builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event) {
.... my condition ...
$event->setData(null);
});
你能帮我吗?谢谢:)
你能把你的控制器代码贴出来吗?是将对象引用传递给createForm
,还是使用$form->getData()
?在你的情况下,你应该坚持第二种。
尝试使用SUBMIT事件代替POstrongUBMIT。正如Symfony文档所述,"它可以用来从数据的规范化表示中更改数据"。
据我所知,您无法更改提交表单。(我可能错了)
但是如果你想在提交后重置表单,你可以在你的控制器中做:
例如:public function fooAction()
{
...
$form = $this->getEntityForm($entity);
...
$form->handleRequest($request);
if ($form->isSubmitted()) {
// Do something
...
// Reset your form with null as entity
$form = $this->getEntityForm(null);
}
...
return $this->render(
'yourfootwig.html.twig',
[
'form' => $form->createView(),
...
]
);
}
protected function getEntityForm($entity = null)
{
return $this->createForm(
'Foo:MyType',
$entity,
[...]);
}
当然,你必须用你自己的代码来适应它。
实际上,如果你想改变数据传递形成实体,应该监听的事件是FormEvents::PRE_SUBMIT
。如官方文档所述。