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
Anupama@28Anupama@28 

update record in trigger 'after update'

Hi,

How to update a record in a trigger after update. I have requirement like below code, when i try this i m getting error. Please help

e.g. trigger conTrigger on Contact(after update)
{
    set<id> conId = new set<id>();
 List<Contact> conList = new List<Contact>();
 List<Contact> conToUpdate = new List<Contact>();
    for(Contact con : trigger.new)
   {
       conId.add(con.id);
   }
ConList = [Select Id from contact where id in : conId];

for(Contact c : conList)
{
     c.isUpdate = true;   // Just an example
    conToUpdate.add(c);
}

update conToUpdate;
}
KaranrajKaranraj
You can do that in before update trigger operation which will avoid you perform one more DML operation on the same record
 
trigger conTrigger on Contact(before update)
{
    for(Contact con : trigger.new)
   {
       con.isUpdate = true; 
   }

}

 
Victor AbrahamVictor Abraham

Some cases, trigger can be moved to before event, but in your case I am assuming it is not possible.

Your trigger will cause recursive updates(Updating contacts again is causing the trigger to fire again). You can overcome this in two ways,
1) Externalize the code into a different class and using a static variable stop second recursive execution.
2) Make second update call once is records are not already updated. Check below code,

 trigger conTrigger on Contact(after update)
{
    set<id> conId = new set<id>();
    List<Contact> conList = new List<Contact>();
    List<Contact> conToUpdate = new List<Contact>();
    for(Contact con : trigger.new)
    {
        conId.add(con.id);
    }
ConList = [Select Id from contact where id in : conId];

for(Contact c : conList)
{
    if(c.isUpdate != TRUE){
        c.isUpdate = true;  
        conToUpdate.add(c);
    }
}
//Below check will prevent recursive triggering
if(!conToUpdate.siEmpty()){
    update conToUpdate;
}
}