%{ pName = 'object.' + _name + '.' + play.db.Model.Manager.factoryFor(_field.property.relationType).keyName() }%

#{field 'object.' + _name}
    <label for="${field.id}">
        &{_name}
    </label>

    #{if _field.multiple}
        <input type="hidden" name="${pName}" value="" />
        <select id="${field.id}" name="${pName}" multiple="yes">
            %{ _field.choices.each() { }%
            %{
                selected = false;
                if(field.error?.message != 'validation.required') {
                    if(params[pName]) {
                        selected = params.getAll(${pName}).contains(it._key().toString())
                    } else {
                        for (it2 in _value) {
                            if(it2._key() == it._key()) {
                                selected = true;
                            }
                        }
                    }
                }
            }%
            <option value="${it._key()}" ${selected ? 'selected="true"'.raw() : ''}>${it}</option>
            %{ } }%
        </select>
    #{/if}
    #{else}
        <select id="${field.id}" name="${pName}">
            #{ifnot _field.required}
                <option value="">&{'crud.none'}</option>
            #{/ifnot}
            #{else}
                <option value="">&{'crud.selectValue'}</option>
            #{/else}
            %{ _field.choices.each() { }%
            %{
                selected = false
                if(field.error?.message != 'validation.required') {
                    if(params[pName]) {
                        selected = (it._key().toString() == params[pName])
                    } else {
                        selected = it._key() == _value?._key()
                    }
                }
            }%
            <option value="${it._key()}" ${selected ? 'selected="true"'.raw() : ''}>${it}</option>
            %{ } }%
        </select>
    #{/else}

    #{ifError field.name}
        <span class="error">${field.error.raw()}</span>
    #{/ifError}
#{/field}