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
Debendra Ray 8Debendra Ray 8 

Validate creation of related Child Objects in a Master Detail Relationship using APEX

I've three objects: Customer_Visit_Report__c, Action_Point__c , Invitee__c  wherein Action_Point__c , Invitee__c  are child objects for the master Customer_Visit_Report__c. I would like the users to create Action_Point__c , Invitee__c objects much before they create the Customer_Visit_Report__c object. Below is the code, which is not giving me the desired result :

trigger ValidateCVRInvittee_Task_Creation on Customer_Visit_Report__c (after update) {
    
    for (Integer i = 0; i < Trigger.new.size(); i++) {
         try{
           
           
           List<Customer_Visit_Report__c> cvrLst = [select Invitee_Created__c , Actions_Created__c from Customer_Visit_Report__c where id = :Trigger.new[i].id ];
           List<Action_Point__c> cvrActionLst = [select id , name  from Action_Point__c where Customer_Visit_Report__c = :Trigger.new[i].id ]; 
           List<Invitee__c> cvrInviteeLst = [select id , name  from Invitee__c where Customer_Visit_Report__c = :Trigger.new[i].id ]; 
            
           if(cvrActionLst.size() == 0 ){
                 Trigger.new[i].addError('Please create Actions for this Customer Visit Report !');
            }
             
            if(cvrInviteeLst.size() == 0 ){
                 Trigger.new[i].addError('Please create Invitees for this Customer Visit Report !');
            } 
             
             if(cvrInviteeLst.size() > 0 && cvrInviteeLst.size() >0 ){
                 
                 for(Customer_Visit_Report__c cvr :cvrLst ){
                     
                     cvr.Invitee_Created__c = true;
                     cvr.Actions_Created__c = true;
                 
                 }
                 
                  if(RecursiveTriggerHandler.isFirstTime){
                                  RecursiveTriggerHandler.isFirstTime = false; 
                                  update cvrLst;
                   }
                 
                 
             }       
          
                    
         
          }catch(Exception e)
         {
           Trigger.new[i].addError(e.getMessage());
           System.debug('Error : ValidateCVRInvittee_Task_Creation ->'+ e);  
        }
        
    }  
    

}


Any help towards this end will be much appreciated.
HARSHIL U PARIKHHARSHIL U PARIKH
Hi Debendra,

question: why would you want child records created before parent? This won't be possible in master detail relationship in my opinion.