2017-03-01 122 views
0

我使用的Symfony,以使一個網球俱樂部的網站,我打我的頭向下的東西:顯示輸入字段

我想顯示基於輸入字段在下拉列表中選擇該選項。

這是場景: 我是網站的管理員,我想預約。如果預定是比賽(從ChoiceType列表中選擇),我想顯示輸入字段以輸入比賽名稱。

我想要做的東西,看起來像這樣在我的樹枝觀點:

<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 %} 

是否有可能這樣做只是樹枝?

在此先感謝!

+0

你需要JavaScript來實現這一點 – DarkBee

回答

1

您必須使用jQuery來解決這個問題:

$(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>

+0

你好,感謝您的回答! 下面是我結束了:https://jsfiddle.net/rrcpbxeq/ 雖然它不工作,但我很確定我在這裏做錯了什麼... –

+0

是的,在jsfiddle中,你是添加jQuery在JavaScript窗口中。再次檢查它現在工作正常。 https://jsfiddle.net/rrcpbxeq/2/ –

+0

謝謝你的作品! –

0

不,它不可能只與樹枝。

你可以做的是將腳本添加到您的模板:

<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> 

然後在腳本(使用jQuery),你只聽改變select事件插入輸入。

$('select.reservation-type').change(function(

    if($(this).val() == 'tournament') 
    { 
     $('<input type="text" />').appendTo($(this).parent('form-group')); 
    } 
)); 

如果你輸入需要枝杈變量或東西隱藏在樹枝模板,然後在腳本中,您剛剛從隱藏類型更改爲文本或任何你需要,你可以添加輸入:

$('select.reservation-type').change(function(

    if($(this).val() == 'tournament') 
    { 
     $('input[name="tournament-name"]').prop('type', 'text'); 
    } 
)); 

如果你不想使用JavaScript,你可以考慮使用表單事件偵聽器:http://symfony.com/doc/current/form/dynamic_form_modification.html

相關問題