+ Start a Discussion
kynchiiin2kynchiiin2 

Apex trigger to update parent (based on lookup) when child is updated

I am rather new to apex and would greatly appreciate any help. I have 2 custom objects: Medical_Inquiry__c, Medical_Inquiry_Response__c

 

There is a lookup relationship from Medical_Inquiry_Response__c to Medical_Inquiry__c.  

 

I need a trigger that will update  

Medical_Inquiry__c.Reply_Status_btg__c

with

Medical_Inquiry_Response__c.Status__c

based on the lookup relationship whenever a Medical_Inquiry_Response__c is inserted or updated.

 

Thanks!

Steve

 

Best Answer chosen by Admin (Salesforce Developers) 
SFAdmin5SFAdmin5

here ya go

 

trigger updateMedicalInquiry on Medical_Inquiry_Response__c (before insert, before update) 
{              
     Map<Id,Medical_Inquiry__c> miMap = new Map<Id,Medical_Inquiry__c>();
     Set<id> Ids = new Set<id>();
         for (Medical_Inquiry_Response__c  mir : Trigger.new) 
         {
             Ids.add(mir.Medical_Inquiry__c);
         }
     
     Map<id,Medical_Inquiry__c> miMap2 = new Map<id,Medical_Inquiry__c>([Select Id, Reply_Status_btg__c from Medical_Inquiry__c Where Id in :Ids]);  
     
         for (Medical_Inquiry_Response__c mir : Trigger.new) 
         {
             Medical_Inquiry__c mi = miMap2.get(mir.Medical_Inquiry__c);
             mi.Reply_Status_btg__c = mir.Status__c;
             miMap.put(mi.id,mi);
         }
         
         if(!miMap.isEmpty())
         {
             update miMap.values();
         }
}

 

All Answers

SFAdmin5SFAdmin5

here ya go

 

trigger updateMedicalInquiry on Medical_Inquiry_Response__c (before insert, before update) 
{              
     Map<Id,Medical_Inquiry__c> miMap = new Map<Id,Medical_Inquiry__c>();
     Set<id> Ids = new Set<id>();
         for (Medical_Inquiry_Response__c  mir : Trigger.new) 
         {
             Ids.add(mir.Medical_Inquiry__c);
         }
     
     Map<id,Medical_Inquiry__c> miMap2 = new Map<id,Medical_Inquiry__c>([Select Id, Reply_Status_btg__c from Medical_Inquiry__c Where Id in :Ids]);  
     
         for (Medical_Inquiry_Response__c mir : Trigger.new) 
         {
             Medical_Inquiry__c mi = miMap2.get(mir.Medical_Inquiry__c);
             mi.Reply_Status_btg__c = mir.Status__c;
             miMap.put(mi.id,mi);
         }
         
         if(!miMap.isEmpty())
         {
             update miMap.values();
         }
}

 

This was selected as the best answer
kynchiiin2kynchiiin2

perfect! thank you!