Saturday, July 1, 2017

Field expression not allowed for generic SObject in Salesforce

Scenario:


Usually when we writing any trigger we will be following some best practices like One Trigger for One Object,Business logic in Handler Class ,Don't write the whole code in Trigger etc..This kind of error will receive when we are writing whole trigger logic in Separate Handler Class(Apex class) and we are referring to that trigger context variables  in that Apex class or  referring your sobjects in Trigger handler


Root Cause : 


Trigger Code

Trigger CaseTrigger on Case (Before Insert,Before Update,After insert) 
{
   if(Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate))
    {
        CaseTriggerHandler.duplicateCheck(Trigger.new);
    }
}

Handler Class

Public class CaseTriggerHandler
{ 
public static void duplicateCheck(List<Case> TriggerNew)
 {
         for (Case cs : TriggerNew) 
        {
           if(cs.status__c!=Trigger.OldMap.get(cs.Id).status__c)
            {
               System.debug('Status has changed');
            }
        }
 }
}

When your trying save above handler code you will end up with Field expression not allowed for generic SObject .


Solution:

The reason behind is that Trigger.OldMap is a generic variable that means it will be used for all objects so when your using this variable you need to tell the compiler what type of the SObject your referring from Trigger.OldMap. I have highlighted that code change in yellow color in below code.
        

Public class CaseTriggerHandler
{ 
public static void duplicateCheck(List<Case> TriggerNew)
 {
         for (Case cs : TriggerNew) 
        {
           if(cs.status__c!=((Map<Id,Case>)Trigger.OldMap).get(cs.Id).status__c)
            {
               System.debug('Status has changed');
            }
        }
 }
}


Thanks for visiting..hope this helps you!

No comments: