anton
anton

Reputation: 257

Symfony 2 Form theming and JS

I have AFormType class and corresponding twig template which is processed in some_controller_action.html.twig such way:

{% form_theme a_form with ['ABundle:Form:a-form.html.twig'] %}
{{ form(a_form) }}

I want a-form.html.twig contain javascript, which is related to the form only, and to nothing else. So I added there following:

{% block javascripts %}
<script type="text/javascript">
    $(document).ready(function () {
    ...
    }
{% endblock %}

some_controller_action.html.twig also has block javascripts, which contains document.load.

The problem: template engine ignores a_form.html.twig script and not includes to rendered page. controller's html.twig JS is processed correctly.

How may I solve the issue?

Upvotes: 0

Views: 830

Answers (1)

Twifty
Twifty

Reputation: 3378

The problem you are seeing is because The Symfony twig form extension handles the loading and rendering of blocks in theme files. You cannot add anything other than form widgets to your themes.

You can try importing your theme file and setting your current file as a theme. But you may still have to call block('javascripts')

{% form_theme a_form _self %}
{% use 'ABundle:Form:a-form.html.twig' %}

The only other way to add javascript for a form controller is to add it directly to the HTML in the widget. Gregwar CaptchaBundle does this. The problem with this approach is that the script will be added each time a form controller is rendered.

Upvotes: 1

Related Questions