根据列表中选择的项目显示输入字段

时间:2017-03-01 08:14:21

标签: symfony twig

我正在使用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 %}

是否可以用树枝做到这一点?

提前致谢!

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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上插入change事件来插入输入。

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

相关问题