Include Javascript in Symfony2 Form Widgets

I created my own small form type Symfony2. For this to work correctly, I need to enable the js library. Although it was a simple task when using this new form type in one web application, it became much more difficult when I decided to move this form type to a dedicated package to make it reusable.

I currently know about two possible solutions.

1) Ask everyone who uses my package to add a line to their base.html.twig

2) Add a tag <script>to insert the library into the form widget

Both of them are not very smart, so my question is: how can I do this better? Especially if my type of form can be included several times on the same page. And even worse, if I need a type of form, for example. JQuery is present, but I do not know if jQuery is already loaded in the application.

+4
source share
1 answer

Since you have no control about where the users of your package really include JS (I know projects in which they are not included in the file ::base.html.twig, but in a file named layout.html.twigin the main application package), a good way is to provide a JavaScript file, which can then be enabled through Assetic as shown below:

{% javascripts debug=false output="js/bundles.js"
    '@YourVendorAndBundleName/Resources/public/js/formtype.js'
%}
    <script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}

, , , , {yourBundle}/Resources/public/js. symfony2 assets:install .

, JS JS- JS , , minifying ..

: /.


JS- JS-, jQuery, , Cookbook Symfony2: http://symfony.com/doc/master/cookbook/bundles/best_practices.html#vendors

, : JavaScript Symfony 2

0

All Articles