+ Start a Discussion

getting Value of a field by its Name in apex salesforce

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


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

Best Answer chosen by Admin (Salesforce Developers) 

Yes, you can use dynamic DML:




So to access the field matching the fieldName variable, you'd use the get notation :


Object fldObj=c.get(fieldName);