如何使用Symfony2中的FormBuilder将表单的URL设置为POST?

时间:2022-04-14 06:44:38

I'm dynamically loading different form classes in my Controller and displaying them in my template. This works fine, except that the Symfony2 docs show adding the route for the form to POST to in the template by hand.

我在我的Controller中动态加载不同的表单类并在我的模板中显示它们。这样可以正常工作,除了Symfony2文档显示手动将表单路由添加到模板中。

<form action="{{ path('task_new') }}" method="post" {{ form_enctype(form) }}>
    {{ form_widget(form) }}

    <input type="submit" />
</form>

I need to set that form action in the FormBuilder class-- the POST routes (e.g. 'task_new') are different depending on the form class I'm using. Is there a way to set the form action url in the FormBuilder class? How can we get {{ form_widget(form) }} to render the complete form, and not just the rows? Thanks!

我需要在FormBuilder类中设置表单操作 - POST路由(例如'task_new')根据我正在使用的表单类而不同。有没有办法在FormBuilder类中设置表单操作URL?我们怎样才能获得{{form_widget(form)}}来呈现完整的表单,而不仅仅是行?谢谢!

5 个解决方案

#1


47  

It is possible out of the box -- http://symfony.com/doc/current/book/forms.html#changing-the-action-and-method-of-a-form

它可以开箱即用 - http://symfony.com/doc/current/book/forms.html#changing-the-action-and-method-of-a-form

$form = $this->createFormBuilder($task)
->setAction($this->generateUrl('target_route'))
->setMethod('GET')
->add('task', 'text')
->add('dueDate', 'date')
->add('save', 'submit')
->getForm();

#2


32  

I had the same problem. I was using a simple FormType class and wanted to set the action url in buildForm function. I tried different things, but couldn't do it that way.

我有同样的问题。我使用的是一个简单的FormType类,并希望在buildForm函数中设置动作url。我尝试了不同的东西,但不能这样做。

Eventually I used a Form option called 'action'. I don't think it's documented in the Symfony Reference, I have found it by accident while reading some error report :). You can set the option when creating the form within your controller like this:

最后我使用了一个名为“action”的Form选项。我不认为它是在Symfony Reference中记录的,我在阅读一些错误报告时偶然发现它:)。您可以在控制器中创建表单时设置选项,如下所示:

$form = $this->createForm(new FormType(), $obj, array( 'action' => 'whatever you want'));

It's not as pretty as having it encapsulated in the form class, but it works.. I hope this helps.

它不像封装在表单类中那么漂亮,但它有效..我希望这会有所帮助。

#3


9  

It's bad practice to change submit route in form type. It not form type responsibility. If you added form from not handle form route, you can just change action url in template:

在表单类型中更改提交路由是不好的做法。它不构成类型责任。如果您从不处理表单路由添加表单,则只需在模板中更改操作URL:

  {{ form_start(yourForm,{action:path('yourSubmitRoute')}) }}

#4


6  

I solved this problem by injecting the router into my form type. In my application I have created a zip code search form called ZipCodeSearchType:

我通过将路由器注入我的表单类型来解决了这个问题。在我的应用程序中,我创建了一个名为ZipCodeSearchType的邮政编码搜索表单:

Form Class

use Symfony\Component\Form\AbstractType;
/*
 * I'm using version 2.6. At this time 2.7 has introduced a 
 * new method for the Option Resolver. Refer to the documentation 
 * if you are using a newer version of symfony.
 */
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Routing\Router;

/**
 * Class ZipCodeSearchType is the form type used to search for plans. This form type
 * is injected with the container service
 *
 * @package TA\PublicBundle\Form
 */
class ZipCodeSearchType extends AbstractType
{   
    /**
     * @var Router
     */
    private $router;

    public function __construct(Router $router)
    {
        //Above I have a variable just waiting to be populated with the router service...
        $this->router = $router;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('zipCode', 'text', [
                'required' => true,
            ])
            /*
             * Here is where leverage the router's url generator
             */
            //This form should always submit to the ****** page via GET
            ->setAction($this->router->generate('route_name'))
            ->setMethod("GET")
        ;
    }

    ...
}

The next step is to configure your form as a service, and let symfony know that you need the router service injected into your class:

下一步是将表单配置为服务,让symfony知道您需要将注册表服务注入到您的类中:

Define Form as Service

/*
 * My service is defined in app/config/services.yml and you can also add this configuration
 * to your /src/BundleDir/config/services.yml
 */
services:
    ############
    #Form Types
    ############
    vendor_namespace.zip_search_form:
        class: VENDOR\BundleNameBundle\Form\ZipCodeSearchType
        arguments: [@router]
        tags:
            - { name: form.type, alias: zip_code_search }

Use It In Your Controller

/**
 * @param Request $request
 * @return Form
 */
private function searchByZipAction(Request $request)
{
    ...

    $zipForm = $this
        ->createForm('zip_code_search', $dataModel)
    ;
    ...
}

#5


-3  

