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
JK84JK84 

Help with Dynamic Apex

Hi,

 

I have a custom setting in which I have about 4 field's api names.

 

Now, based on some logic, I would have to update one of the fields with a value, so I would know the field name only in run time, so how do I write the code for it in Apex ?

 

Sample code

----------------

 

List<AuditObjects__c> lstObj = [select ObjectName__c,ObjectPrefix__c from AuditObjects__c where ObjectPrefix__c=:keyPrefix LIMIT 1];

 

String lookupRelationship = lstObj[0].ObjectName__c;


 auditRecord.lookupRelationship = recordId;  // This is where I want to dynamically bind the field name.

 

update auditRecord;

Best Answer chosen by Admin (Salesforce Developers) 
JK84JK84
Hi,

Went through the Apex developers workbook and I was able to get it working by adding the following :

auditRecord.put(lookupRelationship,recordId);

Posting this, so that its helpful to someone else who is looking for a similar solution.

Thanks !!

All Answers

KamsR_DEVKamsR_DEV

Hi,

 

If you are trying to bind an ID in a lookup field, you need to declare 'lookupRelationship' field as an ID instead of String.

 

Try this,

 

List<AuditObjects__c> lstObj = [select ObjectName__c,ObjectPrefix__c from AuditObjects__c where ObjectPrefix__c=:keyPrefix LIMIT 1];

ID lookupRelationship = lstObj[0].ObjectName__c;     // Instead of string try using ID here while declare and initializing

 

auditRecord.lookupRelationship = recordId;
update auditRecord;

 

 

Have a nice day...!

 

JK84JK84
Hi,

Went through the Apex developers workbook and I was able to get it working by adding the following :

auditRecord.put(lookupRelationship,recordId);

Posting this, so that its helpful to someone else who is looking for a similar solution.

Thanks !!
This was selected as the best answer