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
Shobhit Jain 7Shobhit Jain 7 

After Insert Trigger Issue

Could someone throw light on this what could be the issue in this trigger? JFYI it gives below error 
Apex trigger t2 caused an unexpected exception, contact your administrator: t2: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, t2: maximum trigger depth exceeded Case trigger even

trigger t2 on Case (after insert)
{
  List<case> chcase = new List<case>();
  for (Case c: trigger.New)
  {
    Case child = new Case(ParentId = c.Id, subject = c.Subject);
    chcase.add(child);
  }
  insert chcase;  
}
Bryan JamesBryan James
It looks to me as if you may be having an issue with recursion. Your trigger is set up to run after the insert of a case record. Inside of your trigger you are creating cases. This will cause an infinate loop of created cases. 
Hargobind_SinghHargobind_Singh
Hi, if you want to create a child case on every case creation, you will need to make sure that the child case doesn't create another child case under it. Maybe update a flag on your original case as "parent case" from your trigger and then use that flag to detect and create the child-case. 

As @bryan pointed out, this will result in an infinite loop of cases trying to create child cases. 
BALAJI CHBALAJI CH
Hi Shobit Jain,

Agreeing with @Bryan and @Hargobind, your trigger will result in an Infinite loop of cases and you can create and update a Flag on your Original case as "Parent Case" to distinguish with other cases.
Another workaround is, you can check the case whether it has a ParentId or not before continuing in the loop to create a Child Case.
Please find below modified trigger.
trigger t2 on Case (after insert)
{
    List<case> chcase = new List<case>();
    for (Case c: trigger.New)
    {
        if(c.ParentId == null)
        {
            Case child = new Case(ParentId = c.Id, subject = c.Subject);
            chcase.add(child);
        }
    }
    insert chcase;  
}

Best Regards,
BALAJI