Symfony3在FormType中设置Action



在symfony2中,我能够调用

// MyController.php
$formType = new MyFormType($this->container);
$form = $this->createForm($formType); 
// MyFormType.php
protected $container;
public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->setAction($this
            ->container
            ->get('router')
            ->generate('myAction')
        );
    // ...
    }
}

在symfony3中,我应该将string传递给createForm方法,所以我无法将控制器或路由器传递给MyFormType

我试图将FormType定义为一个服务,但它并没有改变行为。

如何在MyFormType中设置操作(而不是在MyController中)?

我目前发现的第一个也是唯一的选项是:

// MyController.php
$this->createForm(MyFormType::class, null, ['router' => $this->get('router')]);
// MyFormType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->setAction($options['router']->generate('myAction'));
    // ...
}
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'router' => null,
        // ...
    ]);
}

但这个解决方案对我来说似乎有点难看。

至少在Symfony2(在2.7中测试)中,您可以做到这一点:

//MyController.php
$this->createForm(MyFormType::class, null, array('action' => $this->generateUrl('my_acton_name')));

有了这个解决方案,无需修改FormType,选项"action"是Symfony Forms支持的真正选项,因此无需使用路由器添加它。你可以在这里找到文档。

您应该将表单定义为服务,例如:

// src/AppBundle/Form/Type/MyFormType.php
namespace AppBundleFormType;
use SymfonyBundleFrameworkBundleRoutingRouter;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
class MyFormType extends AbstractType
{
    private $router;
    public function __construct(Router $router)
    {
        $this->router = $router;
    }
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // You can now use myService.
        $builder
            ->setAction(
                $this->router->generate('myAction')
            )
            ->add('myInput')
            ->add('save', SubmitType::class)
        ;
    }
}
# app/config/services.yml
services:
    app.form.type.my_form_type:
        class: AppBundleFormTypeMyFormType
        arguments: [ "@router" ]
        tags:
            - { name: form.type }

在您的控制器中,您只需调用$this->createForm(MyFormType::class);

最新更新