Symfony:我可以从Type/Form返回null吗?

Gay*_*d.P 10 php symfony-forms symfony

我有一个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'
        ));
    }
Run Code Online (Sandbox Code Playgroud)

但是在POST_SUBMIT事件中,我想返回null(没有实体).我测试了这个,但没有工作:

    $builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event) {
        .... my condition ...
        $event->setData(null);
    });
Run Code Online (Sandbox Code Playgroud)

你能帮助我吗 ?谢谢 :)

doy*_*y44 0

据我所知,您无法更改提交表单。(我可能是错的)

但是如果您想在提交后重置表单,您可以在控制器中执行此操作:

例如:

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,
        [...]);
}
Run Code Online (Sandbox Code Playgroud)

当然,您必须使用自己的代码对其进行调整。