getting Value of a field by its Name in apex salesforce

Ritesh Mehandiratta picture Ritesh Mehandiratta · Feb 27, 2013 · Viewed 35k times · Source

in my visualforce page i have some campaign object first user select an object then there is a multi picklist. in this picklist there is Label for all the fields user selects some fields then i have to show the value of these fields in the selected campaign object for showing multiple picklist my apex function is

 public List<SelectOption> getOptionalFields(){


   Map <String, Schema.SObjectField> fieldMap= Campaign.sObjectType.getDescribe().fields.getMap();
       List<SelectOption> fieldsName =new List<SelectOption>();

   for(Schema.SObjectField sfield : fieldMap.Values())
{
schema.describefieldresult dfield = sfield.getDescribe();
fieldsName.add(new SelectOption(dfield.getName(),dfield.getLabel()));

}

but i have no idea how to show value for the the field for exmple i have object instance like

Campaign c;

now i have to get value of any field whose Name is in string form.how to get corresponding value for that field.one solution is just write like say

String fieldName;

and use multiple if

if(fieldName=='Name')
c.Name=
if(fieldName=='Id')
c.Id=

is there any other convenient method??please explain!!

Answer

eyescream picture eyescream · Feb 27, 2013

You need to read about "dynamic apex". Every "concrete" sObject (like Account, Contact, custom objects) can be cast down to generic sObject (or you can use the methods directly).

Object o = c.get(fieldName);
String returnValue = String.valueOf(o);

There are some useful examples on dynamic get and set methods on Salesforce-dedicated site: https://salesforce.stackexchange.com/questions/8325/retrieving-value-using-dynamic-soql https://salesforce.stackexchange.com/questions/4193/update-a-records-using-generic-fields (second question is a bit more advanced)

You'll still need to somehow decide when to return it as String, when as number, when as date... Just experiment with it and either do some simple mapping or use describe methods to learn the actual field type...