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
narendharnarendhar 

Capturing deletion log using dynamic apex

I am trying to create an entry in to deletion_log__c object before the lead record gets deleted, I would like to capture all the lead field names along with values in deletion_log__c object with the respective field values in to single field deletion_log__c .data__c . I would like my code to be dynamic(i mean in future if i create any new fields , the same field values also should get captured with out modifying the existing code). 

I am using the below code for the same ,
trigger leadTrg on Lead (before delete) {

public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();

 list<Deletion_Log__c> leadDeletionLogList = new list<Deletion_Log__c>();
 Schema.SObjectType leadSchema = schemaMap.get('Lead');
 Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();
for (lead l: trigger.old){
   
    Deletion_Log__c leadDeletionLog = new Deletion_Log__c ();
    
    
    string logRecord ;
    
    for (String fieldName: fieldMap.keySet())
    { 
        system.debug('fieldName&&&'+fieldName);
        String fieldLabel = fieldMap.get(fieldName).getDescribe().getLabel();
 
       
        Schema.DisplayType fielddataType = fieldMap.get(fieldName).getDescribe().getType();
        
        s1 = s1+fieldName+'='+l.fieldName;
         
     }
     
     leadDeletionLog.data__c =  s1 ;
     leadDeletionLogList.add(leadDeletionLog);
     
  }
  insert leadDeletionLogList;
}



but i am not able to save the code , i am getting the error message "Invalid field fieldName for SObject Lead ". 

The statement " s1 = s1+fieldName+'='+l.fieldName;" is causing the error, i am clueless about the reason anyone has ever encountered this error?
Thanks
Best Answer chosen by narendhar
Nayana KNayana K
s1 = s1+fieldName+'='+l.get(fieldName);

 

All Answers

Nayana KNayana K
s1 = s1+fieldName+'='+l.get(fieldName);

 
This was selected as the best answer
narendharnarendhar
Missed this point, Thank you.