Sunday, 21 August 2011

Create Drop Down List From Picklists

Sometimes its not possible to use <apex:inputfield /> or
            <apex:selectList size="1"  id="dependentField" required="false" value="{!aTask.1stfield}" .>                 
to display values from a picklist.

So I wondered how do I find the values in a picklist through code and display them on the page.
The code below shows a function getTaskStatus() which uses the functions getTheseSelectOptions() and getThePicklists() which find values from any picklist field and exclude any values which you want to exclude.

    <apex:selectList size="1" required="false" value="{!aTask.2ndfield}">
                        <apex:selectOptions value="{!TaskStatus}" />

   public Task aTask {get;set;}
   public List<SelectOption> getTaskStatus() {
            //gets the picklists
            List<SelectOption> options = new List<SelectOption>();
                String[] excluded = new String[]{''};
                options = getTheseSelectOptions('<<object>>','<<picklist field>>',excluded,false);
            return options;

public static List<SelectOption> getTheseSelectOptions(String thisObject, String thisField, List<String> excluded, Boolean optionalBlank) {

        List<SelectOption> options = new List<SelectOption>();
        if (optionalBlank)
            options.add(new SelectOption('' ,'' ));
            List<Schema.PicklistEntry> returnPicks = getThePicklists(thisObject, thisField);
            if (returnPicks == null)
                return null;
            String thisPickValue;
            Boolean ExclusionExists;
            for (Schema.PicklistEntry EachVal: returnPicks){
                thisPickValue = String.valueof(EachVal.getValue());
                //search each Exclusion for this thisPickValue
                for (String EachExclusion: excluded){
                    if (thisPickValue != EachExclusion)
                        options.add(new SelectOption(thisPickValue,thisPickValue)); //add thisPickValue if it is not in the Exclusion
        catch(Exception e){}
        return options;  

public static List<Schema.PicklistEntry> getThePicklists(String thisobject,String thisFieldName){ 

    List<Schema.PicklistEntry> picklists;
        Map<String, Schema.SObjectType> thisPickListMap = Schema.getGlobalDescribe();
        Schema.SObjectType myObjectType = thisPickListMap.get(thisobject) ;
        Schema.DescribeSObjectResult objResult = myObjectType.getDescribe() ;
        Map<String, Schema.SObjectField> fields = objResult.fields.getMap() ;

        Schema.SObjectField selectedObjectFld = fields.get(thisFieldName) ;
        Schema.DescribemyfldResult myfldResult = selectedObjectFld.getDescribe() ;
        picklists = myfldResult.getThePicklists();
    catch(Exception e){}
    return picklists;

No comments:

Post a Comment

Note: only a member of this blog may post a comment.