Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have created my own little Symfony2 form type. For this to work properly, I need to include a js library. While that was a simple task when using this new form type in a single web application, it became way more difficult when I decided to move that form type to a dedicated bundle in order to make it reusable.

For now, I am aware of two possible solutions

1) Ask everyone who is using my bundle to add a line into their base.html.twig

2) Add a <script> tag for embedding the library to my form widget

Both of them are not very smart so my question is: how do I do this better? Especially, if my form type can be included several times on a single page. And even worse, if my form type is requiring e.g. JQuery to be present, but I do not know, if JQuery has already been loaded in the application.

share|improve this question

1 Answer 1

Since you don't have any controll about where the users of your bundle actually include the JS (I know projects where they aren't included in the ::base.html.twig file, but in a file called layout.html.twig in the main bundle of the application), a good way is to provide a JavaScript file which can then be included via Assetic like the following:

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

So you basically just store everything you need in that one file located in {yourBundle}/Resources/public/js. The symfony2 command assets:install will do the rest.

This way the user could store your JS together with other vendor JS in one file and do more stuff with it like minifying etc.

Important: Make sure to add this to your installation/usage guide.


If your JS code relies on third party JS libraries like jQuery, you should not add those, as the Symfony2 Cookbook says: http://symfony.com/doc/master/cookbook/bundles/best_practices.html#vendors

Instead you could require a specific asset with a specific name, like mentioned here: Managing common javascript dependencies in Symfony 2

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.