[SalesForce] Display a pick list field on a visual force page using custom controller

visualforce page

<apex:page Controller="AddAccountCntrlr" >
<apex:form>
<apex:pageBlock title="Add Account" >    
    <apex:pageBlockButtons>
        <apex:commandButton value="Save" action="{!Save}" />
    </apex:pageBlockButtons>
        Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<apex:inputText value="{!name}" /><br/><br/>
        Phone&nbsp;&nbsp;&nbsp;&nbsp;<apex:inputText value="{!phone}" /><br/><br/>
        Account<br/> Number&nbsp;&nbsp;<apex:inputText value="{!accountNumber}" /><br/><br/>
        Industry&nbsp;&nbsp;<apex:inputText value="{!industry}" />
</apex:pageBlock>
</apex:form>    

I want to display industry as a picklist field

Industry&nbsp;&nbsp;<apex:inputText value="{!industry}" />

controller

public class AddAccountCntrlr {

public String name{get;set;}
public String phone{get;set;}
public String industry{get;set;}
public String accountNumber{get;set;}

public pagereference save(){
    Account acc = new Account(name=name, phone=phone, industry=industry, accountnumber=accountnumber);  
    insert acc;
    String accId = acc.Id;
    return null;
}
public List<Account> getnewAccountTable(){
    return accTable;
}

}

Best Answer

2 Changes

1.Instead of declaring a string for each type instantiate a controller variable of type account and use it in the VF page

public Account accnt{get;set;}

2.In the page use apex:inputField instead of inputtext and it can dynamically read the type of field from the sObject and display picklist,date if the field of type date and so on. Documentation

<apex:inputField value="{!accnt.industry}"/>

Finally you can use accnt variable to directly save the data in Account object.

Related Topic