[SalesForce] Creating selectList/selectOptions from SOQL

I have a SOQL query and I want to add the results to a selectList and I'm not totally sure how. The documentation on selectList makes it look like I should loop through the results and add them as selectOptions to another list. But I'm having trouble with the syntax.
Here is the SOQL

public List<Contact> contacts { get; set; }

public PageReference searchContacts()
{
    contacts = [select Id
                      ,Name
                 from Contact 
                where FirstName LIKE :name+'%'];
    return null;
}

Best Answer

Yes, you'll want to make a list of SelectOption to bind to.

public SelectOption[] contactOptions { get; set; }
public Id selectedContactId { get; set; }

public void searchContacts() {
    contactOptions = new SelectOption[0];
    for(Contact record: [SELECT Name FROM Contact WHERE Name LIKE :name+'%']) {
        contactOptions.add(new SelectOption(record.Id, record.Name));
    }
}

<apex:selectList value="{!selectedContactId}">
    <apex:selectOptions value="{!contactOptions}" />
</apex:selectList>

Side note: don't return a PageReference if you don't intend to redirect. It makes the code self-documenting.

Related Topic