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
santhoshkumar Bhojan 14santhoshkumar Bhojan 14 

Trigger to update lookup field in its related objects

Hi,  Could you please help me with the below Apex trigger. I am new to coding and SFDC as well .I am not sure what went wrong. Here is my code  
Contact-lookup with case(Case_c)
Caselookup with Opportunity (Opportunity_c)and Contact(contact)
Opportunity lookup with Contact(contact_c)  
Whenever I update case_c field in Contact,it should update case object and its related opportunity  (I mean the lookup field should be updated with contact name automatically)
 trigger Contacttriggertoupdatecase1 on Contact (before update) { Set<Id> contactids=new Set<Id>(); Map<Id,case> oppcase=new Map<Id,case>(); for(contact CON:Trigger.new) { contactids.add(con.id); }  List<contact> conlist=[Select Id,FirstName,Name,case__r.id from contact where Id IN:contactids]; List<case> caselist=[Select Id,contactid from case where contactId IN: contactids];  if(Caselist.size()>0) { for(Integer i=0;i<caselist.size();i++) { if(Trigger.isbefore&&Trigger.isupdate) { if(Trigger.New[i].case__c!='NULL') { Caselist[i].contactid=Trigger.New[i].id; } } } } //Child Parent SOQL query to retrieve its related opportunity List<case> caseopplist=[Select Id,caseNumber,Opportunity__r.id from Case where id IN:caselist]; for(case co:caseopplist) { //Adding case and its related opportunity id in Map oppcase.put(co.Opportunity__r.id,co); } //Querying related opportunities List<opportunity> opplisttoupdate=[Select id,contact__c from opportunity where id in:oppcase.keyset()];  if(opplisttoupdate.size()>0) {  for(contact con:Trigger.New) { for(opportunity o:opplisttoupdate) { o.contact__c =Trigger.New[0].id; o.contact__c=con.id; //opplisttoupdate[l].contact__c =Trigger.new[l].id; opplisttoupdate.add(o); } } update opplisttoupdate; } }  Regards,
Best Answer chosen by santhoshkumar Bhojan 14
Paul S.Paul S.
This should probably be refactored to do more checking to see if the update to the contact record was the value of the Case__c field, but as a proof of concept of sorts, this should work.  This only addresses the portion of your trigger that updates the related case record, so please keep that in mind.
List<Id> caseIds = new List<Id>();

Map<Id, Case> mapOfCaseByCaseId = new Map<Id, Case>(); 
    
for(Contact con : Trigger.new) { 

    if(con.case__c != null){
        caseIds.add(con.Case__c);
    } 

}
    
List<Case> caseList = [Select Id, ContactId from case where Id IN : caseIds];
    
List<Case> casesToUpdate = new List<Case>();
    
if(caseList.size() > 0) {

    for(Case c : caseList){
        mapOfCaseByCaseId.put(c.Id, c);
    } 

    for(Contact ct : Trigger.new){
        Case c = mapOfCaseByCaseId.get(ct.case__c);
        c.ContactId = ct.Id;
        casesToUpdate.add(c);
    }

}

update casesToUpdate;

 

All Answers

Paul S.Paul S.
What isn't working?  Are the cases not being updated?  The opportunities?  Both?

 
Muzammil BajariaMuzammil Bajaria

What Error you are facing. Your question is not clear. Still as per my usderstanding I am posting a snippet. Let me know if you have any doubts.

 trigger Contacttriggertoupdatecase1 on Contact (before update) {
     for(contact CON:Trigger.new) {
        newContactMap.put(con.id,con);
     }  
     for(contact CON:Trigger.old) {
        oldContactMap.put(con.id,con);
     }  
     List<contact> conlist=[Select Id,FirstName,Name,case__r.id from contact where Id IN:newContactMap.keySet()]; 
     List<case> caselist=[Select Id,contactid from case where contactId IN: newContactMap.keySet()];
     List<case> upsertList = new List<case>();
     map<id,contact> newContactMap = new map<id,contact>(); 
     map<id,contact> oldContactMap = new map<id,contact>(); 
     for(contact con : trigger.new){
         if(newContactMap.get(con.id) == oldContactMap.get(con.id)){
             if(newContactMap.get(con.id).case_c != oldContactMap.get(con.id).case_c){
                 for(case c :caselist){
                     if(c.id == con.case__c && c.id != null){
                         upsertList.add(c);
                     }
                 }
             }
         }
     }
     
     if(upsertList.size()>0){
        upsert upsertList;         
     }
 

santhoshkumar Bhojan 14santhoshkumar Bhojan 14
Thanks for your reply.I am not getting any errors but the lookup fields are not getting updated@Paul
santhoshkumar Bhojan 14santhoshkumar Bhojan 14
Muzammil Bajaria@I tried yur code and I am getting the below error


Error: Compile Error: Variable does not exist: case_c at line 15 column 43.
Paul S.Paul S.
This should probably be refactored to do more checking to see if the update to the contact record was the value of the Case__c field, but as a proof of concept of sorts, this should work.  This only addresses the portion of your trigger that updates the related case record, so please keep that in mind.
List<Id> caseIds = new List<Id>();

Map<Id, Case> mapOfCaseByCaseId = new Map<Id, Case>(); 
    
for(Contact con : Trigger.new) { 

    if(con.case__c != null){
        caseIds.add(con.Case__c);
    } 

}
    
List<Case> caseList = [Select Id, ContactId from case where Id IN : caseIds];
    
List<Case> casesToUpdate = new List<Case>();
    
if(caseList.size() > 0) {

    for(Case c : caseList){
        mapOfCaseByCaseId.put(c.Id, c);
    } 

    for(Contact ct : Trigger.new){
        Case c = mapOfCaseByCaseId.get(ct.case__c);
        c.ContactId = ct.Id;
        casesToUpdate.add(c);
    }

}

update casesToUpdate;

 
This was selected as the best answer
santhoshkumar Bhojan 14santhoshkumar Bhojan 14
Paul@Sorry for the delay in reply.Thanks a lot for your reply and its working fine.I have a clarification here,in Map we are updating Case Id and case in line 20.
for(Case c : caseList){
  mapOfCaseByCaseId.put(c.Id, c);
But in line 24,you are retreiving as contact field i.e  Case c = mapOfCaseByCaseId.get(ct.case__c).Can you please give me some headsup on this .I am completely confused

Regards,
Santhosh Kumar
Paul S.Paul S.
Santhosh - the case__c lookup field on your contact record holds a case Id, so we can then use that to retrieve the case from the map.  It doesn't matter that we we populated the map directly from the case record.  I'm doing so in the context of a contact-based for loop so that we can easily update the contactId field on the case record with the Id of the contact record that we're currently looping through.  
santhoshkumar Bhojan 14santhoshkumar Bhojan 14
Thanks for your clarification Paul.Now how do I update related opportunity from caselist. 

Regards,
Santhosh Kumar
Paul S.Paul S.
I believe this will work - you may want to tinker around with it.
List<Id> caseIds = new List<Id>();
List<Id> oppIds = new List<Id>();

Map<Id, Case> mapOfCaseByCaseId = new Map<Id, Case>(); 
Map<Id, Opportunity> mapOfOppByOppId = new Map<Id, Opportunity>();
    
for(Contact con : Trigger.new) { 

    if(con.case__c != null){
        caseIds.add(con.Case__c);
    } 

} 

List<Case> casesToUpdate = new List<Case>();
List<Opportunity> oppsToUpdate = new List<Opportunity>();
    
List<Case> caseList = [SELECT Id, ContactId, Opportunity__c FROM Case WHERE Id IN : caseIds];

if(caseList.size() > 0) {

    for(Case c : caseList){
        mapOfCaseByCaseId.put(c.Id, c);
        oppIds.add(c.opportunity__c);
    }

    for(Opportunity o : [SELECT Id, Contact__c FROM Opportunity WHERE Id IN : oppIds]){
        mapOfOppByOppId.put(o.Id, o);
    } 

    for(Contact ct : Trigger.new){

        if(mapOfCaseByCaseId.get(ct.case__c) != null){
            Case c = mapOfCaseByCaseId.get(ct.case__c);
            c.ContactId = ct.Id;
            casesToUpdate.add(c);

            if(mapOfOppByOppId.get(c.Opportunity__c) != null){
                Opportunity o = mapOfOppByOppId.get(c.Opportunity__c);
                o.Contact__c = ct.Id;
                oppsToUpdate.add(o);
            }
        }


    }

}

update casesToUpdate;
update oppsToUpdate;

 
santhoshkumar Bhojan 14santhoshkumar Bhojan 14
It works perfect.Thanks a lot Paul.You are Genius!!!