{% import 'macros/form.html' as form %}
{% macro help_text() %}
  {% snippet 'scheming/form_snippets/help_text.html', field=field %}
{% endmacro %}

{% set selected = h.relationship_get_current_relations_list(field, data) %}
{% if not selected %}
  {% set selected = request.args[field.field_name] %}
{% endif %}

{% set classes = ['control-full'] %}
{% if field.hidden_from_form %}
  {% do classes.append('hidden') %}
{% endif %}

{% call form.input_block(
        'field-' ~ field.field_name,
        label=h.scheming_language_text(field.label),
        classes=classes,
        error=errors[field.field_name],
        is_required=h.scheming_field_required(field),
        extra_html=help_text()
        ) %}

  {% set choices = h.relationship_get_choices_for_related_entity_field(field, data.get('id', None)) %}

  {% if not h.scheming_field_required(field) and not field.multiple %}
    {% do choices.insert(0, ('', 'No relation')) %}
  {% endif %}

  <select {% if field.multiple %}multiple{% endif %}
          size='{{ field.get('select_size', field.choices|length) }}'
          style='display: block'
          id='field-{{ field.field_name }}'
          name='{{ field.field_name }}'
          {{ form.attributes(dict(
        {'data-module': 'autocomplete'}, **field.get('form_select_attrs', {}))) }}>
    {% for val, label in choices %}
      <option id='field-{{ field.field_name }}-{{ val }}'
              value='{{ val }}'
              {{ 'selected ' if val in selected }} />
      {{ label }}
      </option>
    {% endfor %}
  </select>
{% endcall %}
