{% from "macros/form/input_block.html" import input_block %}
{% from "macros/form/attributes.html" import attributes %}

{#
Creates all the markup required for an select element. Handles matching labels to
inputs and error messages.

A field should be a dict with a "value" key and an optional "text" key which
will be displayed to the user. We use a dict to easily allow extension in
future should extra options be required.

name        - The name of the form parameter.
id          - The id to use on the input and label. Convention is to prefix with 'field-'.
label       - The human readable label.
options     - A list/tuple of fields to be used as <options>.
    selected    - The value of the selected <option>.
    error       - A list of error strings for the field or just true to highlight the field.
    classes     - An array of classes to apply to the form-group.
    is_required - Boolean of whether this input is required for the form to validate

    Examples:

    {% import 'macros/form.html' as form %}
    {{ form.select('year', label=_('Year'), options=[{'value':2010, 'text': 2010},{'value': 2011, 'text': 2011}], selected=2011, error=errors.year) }}

    Or only with values if they are the same as text:
    {{ form.select('year', label=_('Year'), options=[{'value':2010},{'value': 2011}], selected=2011, error=errors.year) }}

    Complete example:
    {{ form.select('the_data_type', id='the_data_type', label=_('Data Type'), options=[
        {'value': '0', 'text': _('[Choose Data Type]')}
        , {'value': '1', 'text': _('Private data')}
        , {'value': '2', 'text': _('Not private data')}
    ], selected=data.the_data_type if data.the_data_type else '0', is_required=true) }}

#}

{% macro select(name, id='', label='', options='', selected='', error='', classes=[], attrs={'class': 'form-control form-select'}, is_required=false) %}
{% set classes = (classes|list) %}
{% do classes.append('control-select') %}

{%- set extra_html = caller() if caller -%}
{% call input_block(id or name, label or name, error, classes, extra_html=extra_html, is_required=is_required) %}
<select id="{{ id or name }}" name="{{ name }}" {{ attributes(attrs) }}>
    {% for option in options %}
<option value="{{ option.value }}"{% if option.value == selected %} selected{% endif %}>{{ option.text or option.value }}</option>
{% endfor %}
</select>
{% endcall %}
{% endmacro %}
