1

im trying to retrieve the values in a picklist (using code) that was created without code. i want to be able to assign the already created values to a custom object's field in apex. any idea how to retrieve those values below is my code

public class TestIMP { 
// a class used to test any implementation
public static void mymethod(){




}        

public static List<selectOption> returnPickList (sObject targetobject,  string objfield ){

    List<selectoption> options = new List<selectoption>();
    Schema.SObjectType objtype = targetobject.getSObjectType();
    schema.DescribeSobjectResult description = objtype.getDescribe();
    map<string, schema.SObjectField> fields = description.fields.getmap();

    List<schema.PicklistEntry> pickoptions = fields.get(objfield).getdescribe().getpicklistValues();


    for(schema.PicklistEntry a : pickoptions){

        options.add(new selectoption (a.getlabel(), a.getvalue()));

    }
    system.debug(options);
    return options;


}

}

then i opened an anonymous execution and tried to run it using this code..

    Account acct = new Account(Name='test');
   testImp.returnPickList(acct, acct.AccountSource);  

im getting a null pointer error at this line

   List<schema.PicklistEntry> pickoptions = fields.get(objfield).getdescribe().getpicklistValues();

1 Answer 1

0

Its because you are passing wrong value in the method returnPickList

 Account acct = new Account(Name='test');
 testImp.returnPickList(acct, acct.AccountSource);  

in the second line , you passing value of Account acct instance's value for AccountSource, as AccountSource was not instantiated, its value would be null and thus it gives you null pointer exception.

Fix: Provide String Constant field API name

 Account acct = new Account(Name='test');
 testImp.returnPickList(acct, 'AccountSource');  

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .