forms - Symfony 2自定义表单字段类型:如何仅一次添加JavaScript和CSS?

标签 forms symfony twig

我想在自定义Symfony 2表单字段类型扩展中使用javascript。所以,我有这样的Twig扩展模板:

{% block some_widget %}
    <input ... />

    <script src="some.js"></script>
    <link href="some.css" />
{% endblock %}


但是我只想在HTML中一次拥有这些脚本和链接标记,最好在head标记中,而不修改基本模板。我尝试扩展Twig块,但无法访问表单模板中的操作模板块。也许是这样的:

{# widget tempate #}
{% block some_widget %}
    <input ... />

    {{ use_javascript('some.js') }}
    {{ use_css('some.css') }}
{% endblock %}

{# main action template #}
...
<head>
{{ dump_javascripts() }}
{{ dump_css() }}
</head>
...


如何使用Symfony 2 Forms + Twig执行此操作?

附言对不起,我的英语不好。

最佳答案

我必须编写一个需要JavaScript的自包含表单窗口小部件,通过侦听event_dispatcher并在kernel.response末尾附加JavaScript的Symfony\Component\HttpFoundation\Response,我能够实现您要尝试的操作。这是我的表单类型的代码段:

<?php

namespace AcmeBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;

class AcmeFileType extends AbstractType{

  private $twig;
  private $dispatcher;

  public function __construct(\Twig_Environment $twig, EventDispatcherInterface $dispatcher){
    $this->twig = $twig;
    $this->dispatcher = $dispatcher;
  }

  public function buildView(FormView $view, FormInterface $form, array $options){

    $javascriptContent = $this->twig->render('AcmeBundle:Form:AcmeFileType.js.twig', array());

    $this->dispatcher->addListener('kernel.response', function($event) use ($javascriptContent) {

      $response = $event->getResponse();
      $content = $response->getContent();
      // finding position of </body> tag to add content before the end of the tag
      $pos = strripos($content, '</body>');
      $content = substr($content, 0, $pos).$javascriptContent.substr($content, $pos);

      $response->setContent($content);
      $event->setResponse($response);
    });

  }

  ... 


当您在services.yml中定义表单类型时,它看起来像这样:

acme.form.acme_file_type:
    class: AcmeBundle\Form\AcmeFileType
    arguments:
        - @twig
        - @event_dispatcher
    tags:
        - { name: form.type, alias: acmefile }


因此,现在,每次使用acmefile构建表单时,javascript都将附加到<body>。尽管此解决方案不会阻止javascript多次显示,但是您应该可以轻松地对其进行改进以满足自己的需求。

如果愿意,还可以使用$response对象来修改标题。

关于forms - Symfony 2自定义表单字段类型:如何仅一次添加JavaScript和CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10009352/

相关文章:

symfony - 如何检查 Twig 模板中是否存在 block - Symfony2

php - 表单未在必填字段上显示错误

javascript - 创建递归表单元素

symfony实体setmaxresult/数组集合的限制

symfony - 在 Symfony2 中流式传输响应

mongodb - 更新 Mongodb 文档并添加字段

Symfony 2.7 使用 VichUploaderBundle 在 Twig 中渲染图像

html - 是否可以将 html 表单元素包装在多个表单标签中?

php - Symfony\组件\表单\异常\InvalidArgumentException : Could not load type "..."

symfony - symfony2自定义错误页面并扩展