{% extends DYNAMICFORMS.field_base_template %}
{% load dynamicforms %}
{% block field_input %}
<select id="{{ field.uuid }}" class="form-control {{ DYNAMICFORMS.select2_form_field_class }}
        {% if field.errors %}is-invalid{% endif %}" name="{{ field.name }}"
        {% if field.read_only %}disabled{% endif %}
  >
  {% if field.allow_null or field.allow_blank %}
    <option value="" {% if not field.value %}selected{% endif %}>{{ field.null_choice_text }}</option>
  {% endif %}
  {% iter_options_bound field as iter_options %}
  {% for select in iter_options %}
    {% if select.start_option_group %}
      <optgroup label="{{ select.label }}">
    {% elif select.end_option_group %}
      </optgroup>
    {% elif select.value is not None %}
      <option value="{{ select.value }}" {% if select.value|as_string == field.value|as_string %}selected{% endif %} {% if select.disabled %}disabled{% endif %}>{{ select.display_text }}</option>
    {% endif %}
  {% endfor %}
</select>

{% if DYNAMICFORMS.use_select2 %}
  <script type="text/javascript">
    // Check bootstrap version to set select2 theme
    var sel2Conf = {
      {% if field.url_reverse %}
      ajax: {
        url: '{% url field.url_reverse format='json' %}{{ field.additional_parameters_urlencoded }}',
        dataType: 'json',
        data: function(params) {
          return { '{{ field.query_field }}': params.term };
        },
        processResults: function (data) {
          var results = data.results ? data.results : data;  //data is paginated (or it isn't)
          return {
            results: $.map(results, function (item) {
              return {
                id: item.choice_id,
                text: item.choice_text,
              }
            })
          };
        }
      },
      // Disables ajax request on dropdown opening
      minimumInputLength: 1,
      {% endif %}
      {% if style.placeholder %}placeholder:"{{ style.placeholder }}",{% endif %}
      // Attaches select2 to its form parent and enables input field (in dialog)
      dropdownParent: $('#{{ style.serializer.uuid }}'),
      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);
        });
      }
    });

  </script>
{% endif %}

{% endblock %}
