How to add options from a source model to an input field in a Form UI component

In the Magento backend, when we usually want to have a dropdown field with pre-defined data that we can select from, we use a SourceModel.

If we want to use a SourceModel in a UI component, lets say in a Form component, we would set the formElement of the field that we want to use to be formElement="select". Inside the field element we would specify our source model under


<field name="test" formElement="select">
    <formElements>
        <select>
            <settings>
                <options class="{{PATH_TO_SOURCEMODEL}}"/>
            </settings>
        </select>
    </formElements>
</field>

This is all fine when you want to have a select element in your configuration. But if you want to have a dynamic field, that only shows data from a SourceModel without being able to select it or edit it, this method wont work. You could of course set the element to be an input field and set it to be disabled, but then that does not look too good and someone who does not know the code might think that this field can be enabled and is editable.

A more clean solution to this would be to use a custom element template or elementTmpl. You can learn more on what element templates are and how they work here.

Once you have created you template under view/{{area}}/form/element/custom-element.html, add the following code to it:

<span class="admin__field-value"
      data-bind="
        text: getOption(value()).label,
        attr: {
            name: inputName,
            id: uid
    }"/>

Instead of outputting all the values in select field as usual, this will only return one value as a string, which cannot be changed. Now that we have the custom template, we should include it in the form ui component. This should look something like this:


<field name="test" formElement="select" sortOrder="30">
    <settings>
        <label translate="true">Test</label>
        <dataScope>status</dataScope>
        <dataType>text</dataType>
        <elementTmpl>Module_Name/form/element/custom-element</elementTmpl>
    </settings>
    <formElements>
        <select>
            <settings>
                <options class="Module\Name\Model\Config\Source\Test"/>
            </settings>
        </select>
    </formElements>
</field>

This is how it should look like in the form:

Single select field