Dynamically getting picklist values using SOQL

Sample Code:

Visualforce page:

<apex:page controller="sample">
   
    <apex:form >
   
    <apex:pageBlock >
        <apex:commandButton value="Get" action="{!get}"/>
    </apex:pageBlock>
   
    <apex:pageBlock id="a" >
        <apex:selectList value="{!answer}" size="1">
            <apex:selectOptions value="{!answers}"/>
        </apex:selectList>       
    </apex:pageBlock>   

    </apex:form>

</apex:page>


Apex Code:

public class sample
{
    public List<Account> act = new List<Account>();
    public List<String> values = new List<String>();
    public String answer;

    public void get()
    {
        String sql = 'SELECT Name FROM Account LIMIT 10';
        act = Database.Query(sql);
       
        for(Account a:act)
        {
            values.add(a.Name);
        }
    }

    public List<SelectOption> getanswers()
    {
        List<SelectOption> options = new List<SelectOption>();
        for(String s:values)
        {
            options.add(new SelectOption(s,s));
        }       
        return options;
    }
       
    public String getanswer()
    {
        return answer;
    }

    public void setanswer(String answer)
    {
        this.answer = answer;
    }     
}

No comments:

Post a Comment