3

Basically, we have this object: Animal. And Animal has a few fields, Number_Of_Legs, Warm_Or_Cold_Blooded, etc and I basically want to automatically map the names and corresponding values into a map.

That way, as we added more fields, we wouldn't have to update the code.

Currently, we have:

    Map <String, Schema.SObjectField> fieldMap = Animal__c.getSobjectType().getDescribe().fields.getMap();

    Map<String, Integer> animalQualities = new Map<String, Integer>();
    for(String field : fieldMap.keySet()){
        //animal passed in prior...
        animalQualities.put(field, animal.getFieldValueOf(field));
    }

animal.getFieldValueOf(field) isn't a real function, but is there something similar that already exists?

5

You're looking for getPopulatedFieldsAsMap. This gives you a Map where the key is each populated field, and the value is each value stored in the record. Unpopulated values won't be present.

| improve this answer | |
0

I have in a utilities class that returns the picklist values of a field where I pass the object and the field. In this way it's one piece of code that can be reused. I think it indirectly answers your question because you can't do getfieldvalueof

public static List<SelectOption> getPicklistValues(SObject obj, String fld)
{
    List<SelectOption> options = new List<SelectOption>();

    // Get the object type of the SObject.
    Schema.sObjectType objType = obj.getSObjectType(); 
    // Describe the SObject using its object type.
    Schema.DescribeSObjectResult objDescribe = objType.getDescribe();       
    // Get a map of fields for the SObject
    Map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap(); 
    // Get the list of picklist values for this field.
    List<Schema.PicklistEntry> values = fieldMap.get(fld).getDescribe().getPickListValues();
    
    // Add these values to the selectoption list.
    for (Schema.PicklistEntry a : values)
    { 
        options.add(new SelectOption(a.getLabel(), a.getValue())); 
    }
    return options;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.