+ Start a Discussion
Chirag GChirag G 

how to write trigger for the below scenario.. please help me

Hi All,

Here is the scenario : 
On the account object, create a new field to store the date and time stamp of the most recent change to the account name or the account address.

I have written th code but it's not working.. could any please help me out to correct it?? Is it possible to update date on changes without querying any account in class??

public class AccountHandler {
    public static void updateAccount(List<Account> accountList, Map<Id,Account> oldAccountMap)){
        
        Set<Id> accid = new Set<Id>();
               
        If(accid.size()>0){
            
            List<Account> accList = [SELECT Id, Name, Physical_Address__c from Account where Id in:accid);
            
            if(accList.size()>0){
                
                for(Account acc:accList) {
                    
                    if(Trigger.IsUpdate && !oldAccountMap.isEmpty() && oldAccountMap.containsKey(acc.Id) &&
                    ((oldAccountMap.get(acc.Id).Name != acc.Name || oldAccountMap.get(acc.Id).Physical_Address__c != acc.Physical_Address__c)){
                        acc.Address_Change_Date__c = System.now();
                    }                    
                }
            }        
            Update accList;
        }
    }
}


I am calling this method in after update.. from trigger controler...
sfdcMonkey.comsfdcMonkey.com
Try This one In Before Update Triiger :
public class AccountHandler {
    public static void updateAccount(List<Account> accountList, Map<Id,Account> oldAccountMap){        
		for(Account acc : accountList){
			if(Trigger.IsBefore && Trigger.IsUpdate && !oldAccountMap.isEmpty() && oldAccountMap.containsKey(acc.Id) &&
			((oldAccountMap.get(acc.Id).Name != acc.Name || oldAccountMap.get(acc.Id).Physical_Address__c != acc.Physical_Address__c)){
				acc.Address_Change_Date__c = System.now();
			}                    
		}
    }
}
Thanks, let us know if it helps you