Saturday 29 September 2012

Getting Picklist Fields From Object and Their Values In Apex


Today i need to finding picklist type fields and their values in my project it's very easy and simple so i want to share my code with you guys. I know some of us know about this but useful for new buddy's 

 // This Map hold all the fields of Opportunity 
 //   { If you want fields of other object replace Opportunity by other object api name}

 Map<String, Schema.SObjectField> M = Schema.SObjectType.Opportunity.fields.getMap();

 //This Map of list hold the picklist fields and picklist values 
 Map<String ,List<Schema.PicklistEntry>> MapofPicklistfieldswithValues 
                                                       = new Map<String ,List<Schema.PicklistEntry>>();

//Now we are itreating field and find that field which is picklist type and keep in our map 
 with their picklist values
  for(Schema.SObjectField x :M.values())
  {
       if(String.valueOf(M.get(String.valueOf(x)).getDescribe().getType())=='PICKLIST')
        {
          //now we find it the field which is picklist type and now we are puting its name and value in Map
           MapofPicklistfieldswithValues.put(String.valueOf(x ),
                                                                   M.get(String.valueOf(x)).getDescribe().getPicklistValues());
         }
  }

  System.debug('Api name of field which are picklist type ::: -'+MapofPicklistfieldswithValues.keyset());

  for(String fieldApiName : MapofPicklistfieldswithValues.keySet())
  {
       for(Schema.PicklistEntry Picklistvalue :MapofPicklistfieldswithValues.get(fieldApiName) )
      {
             System.debug('Name of field:::'+fieldApiName + '_______Picklist values :::'                                         
                                                                                 +Picklistvalue.getValue());
       }
 }

Thanks,

Regards,
Ashlekh Gera.

No comments:

Post a Comment