function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ritesh__Ritesh__ 

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

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

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

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

Yes, you can use dynamic DML:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_dml.htm

 

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

 

Object fldObj=c.get(fieldName);