+ Start a Discussion
Subha Ayyappan 7Subha Ayyappan 7 

Trigger to change the field values before deleting

Below is my code to change the Request Field value to after deleting. It works fine, but not all the time. When i delete primary request, the secondary request must be changed to primary and the tertiary must change to secondary. 
Sometimes when i delete primary, tertiary is changed to secondary but secondary is not changing to primary. Any idea please.

List<Reclassification_Request__c> lstSecondaryReq  =[Select Id,Name,Request__c, MGCRB_CBSA_Code__c from Reclassification_Request__c where Request__c='Secondary Request' LIMIT 1];
       List<Reclassification_Request__c> lstTertiaryReq  =[Select Id,Name,Request__c, MGCRB_CBSA_Code__c from Reclassification_Request__c where Request__c='Tertiary Request' LIMIT 1];
       For(Reclassification_Request__c RR : Trigger.old) {
       If (RR.Request__c == 'Primary Request') 
            {                                
                    If (lstSecondaryReq != null &&  lstSecondaryReq.size() > 0) {
                    Reclassification_Request__c SecondaryReq = new Reclassification_Request__c();    
                    SecondaryReq = lstSecondaryReq[0];
                    System.debug('Current Value To Modified '+SecondaryReq.Request__c);
                    SecondaryReq.Request__c = 'Primary Request';
                    update SecondaryReq ;
                    System.Debug('Primary to Secondary Update Completed'+SecondaryReq.Request__c);
                }
            
                If (lstTertiaryReq!= null && lstTertiaryReq.size() > 0) {
                Reclassification_Request__c TertiaryReq = new Reclassification_Request__c();    
                TertiaryReq = lstTertiaryReq[0];
                TertiaryReq.Request__c = 'Secondary Request';
                update TertiaryReq;
            }
     } else if (RR.Request__c == 'Secondary Request') 
            {
                If (lstTertiaryReq!= null && lstTertiaryReq.size() > 0) {
                Reclassification_Request__c TertiaryReq = new Reclassification_Request__c();    
                TertiaryReq = lstTertiaryReq[0];
                TertiaryReq.Request__c = 'Secondary Request';
                update TertiaryReq;
            }            
     }
       }
 
Jerome RussJerome Russ
I couldn't see anything that stood out as incorrect and the use of the word 'sometimes' makes me believe that it could be related to data available at the time of the delete's execution.

I would recommend putting in some error handling for when your lists return null.
Subha SavithriSubha Savithri
Thank you. I will try with error handling.