+ Start a Discussion
Rahul Singh 1384Rahul Singh 1384 

Can i upadte my field which is lookup field from other object

I have these 3 objects and all have lookup fields need to update using trigger.
 these are my objects
 1. daily report has fields:
    daily Report Name :
    RegionofReport         :
    Company                 :
 
 2. RegionofReport  object has fields
    RegionofReport Name:
    Resource   :
 
 3. Resource object has fields
    Resource Name :
    Company       :
    
 need to write trigger that when 'daily report' has created need to update company name automatically from (daily_report__r.RegionofReport__r.Resource__r.Company__c
 
  1. daily report has fields
 
    daily report Name :  Travel to company
    RegionofReport                :  US
    Company                :
 
 2. RegionofReport object has fields
    RegionofReport Name:  US
    Resource   :    rajat
 
 3. Resource object has fields
    Resource Name :    rajat
    Company       : Sumit Industries
    
    If daily report 'Travel to comapny' is saved i need to update company as 'sumit Industries' automatically.
Best Answer chosen by Rahul Singh 1384
Suraj TripathiSuraj Tripathi
Hi Rahul,

Please Try this code once, i think it should work, 

trigger DailyReportAfterInsert on daily_report__c (before Insert){
      set<id> regionsofreportID = new set<id>();
      for(daily_report__c  drp: Trigger.New){
          regionsofreportID.add(drp.RegionofReport__c);
      }
      
      map<id,string> mapRegionOfReportToComapnyName = new map<id,string>();
      for(RegionofReport__c region : [select id,resource__r.company__c from RegionofReport__c where id IN:regionsofreportID]){ 
           mapRegionOfReportToComapnyName.put(region.id,region.resource__r.company__c);
      }
    
      for(daily_report__c  drp: Trigger.New){
          drp.company__c = mapRegionOfReportToComapnyName.get(drp.RegionofReport__c);
      }     
}


Hope, It will help you,
Regards 
Suraj

All Answers

Suraj TripathiSuraj Tripathi
Hi Rahul,

Please Try this code once, i think it should work, 

trigger DailyReportAfterInsert on daily_report__c (before Insert){
      set<id> regionsofreportID = new set<id>();
      for(daily_report__c  drp: Trigger.New){
          regionsofreportID.add(drp.RegionofReport__c);
      }
      
      map<id,string> mapRegionOfReportToComapnyName = new map<id,string>();
      for(RegionofReport__c region : [select id,resource__r.company__c from RegionofReport__c where id IN:regionsofreportID]){ 
           mapRegionOfReportToComapnyName.put(region.id,region.resource__r.company__c);
      }
    
      for(daily_report__c  drp: Trigger.New){
          drp.company__c = mapRegionOfReportToComapnyName.get(drp.RegionofReport__c);
      }     
}


Hope, It will help you,
Regards 
Suraj
This was selected as the best answer
Rahul Singh 1384Rahul Singh 1384
Thank You So much Suraj for helping, it works fine for now.