+ Start a Discussion
hramanihramani 

After Insert and After Update trigger issue

I'm working on a Trigger on Account where a field named 'test__c' should get updated when a record is created or edited. I wrote a trigger for that. Below it is.  But when I create a record or edit it, I get an error "first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, TestUpdate: maximum trigger depth exceeded Account trigger event AfterUpdate for [0019000001ZgGny"

Can someone help me with this.

Below is the code:

trigger TestUpdate on Account ( after insert, after update) {


List<Account> ast = new List<Account>();

for (Account a : [select id, name, test__c from Account where id IN: trigger.new])

{

if (a.test__c == null)        
        a.test__C = 'TestUpdate';
        
ast.add(a);
}

update ast;
}
Vishal Negandhi 16Vishal Negandhi 16
Since you're updating the current record, your trigger should be a before insert trigger/before update trigger instead of after insert/update. 
 
trigger TestUpdate on Account ( before insert, before update) {


for (Account a : trigger.new)

{

if (a.test__c == null)        
        a.test__c = 'TestUpdate';
        
}

}

Check this link to understand better on when to use before and after triggers:

http://www.sfdc99.com/2014/01/25/use-vs-triggers/