{% extends DYNAMICFORMS.field_base_template %}{% load i18n dynamicforms %}{% trans "No items to select." as no_items %}
{% block field_input %}
  <select multiple {{ field.choices|yesno:",disabled" }} id="{{ field.uuid }}"
          class="form-control {{ DYNAMICFORMS.select2_form_field_class }}
        {% if field.errors %}is-invalid{% endif %}" {% if field.read_only %}disabled{% endif %} style="width: 100%"
          name="{{ field.name }}" {% if field.placeholder %}data-placeholder="{{ field.placeholder }}" {% endif %}>
    {% for select in field.iter_options %}
      {% if select.start_option_group %}
        <optgroup label="{{ select.label }}">
          {% elif select.end_option_group %}
        </optgroup>
      {% else %}
        <option value="{{ select.value }}"
                {% if select.value|as_string in field.value|as_list_of_strings %}selected{% endif %}
                {% if select.disabled %}disabled{% endif %}>{{ select.display_text }}</option>
      {% endif %}
    {% empty %}
      <option>{{ no_items }}</option>
    {% endfor %}
  </select>

  {% if DYNAMICFORMS.use_select2 %}
    <script type="text/javascript">
      // Check bootstrap version to set select2 theme
      var sel2Conf = {
      // Attaches select2 to its form parent and enables input field (in dialog)
        dropdownParent: $('#{{ style.serializer.uuid }}'),
        {% if style.placeholder %}placeholder:"{{ style.placeholder }}",{% endif %}
        theme: '{{ DYNAMICFORMS.select2_theme }}'
      }

      var $sel2 = $("#{{ field.uuid }}");
      $sel2.data("sel2Conf", sel2Conf);
      $sel2.select2(sel2Conf);

      $sel2.on("change", function (evt) {
        if ($(evt.currentTarget).parents('tr.dynamicforms-filterrow').length) {
          {#  If select2 is for filter#}
          $(evt.currentTarget).parents('table').each(function (key, value) {
            var id = value.getAttribute('id');
            if (id.startsWith('list-'))
              setTimeout(function () {dynamicforms.filterData(id.replace('list-', ''));}, 1);
          });
        }
      }).on("select2:opening", function (evt) {
        dynamicforms.select2Opening(evt, $(this), null);
      }).on('select2:unselecting', function () {
        dynamicforms.select2Unselecting($(this));
      });
    </script>
  {% endif %}

{% endblock %}
