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
Ravi Panchal 8Ravi Panchal 8 

how to get value from parent object field to child object trigger

If I want to get an account phone and update it on Opportunity,  the field name is  'Account_Phone__c'  please help me write a trigger to achieve this 
Thank you in advance.
Best Answer chosen by Ravi Panchal 8
mukesh guptamukesh gupta
HI Ravi,

Please use below code:-
 
Trigger OpportunityFieldupdate on opportunity(before insert, before update){

set<id> accids = new set<id>();
for(opportunity opp:trigger.new){
   if( opp.AccountId!=Null){
       accids.add(opp.Accountid);
    }
}
Map<id,Account> accMap = new Map<id,Account>();
for(Account acc:[select id, Phone from account where id=:accids]){
     accMap.put(acc.id,acc);
}
for(opportunity opp:trigger.new){
  if(accMap.containskey(opp.AccountId)){
        opp.Account_Phone__c = accMap.get(opp.AccountId).Phone;
    }
  }
}

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh

All Answers

AnkaiahAnkaiah (Salesforce Developers) 
Hi Ravi,

try with below code.
Trigger AccountFieldupdate on opportunity(before insert, before update){

set<id> accids = new set<id>();

for(opportunity opp:trigger.new){
if( opp.AccountId!=Null){

accids.add(opp.Accountid);

}
}
List<id,string> accmapwithphone = new List<id,string>();

for(Account acc:[select id, Phone from account where id=:accids]){
accmapwithphone.put(acc.id,acc.phone);
}

for(opportunity opp:trigger.new){
if(accmapwithphone.containskey(opp.AccountId)){
opp.Account_Phone__c = accmapwithphone.get(opp.AccountId);
}
}

}

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​
mukesh guptamukesh gupta
HI Ravi,

Please use below code:-
 
Trigger OpportunityFieldupdate on opportunity(before insert, before update){

set<id> accids = new set<id>();
for(opportunity opp:trigger.new){
   if( opp.AccountId!=Null){
       accids.add(opp.Accountid);
    }
}
Map<id,Account> accMap = new Map<id,Account>();
for(Account acc:[select id, Phone from account where id=:accids]){
     accMap.put(acc.id,acc);
}
for(opportunity opp:trigger.new){
  if(accMap.containskey(opp.AccountId)){
        opp.Account_Phone__c = accMap.get(opp.AccountId).Phone;
    }
  }
}

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh
This was selected as the best answer
Ravi Panchal 8Ravi Panchal 8
Thank you both for your assistance.