0

Problem

I have a form in my Symfony 2(.1.8) application for creating an entry in a table called media. I build the form with the buildForm function in my media form class.
Amongst other fields the media table has these 3 fields: url, mediatype and file.

The mediatype is a relationship with a mediatype table and I render it as a drop down with the two values: VIDEO and IMAGE.

What I want to do now: When the user selects VIDEO in the dropdown the url form_row should be visible. When he selects IMAGE in the dropdown, the file form_row should be visible. When the user hasn't selected anything yet, neither url or file should be visible.

I tried this with this piece of code (but offcourse it's not working because the form.vars isn't dynamic I guess?):

 {% if form.vars.value.mediatype == "video" %}
     {{ form_row(form.url, { 'attr': {'class': 'form_url'} }) }}
 {% elseif form.vars.value.mediatype == "image" %}
     {{ form_row(form.file, { 'attr': {'class': 'form_file'} }) }}
 {% endif %}


Question

Is there a good way to do this using Twig and/or the Symfony framework? I was thinking of doing it with Javascript, but I first want to know for sure if it isn't possible with Twig/Symfony itself?

Thanks in advance!

4

1 回答 1

1

I was thinking of doing it with Javascript, but I first want to know for sure if it isn't possible with Twig/Symfony itself?

First idea is always the best one ;) Twig is a template language and is parsed server side. The idea of yours to just hide the other field with javascript is a good way to handle these things.

But there is an important thing to note! I guess only one of the fields url and file has to be filled out. With a plain Javascript solution always both of the fields will be send to your app. Therefore Symfony2 provides form events. There is a whole chapter in the cookbook about them.

于 2013-07-30T21:44:11.140 回答