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 (form.duration.vars.id, form.duration.vars.name...) in order to keep the code dynamic.


<div class="form__item">
    {{ form_label(form.duration, "Durée { isTrainee ? 'du stage' : 'de la mission'} :") }}
    <select id="{{ form.duration.vars.id }}" name="{{ form.vars.name }}[{{ form.duration.vars.name }}]">
        <option v-for="duration in durationsForType" v-bind:value="duration.id">{ duration.label }</option>
    </select>
    {% 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 #}
</div>

 More on Stackoverflow   Read the doc


» Comments

Privacy-focused with Commento. (Comment system added on 2019-11-13: be the first! 🥇)