【问题标题】:Symfony2: how to set form action in services.ymlSymfony2:如何在 services.yml 中设置表单操作
【发布时间】:2015-03-25 22:32:44
【问题描述】:

我使用一项服务在我的网站上获取基本搜索表单。我需要将操作表单设置为搜索结果页面。我可以将表单操作设置为特定的 url (/search),但不能在 yaml 中使用类似“generateUrl”的方法。

我希望能够在开发环境 /app_dev.php 以及 prod 环境中测试我的表单。有什么建议或想法吗?

services.yml

parameters:
  form.search.default.value: "search for things"

services:
  app_bundle.form.type.search:
    class: AppBundle\Form\SearchType
    arguments: [AppBundle\Entity\Search]
    tags:
      - { name: form.type, alias: tab_search }

  app_bundle.form.search:
    factory_method: create
    factory_service: form.factory
    class: Symfony\Component\Form\Form
    arguments:
      - tab_search
      - @app_bundle.form.entity.search
      - { action: /search } # I'd like something similar to $this->generateUrl("search")

  app_bundle.form.entity.search:
    class: AppBundle\Entity\Search
    arguments: [%form.search.default.value%]

DefaultController.php

        /**
         * @Route("/", name="homepage")
         * @Template()
         */
        public function indexAction(Request $request)
        {
            $form = $this->get('app_bundle.form.search');
            // [...]
            return array('search' => $form->createView());
        }

【问题讨论】:

  • 如何从Controller而不是Service声明中传递一个名为'action'的表单选项,然后在你的表单类中使用它。
  • 是的,但我想使用一个服务,这个表单将包含在包的几乎每个操作中
  • 好的,你可以将'router'服务和你的目标路由注入你的表单类,然后调用$router->generate(route)。

标签: php forms symfony service


【解决方案1】:

未经测试,但我以前用这段代码做过类似的事情:

protected $action;

public function setAction($action)
{
    $this->action = $action;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    // rest of form configuration
    $builder->setAction($this->action);
}

然后在你的 services.yml 中:

services:
    app_bundle.form.type.search:
    class: AppBundle\Form\SearchType
    arguments: [AppBundle\Entity\Search]
    calls:
        - [setAction, ["%app_bundle.form.type.search.action%"]]      
    tags:
        - { name: form.type, alias: tab_search }

然后在某处的参数中设置app_bundle.form.type.search.action值。

如果您希望允许覆盖该方法但设置默认值,请在setDefaultOptions 中设置action,然后从控制器或侦听器中覆盖。

【讨论】:

  • 好的,但我如何在开发中将app_bundle.form.type.search.action 设置为/app_dev.php/search,在产品中设置/search?我觉得使用config_dev.ymlconfig_prod.yml 有点牵强...
猜你喜欢
  • 2021-01-06
  • 2012-03-22
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
相关资源
最近更新 更多