FormType中的Symfony3 setAction

时间:2016-04-06 11:36:40

标签: symfony

在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中)?

3 个答案:

答案 0 :(得分:2)

我现在找到的第一个也是唯一一个选项是:

// 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,
        // ...
    ]);
}

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

答案 1 :(得分:2)

至少在Symfony2中(在2.7中测试过),你可以这样做:

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

使用此解决方案无需修改FormType,选项'action'是Symfony Forms支持的实际选项,因此无需使用路由器添加它。 您可以找到文档here

答案 2 :(得分:1)

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

// src/AppBundle/Form/Type/MyFormType.php
namespace AppBundle\Form\Type;

use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

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: AppBundle\Form\Type\MyFormType
        arguments: [ "@router" ]
        tags:
            - { name: form.type }

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

即可
相关问题