I don't think it's possible out-of-box today (Mar 18 '12). You could, however, do something like this:

我认为今天(12月12日)可能无法开箱即用。但是,您可以这样做:

in your controller:

在你的控制器中:

....
....

$post_route = null;
if ( $something ){
    $post_route = "some_post_route";
}else if ( $something_else ){
    $post_route = "some_other_post_route"
}else{
    $post_route = "my_default_route";
}

....
....

return array(
    'post_route' => $post_route
);

... and in you template:

......并在你的模板中:

<form action="{ path(post_route) }" method="post" {{ form_enctype(form) }}>

Similar approach would be to generate URL (not just route name) within your controller and pass it to template, in which case you don't need path function there.

类似的方法是在控制器中生成URL(不仅仅是路由名称)并将其传递给模板,在这种情况下,您不需要路径功能。

#1


47  

It is possible out of the box -- http://symfony.com/doc/current/book/forms.html#changing-the-action-and-method-of-a-form

它可以开箱即用 - http://symfony.com/doc/current/book/forms.html#changing-the-action-and-method-of-a-form

$form = $this->createFormBuilder($task)
->setAction($this->generateUrl('target_route'))
->setMethod('GET')
->add('task', 'text')
->add('dueDate', 'date')
->add('save', 'submit')
->getForm();

#2


32  

I had the same problem. I was using a simple FormType class and wanted to set the action url in buildForm function. I tried different things, but couldn't do it that way.

我有同样的问题。我使用的是一个简单的FormType类,并希望在buildForm函数中设置动作url。我尝试了不同的东西,但不能这样做。

Eventually I used a Form option called 'action'. I don't think it's documented in the Symfony Reference, I have found it by accident while reading some error report :). You can set the option when creating the form within your controller like this:

最后我使用了一个名为“action”的Form选项。我不认为它是在Symfony Reference中记录的,我在阅读一些错误报告时偶然发现它:)。您可以在控制器中创建表单时设置选项,如下所示:

$form = $this->createForm(new FormType(), $obj, array( 'action' => 'whatever you want'));

It's not as pretty as having it encapsulated in the form class, but it works.. I hope this helps.

它不像封装在表单类中那么漂亮,但它有效..我希望这会有所帮助。

#3


9  

It's bad practice to change submit route in form type. It not form type responsibility. If you added form from not handle form route, you can just change action url in template:

在表单类型中更改提交路由是不好的做法。它不构成类型责任。如果您从不处理表单路由添加表单,则只需在模板中更改操作URL:

  {{ form_start(yourForm,{action:path('yourSubmitRoute')}) }}

#4


6  

I solved this problem by injecting the router into my form type. In my application I have created a zip code search form called ZipCodeSearchType:

我通过将路由器注入我的表单类型来解决了这个问题。在我的应用程序中,我创建了一个名为ZipCodeSearchType的邮政编码搜索表单:

Form Class

use Symfony\Component\Form\AbstractType;
/*
 * I'm using version 2.6. At this time 2.7 has introduced a 
 * new method for the Option Resolver. Refer to the documentation 
 * if you are using a newer version of symfony.
 */
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Routing\Router;

/**
 * Class ZipCodeSearchType is the form type used to search for plans. This form type
 * is injected with the container service
 *
 * @package TA\PublicBundle\Form
 */
class ZipCodeSearchType extends AbstractType
{   
    /**
     * @var Router
     */
    private $router;

    public function __construct(Router $router)
    {
        //Above I have a variable just waiting to be populated with the router service...
        $this->router = $router;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('zipCode', 'text', [
                'required' => true,
            ])
            /*
             * Here is where leverage the router's url generator
             */
            //This form should always submit to the ****** page via GET
            ->setAction($this->router->generate('route_name'))
            ->setMethod("GET")
        ;
    }

    ...
}

The next step is to configure your form as a service, and let symfony know that you need the router service injected into your class:

下一步是将表单配置为服务,让symfony知道您需要将注册表服务注入到您的类中:

Define Form as Service

/*
 * My service is defined in app/config/services.yml and you can also add this configuration
 * to your /src/BundleDir/config/services.yml
 */
services:
    ############
    #Form Types
    ############
    vendor_namespace.zip_search_form:
        class: VENDOR\BundleNameBundle\Form\ZipCodeSearchType
        arguments: [@router]
        tags:
            - { name: form.type, alias: zip_code_search }

Use It In Your Controller

/**
 * @param Request $request
 * @return Form
 */
private function searchByZipAction(Request $request)
{
    ...

    $zipForm = $this
        ->createForm('zip_code_search', $dataModel)
    ;
    ...
}

#5


-3  

I don't think it's possible out-of-box today (Mar 18 '12). You could, however, do something like this:

我认为今天(12月12日)可能无法开箱即用。但是,您可以这样做:

in your controller:

在你的控制器中:

....
....

$post_route = null;
if ( $something ){
    $post_route = "some_post_route";
}else if ( $something_else ){
    $post_route = "some_other_post_route"
}else{
    $post_route = "my_default_route";
}

....
....

return array(
    'post_route' => $post_route
);

... and in you template:

......并在你的模板中:

<form action="{ path(post_route) }" method="post" {{ form_enctype(form) }}>

Similar approach would be to generate URL (not just route name) within your controller and pass it to template, in which case you don't need path function there.

类似的方法是在控制器中生成URL(不仅仅是路由名称)并将其传递给模板,在这种情况下,您不需要路径功能。