Hope this helps... and modify as per your needs...This trigger will update the opportunity owner with its respective accounts owner and if you want any custom field to be updated on opportunity with account owner update the highlighted line with your any custom field.
trigger opportunityTrigger on Opportunity (before insert) {
map<id,Account> accIdMap; set<id> accIds = new set<Id>();
for(opportunity o : trigger.new){ if(o.AccountId != null) accIds.add(o.AccountId); }
if(accIds != null){ accIdMap = new map<id, Account>([select id, ownerId from Account where Id IN : accIds]); for(opportunity o : trigger.new){ if(o.AccountId != null) o.ownerId = accIdMap.get(o.AccountId).ownerId; } }
Hope this helps... and modify as per your needs...This trigger will update the opportunity owner with its respective accounts owner and if you want any custom field to be updated on opportunity with account owner update the highlighted line with your any custom field.
trigger opportunityTrigger on Opportunity (before insert) {
map<id,Account> accIdMap; set<id> accIds = new set<Id>();
for(opportunity o : trigger.new){ if(o.AccountId != null) accIds.add(o.AccountId); }
if(accIds != null){ accIdMap = new map<id, Account>([select id, ownerId from Account where Id IN : accIds]); for(opportunity o : trigger.new){ if(o.AccountId != null) o.ownerId = accIdMap.get(o.AccountId).ownerId; } }
trigger opportunityTrigger on Opportunity (before insert) {
map<id,Account> accIdMap;
set<id> accIds = new set<Id>();
for(opportunity o : trigger.new){
if(o.AccountId != null)
accIds.add(o.AccountId);
}
if(accIds != null){
accIdMap = new map<id, Account>([select id, ownerId from Account where Id IN : accIds]);
for(opportunity o : trigger.new){
if(o.AccountId != null)
o.ownerId = accIdMap.get(o.AccountId).ownerId;
}
}
}
All Answers
trigger opportunityTrigger on Opportunity (before insert) {
map<id,Account> accIdMap;
set<id> accIds = new set<Id>();
for(opportunity o : trigger.new){
if(o.AccountId != null)
accIds.add(o.AccountId);
}
if(accIds != null){
accIdMap = new map<id, Account>([select id, ownerId from Account where Id IN : accIds]);
for(opportunity o : trigger.new){
if(o.AccountId != null)
o.ownerId = accIdMap.get(o.AccountId).ownerId;
}
}
}
http://salesforce.stackexchange.com/questions/27500/writing-a-test-for-a-simple-apex-trigger
https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods
In your test class you will need to create a user(optional), Account and then opportunity and assertions(optional).