Render a form field manually with Vue.js instead of Symfony

Published on 2019-06-12 • Modified on 2019-06-12

When buidling a form, sometimes you want a field to be rendered with the help of Vue.js instead of Symfony. Using Vue.js allows us for example to have dynamic options for select boxes. In this case, the label will be modified when you change the value of another field (which is stored in the isTrainee computed variable). Then the options of the duration select box will be also loaded dynamically with the help of the durationsForType computed variable. Note that in fact we only avoid to use the form_widget Twig helper. We still use the other helpers: form_label(), form_errors() and form variables (, to keep the code dynamic.

<div class="form__item">
    {{ form_label(form.duration, "Durée { isTrainee ? 'du stage' : 'de la mission'} :") }}
    <select id="{{ }}" name="{{ }}[{{ }}]">
        <option v-for="duration in durationsForType" v-bind:value="">{ duration.label }</option>
    {% if form_errors(form.duration) is not empty %}<div class="modal-error"><div class="arrow"></div>{{ form_errors(form.duration) }}</div>{% endif %}
    {% do form.duration.setRendered() %}
    {# Mark form field as manually rendered so it's not displayed Twice by the form_rest() Twig helper #}

 More on Stackoverflow   Read the doc  Random snippet