• David Leckenby OES
  • 0 Points
  • Member since 2017
  • Salesforce Analyst
  • OES

  • Chatter
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
  • 0
public Class AvoidRecursion{
    private static boolean firstRun = true;
    public static boolean isFirstRun(){
      firstRun = false;
      return true;
        return firstRun;

trigger UpdateSelfManage on Case (after insert, after update) {

  if (AvoidRecursion.isFirstRun())

    //Record Ids
    List<RecordType> rList = new List< RecordType>([SELECT Id, Name FROM RecordType WHERE SObjectType = 'Case' AND DeveloperName = 'Amend_Enrolment' ]);
    Id caId = !rList.isEmpty() ? rList[0].Id : null;

    //Unique set of Course Enrolments IDs to capture
    Set<ID> setofCEIds = new Set<ID>();

     for (Case c: Trigger.New){
       if ((c.RecordTypeId == caId) && (c.Origin == 'Student Portal') && (c.Subject == 'Self Managed Amendment') && (c.Status == 'Closed')) {
    //If the list has anything in it then loop through the list of Course Enrolments and then through the related cases for each CE. If any of the related cases has the conditions as
    //described below then update the self manage statud to 'Open' and add to the listofCEstoupdate list. When all of the looping through the list of CEs is done then bulk update the list
    //outside of the loop
      if (setofCEIds.size() > 0) {

      //Flag to test if the current CE needs to be updated or not
      Boolean updatethefield = true;

      //List of Course Enrolments to query which also pulls in info from the related case record
      List<Course_Enrolment__c> listofCEs = [SELECT Id, Self_Manage_Status__c, (SELECT Id, RecordTypeId, Origin, Subject, Status, Course_Enrolment__c FROM Cases__r) FROM Course_Enrolment__c WHERE Id in :setofCEIds];

      //New empty list of Course Enrolements to add to and then finally update
      List<Course_Enrolment__c> listofCEstoupdate = new List<Course_Enrolment__c>();

        for (Course_Enrolment__c ce : listofCEs){

          updatethefield = True;

          for (Case rc : ce.Cases__r){
            if ((rc.Status <> 'Closed') && (rc.Origin == 'Student Portal') && (rc.Subject == 'Self Managed Amendment') && (rc.RecordTypeId == caId)){

                updatethefield = False; 

          if (updatethefield == True){

              ce.Self_Manage_Status__c = 'Open';

        Update listofCEstoupdate;




Dear All - Have been trying to resolve a recusion error and cannot deploy the above trigger to production. Any feedback is greatly appreciated!