0

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;
}
1
  • What are you trying to bind the resulting selection to?
    – Adrian Larson
    Jul 27, 2017 at 13:38

2 Answers 2

3

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.

1

To have your results displayable in a Select List on a visualforce page, you need a list of SelectOption.

This returns a list of SelectOptions created from the list of contacts you have created.

public List<SelectOption> getContacts()
{
    List<SelectOption> lstSelectList = new List<SelectOption>();
    for (Contact aContact : contacts) {
        lstSelectList.add(new SelectOption(aContact.Id, aContact.FirstName));
    }
    return lstSelectList;
}

The select list will use the contact's FirstName as the label, and the record Id for the value.

If you don't need to store the list of contacts for other uses, you can directly loop through the query results to create the list of select options, like so:

public List<SelectOption> getContacts()
{
    List<SelectOption> lstSelectList = new List<SelectOption>();
    for (Contact aContact : [SELECT Id, FirstName 
                             FROM Contact 
                             WHERE FirstName LIKE :name+'%']) {
        lstSelectList.add(new SelectOption(aContact.Id, aContact.FirstName));
    }
    return lstSelectList;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .