Newer Version Available

This content describes an older version of this product. View Latest

Generating Drop-Down Lists Using Record Field Values

Use an Apex controller if you want to use your record data in list options.

Bind a record field to the ui:inputSelectOption component to display its values. Wire up the component to the Apex controller using the controller attribute, and invoke it during component initialization.

Let’s create a drop-down list that displays your contact names.

1<aura:component controller="ContactController">
2    <!-- Handle component initialization in a client-side controller -->
3    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
4
5    <!-- The list of contacts to display -->
6    <aura:attribute name="contacts" type="Contact[]"/>
7
8    <ui:inputSelect aura:id="opt" label="Contacts" change="{!c.onSelectChange}">
9        <aura:iteration items="{!v.contacts}" var="contact">
10            <ui:inputSelectOption text="{!contact.Name}" label="{!contact.Name}" />
11       </aura:iteration>
12    </ui:inputSelect>
13</aura:component>

This client-side controller initializes the option values by calling a helper and prints out the selected value when a select change event occurs.

1({
2    doInit : function(component, event, helper) {
3        // Retrieve contacts during component initialization
4        helper.getMyContacts(component);
5    },
6
7    onSelectChange : function(component, event, helper) {
8        // Print out the selected value
9        var selected = component.find("opt").get("v.value");
10        console.log(selected);
11    }
12})

The helper function calls the Apex controller getContacts()method to load the contact names.

1({
2    getMyContacts : function(cmp) {
3        // Load all contact data
4        var action = cmp.get("c.getContacts");
5        action.setCallback(this, function(response){
6            var state = response.getState();
7            if (state === "SUCCESS") {
8                cmp.set("v.contacts", response.getReturnValue());
9            }
10        });
11        $A.enqueueAction(action);
12    }
13})

Finally, the Apex controller queries and returns a list of contacts. Your controller name must correspond with your component’s controller attribute.

1public with sharing class ContactController {
2    @AuraEnabled
3    public static List<Contact> getContacts() {
4        List<Contact> contacts = [SELECT Id, Name FROM Contact];
5
6        //Add isAccessible() check
7        return contacts;
8    }
9}