Type 4:Usage of picklist in vf & Apex

Some times we need to display picklist in Vf page which is of type picklist in Sobject. Acutally we are not displaying the picklist values but then picklist record values which may have redundency…lets take an example .


<apex:page controller="picklistexamp2" showHeader="false" sidebar="false">

 <apex:form >
  <apex:selectList size="1" value="{!selectedValue}">
   <apex:selectOptions value="{!values}"/>
   <apex:actionSupport event="onchange" reRender="one"/>
  </apex:selectList><br/>
  <apex:outputLabel id="one"><b> The selected value is : {!selected     Value}<b></apex:outputlabel>
  </apex:form>
</apex:page>

Controller


public class picklistexamp2{
public List<selectoption> getValues() {
List< selectOption> ls= new list<selectOption>();
for(Parent__c p:[select commodities__c from Parent__c]){
ls.add(new selectOption(p.commodities__c,p.commodities__c));
}
return ls;
}
public String selectedValue { get; set; }
}

Out put: Here it is displaying the totla number of picklist values present in the records but not the picklist values present in it.

 one
To Resolve this we Use Map , By Using Map We can get all unique values in the map and we can store in list to display finally.
and the for this is


List< selectOption> ls= new list<selectOption>();

map <string,selectoption> map1= new map<string,selectoption>();

for(Parent__c p:[select commodities__c from Parent__c]){
map1.put(p.commodities__c, new selectoption(p.commodities__c,p.commodities__c));
}
ls=map1.values();
return ls;
}

one

 

Advertisements

One thought on “Type 4:Usage of picklist in vf & Apex

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s