将全选选项添加到symfony中的复选框列表中

时间:2015-02-19 16:39:51

标签: php symfony checkbox html-form

我对网页开发和HTML表单相对较新。在我的webapp中,我有一个列表(gpstracks),每个列表条目都有一个复选框,因此用户可以一次编辑,删除,下载,等等......所有选定的曲目。为了提高可用性,我想添加一个“全选”按钮或复选框,自动检查表单中的所有其他复选框(最好不重新加载整个表单)。

有没有可能做到这一点?我一直在尝试使用

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($tracks){

        $form = $event->getForm();

        foreach($tracks as $track)
        {
            $form->get($track->getId())->setData(array('checked'=>true));
        }
    }

结合“提交”类型的第二个按钮,显示“全选”。显然,这会重新加载整个表单。但重新加载后,所有复选框都保持未选中状态,因此setData方法似乎根本没有效果。

是否有任何选项以编程方式检查表单中的复选框复选框,最好是不重新加载整个表单?

2 个答案:

答案 0 :(得分:1)

  1. 为复选框设置html类(在表单构建器设置选项attr [' class']中)
  2. 添加其他课程的按钮
  3. 添加事件以捕获点击按钮2,并检查检查点 http://www.sanwebe.com/2014/01/how-to-select-all-deselect-checkboxes-jquery

答案 1 :(得分:1)

使用jquery:

// cerad.js
Cerad = {};
Cerad.checkboxAll = function(e)
{   
    var nameRoot = $(this).attr('name'); // "refSchedSearchData[ages][]";

    nameRoot = nameRoot.substring(0,nameRoot.lastIndexOf('['));

    var group = 'input[type=checkbox][name^="' + nameRoot + '"]';

    var checked = $(this).prop('checked') ? true : false;

    $(group).prop('checked', checked);
};

{# searchform.html.twig #}
{# form.dates is an array of form check boxes #}
{% if form.dates is defined %}
  {% set items = form.dates %}
  <td>{% include '@CeradGame/Project/Schedule/Twig/ScheduleSearchCheckboxes.html.twig' %}</td>
{% endif %}

{# ScheduleSearchCheckboxes.html.twig #}
{# render one set of check boxes as a table #}
{# Setting a class on the first item #}
<table border="1">
  <tr><th colspan="30">{{ items.vars.label }}</th></tr>
  <tr>
    {% set itemFirst = true %}
    {% for item in items %}
      <td align="center">{{ form_label(item) }}<br />
      {% if itemFirst %}
        {{ form_widget(item, { 'attr': {'class': 'cerad-checkbox-all' }}) }}
        {% set itemFirst = false %}
      {% else %}
        {{ form_widget(item) }}
      {% endif %}
      </td>
    {% endfor %}
  <tr>
</table>

// Grab all the cerad-checkbox-all elements and pass to Cerad.checkboxAll
{% block javascripts %}
  <script type="text/javascript">
    $(document).ready(function()
    {
      // checkbox all functionality
      $('.cerad-checkbox-all').change(Cerad.checkboxAll);
    });
  </script>
{% endblock %}