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
HelloSanHelloSan 

Autopopulate Account Owner in Oppportunity Object


Apex Trigger to Populate Custom Field of type Lookup in Opportunity Object with Account Owner from Account Object,how can i achieve this
Best Answer chosen by HelloSan
Saikishore Reddy AengareddySaikishore Reddy Aengareddy
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;
        }
    }
    
}

All Answers

Saikishore Reddy AengareddySaikishore Reddy Aengareddy
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;
        }
    }
    
}
This was selected as the best answer
HelloSanHelloSan
Thanks Saikishore,Similary i need a test class for the same trigger for the codecoverage.could you please provide me the test  class
Saikishore Reddy AengareddySaikishore Reddy Aengareddy
See this post and try to write test class and if your are stuck post your code here..

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).