Reputation: 197
I'm using Symfony to make a website for a tennis club, and I'm beating my head down about something :
I want to display an input field based on the option selected in a dropdown list.
This is the scenario : I'm the admin of the website, and I want to make a reservation. If the reservation is a tournament (selected from a ChoiceType list), I want to display an input field to enter the tournament name.
I want to do something that would look like this in my twig view :
<div class="form-group">
<div class="col-xs-4">
{{ form_label(form.reservationType) }}
{{ form_widget(form.reservationType, {'attr': {'class': 'form-control' }}) }}
</div>
</div>
{% if reservationType == "tournament" %}
<div class="form-group">
<div class="col-xs-4>
{{ form_label(form.tournamentName) }}
{{ form_widget(form.tournamentName) }}
</div>
</div>
{% endif %}
Is it possible to do that just with twig ?
Thanks in advance!
Upvotes: 0
Views: 2306
Reputation: 26
You must use jQuery to solve this issue :
$(document).ready(function(){
$('.reservation').change(
var reservation = $(this).val();
if (reservation == 'xxxx'){
$('.tourName').show();
}else{
$('.tourName').hide();
}
);
});
<div class="form-group">
<div class="col-xs-4">
{{ form_label(form.reservationType) }}
{{ form_widget(form.reservationType, {'attr': {'class': 'form-control reservation' }}) }}
</div>
</div>
<div class="form-group">
<div class="col-xs-4>
{{ form_label(form.tournamentName) }}
{{ form_widget(form.tournamentName, {'attr': {'class': 'hidden tourName' }}) }}
</div>
</div>
Upvotes: 1
Reputation: 2007
No it is not possible only with twig.
What you can do is add a script to your template:
<div class="form-group">
<div class="col-xs-4">
{{ form_label(form.reservationType) }}
{{ form_widget(form.reservationType, {'attr': {'class': 'form-control reservation-type' }}) }}
</div>
</div>
<script type="text/javascript" src="{{ asset('bundles/yourBundle/theNameOfTheScriptYouPutInRessourcesPublic.js') }}"></script>
Then in the script (with jquery) you just listen to change event on the select to insert the input.
$('select.reservation-type').change(function(
if($(this).val() == 'tournament')
{
$('<input type="text" />').appendTo($(this).parent('form-group'));
}
));
If your inputs need twig variables or something you can add the inputs as hidden in the twig template and then in the script you just change the type from hidden to text or whatever you need:
$('select.reservation-type').change(function(
if($(this).val() == 'tournament')
{
$('input[name="tournament-name"]').prop('type', 'text');
}
));
If you don't want to use javascript you could consider using a form event listener: http://symfony.com/doc/current/form/dynamic_form_modification.html
Upvotes: 0