I am trying to create an entry in the deletion_log__c object before the lead record gets deleted. I would like to capture all the lead field names along with values in the deletion_log__c object with the respective field values . 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())
        String fieldLabel = fieldMap.get(fieldName).getDescribe().getLabel();

        Schema.DisplayType fielddataType = fieldMap.get(fieldName).getDescribe().getType();

        s1 = s1+fieldName+'='+l.fieldName;


     leadDeletionLog.data__c =  s1 ;

  insert leadDeletionLogList;

However, 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, has anyone ever encountered this error?

  • I notice that l.fieldName is belong to Lead in for(Lead l:trigger.old) which is not exist, that's why it throw error. – unidha May 6 '17 at 13:52
        s1 = s1+fieldName+'='+l.fieldName;

You need to use the SObject#get method to get a field value dynamically:

        s1 = s1+fieldName+'='+String.valueOf(l.get(fieldName));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.