+ Start a Discussion
bhanu_prakashbhanu_prakash 

update lookup field from another object

 I have 3 objects   expense report, Region and Resource and all have lookup fields need to update using trigger.
 
 1. Expesene report has fields
 
    Expense Report Name :
    Region                :
    Company                 :
 
 2. Region object has fields
    Region Name:
    Resource   :
 
 3. Resource object has fields
    Resource Name :
    Company       :
    
    
 I need to write trigger that when expense report has created need to update company name automatically from (Expesene_report__r.Region__r.Resource__r.Company__c
 
  1. Expesene report has fields
 
    Expense Report Name :  Travel to company
    Region                :  England
    Company                :
 
 2. Region object has fields
    Region Name:  England
    Resource   :    Rajeev
 
 3. Resource object has fields
    Resource Name :    Rajeev
    Company       : Sunny Industries
    
    
    If Expense report (Travel to comapny ) is saved i need to update company as (Sunny Industries ) automatically..
Best Answer chosen by bhanu_prakash
Ahmad J. KoubeissyAhmad J. Koubeissy
Try this code:

trigger ExpenseReportAfterInsert on Expense_Report__c (before Insert){
      set<id> regionsID = new set<id>();
      for(Expense_Report__c  expRep: Trigger.New){
          regionsID.add(expRep.region__c);
      }
      
      map<id,string> mapRegionToComapnyName = new map<id,string>();
      for(region__c Region : [select id,resource__r.company__c from region__c where id in:regionsID]){ 
           mapRegionToCompanyName.put(region.id,region.resource__r.company__c);
      }
    
      for(Expense_Report__c  expRep: Trigger.New){
          expRep.company__c = mapRegionToCompanyName.get(expRep.region__c);
      }
      
}

If this solves your need, kindly mark as best answer. thanks

All Answers

Ahmad J. KoubeissyAhmad J. Koubeissy
Try this code:

trigger ExpenseReportAfterInsert on Expense_Report__c (before Insert){
      set<id> regionsID = new set<id>();
      for(Expense_Report__c  expRep: Trigger.New){
          regionsID.add(expRep.region__c);
      }
      
      map<id,string> mapRegionToComapnyName = new map<id,string>();
      for(region__c Region : [select id,resource__r.company__c from region__c where id in:regionsID]){ 
           mapRegionToCompanyName.put(region.id,region.resource__r.company__c);
      }
    
      for(Expense_Report__c  expRep: Trigger.New){
          expRep.company__c = mapRegionToCompanyName.get(expRep.region__c);
      }
      
}

If this solves your need, kindly mark as best answer. thanks
This was selected as the best answer
bhanu_prakashbhanu_prakash
Thanks Ahmad. it worked :) . we can acheive it through process builder also . If yes,please help me to create process