如何使用Symfony2将表单值发送到控制器的路由

时间:2013-08-08 21:30:44

标签: forms symfony twig

是否可以将表单中的变量发送到控制器的路由?

示例:

FormType:

public function buildForm(FormBuilderInterface $builder, array $options)
    {    
        $builder->add('status', 'entity', array( 'class' => 'ADVD:Status', 
                        'label'   => 'form.country', 
                        'translation_domain' => 'ADVDBundle',
                        'empty_value'=> '- Select -', 
                        'property' => 'name'))

                ->add('country', 'entity', array(
                        'class' => 'ADVD:Country', 
                        'label'   => 'form.country', 
                        'translation_domain' => 'ADVDBundle',
                        'empty_value'=> '- Select -', 
                        'property' => 'description'));

    }

控制器:

 public function groupPrizesRequestedAction($status = 0, $country = 0) {
        switch ($status) {
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                break;
            case 5:
                break;
            case 6:
                break;
            case 7:
                break;
            case 8:
                break;
            case 9:
                break;
            case 10:
                break;
            case 11:
                break;
            default:
                $formulario = $this->createForm(new GroupingType());
                return $this->render('ADVDBundle:Prize:groupIndex.html.twig', array('form' => $formulario->createView())
                );
                break;
        }
    }

模板:

    {% block body %}
    <form action="{{ path('advd_status', {'status': X, 'country': X}) }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
            <input class="input_button" type="submit" value="Search" />
        </form>
{% endblock %}

GroupIndex模板是一个搜索模板,我们的想法是,从下拉列表中选择这些值后,按下搜索,然后搜索表单发送的国家和状态参数,事情是我不知道如何让控制器接收这些值,因为我不知道放在这里的内容path('advd_status', {'status': X, 'country': X}),我需要它们来控制器上的开关。

1 个答案:

答案 0 :(得分:1)

您可以在控制器中提交表单并获取表单数据(无需在URL中指定)

{% block body %}
    <form action="{{ path('advd_status') }}" method="post" {{ form_enctype(form) }}>
        {{ form_widget(form) }}
        <input class="input_button" type="submit" value="Search" />
    </form>
{% endblock %}

在控制器中

 public function groupPrizesRequestedAction($status = 0, $country = 0) {
    $formulario = $this->createForm(new GroupingType());
    if ($request->getMethod() == 'POST') {
        $data = $formulario->getData();
        $status = $data->getStatus();
        switch ($status) {
            ...
        }
    }
   else {
      return $this->render('ADVDBundle:Prize:groupIndex.html.twig', array('form' => $formulario->createView());

   }  
}
symfony一书中的

Forms chapter