So I got help on something recently where I was having a recursive issue with queries, and I got that sorted out.
Today I am having issues with trying to run this loop on a single record.
It's supposed to populate a date field if it is empty. When creating a new record or trying to update I get this error:
Error: Invalid Data. Review all error messages below to correct your data. Apex trigger dreamDateUpdate caused an unexpected exception, contact your administrator: dreamDateUpdate: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id a0p370000017LJ9AAM; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, dreamDateUpdate: maximum trigger depth exceeded Dream_Journal trigger event AfterUpdate for [a0p370000017LJ9] Dream_Journal trigger event AfterUpdate for [a0p370000017LJ9] Dream_Journal trigger event AfterUpdate for [a0p370000017LJ9] Dream_Journal trigger event AfterUpdate for [a0p370000017LJ9] Dream_Journal trigger event AfterUpdate for [a0p370000017LJ9] Dream_Journal trigger event AfterUpdate for [a0p370000017LJ9]: []: Trigger.dreamDateUpdate: line 17, column 1
It shows more recursive errors than that, but I cut out a lot of them posting this because I figured that is enough.
My expectation is that once I populated the record date field it would invalidate it from meeting the criteria then next time the loop iterated. I also tried creating a Set collection, and the run the loop only on Id's in the collection, but it still generated the same result. I've been scratching my head all day trying to figure it out.
All I can figure is I'm not invalidating it properly after it's been looped. Any advice would be greatly appreciated.
Thanks!
Trigger setDate on object__c (after insert, after update){
List<object__c> tuList = new List<object__c>();
for(object__c checkThis : trigger.new)
{
object__c toUp = new object__c();
toUp.Id = checkThis.Id;
if(checkThis.Date == null)
{
toUp.Date = Date.Today();
}
tuList.add(toUp);
}
update tuList;
}
Resolution notes: Using the marked answer, I was able to figure out what I was doing wrong. When using an after update trigger, if you aren't being careful, it runs recursive because you are saying "Hey! Update this record" IN the trigger. And then the trigger says "Hey! Something got updated, I need to do more stuff." This creates a loop. For this particular case I was able to switch to a before insert, before update trigger, which adds additional criteria to be inserted/updated. Salesforce, in this case, includes that information as part of it's normal update or insert event, without us have to specifically call it.