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
jishan royjishan roy 

Account owner name should same as Opportunity owner name when user is change.

This is my trigger:
Whats wrong in this trigger please help me out of this problem.

code:
trigger oppOwnerTrigger on Opportunity (after insert) {
    set<id> setAccountId = new set<id>();
    list<Opportunity> oppolist = new list<Opportunity>();
    for(Opportunity opp: trigger.new){
        setAccountId.add(opp.AccountId); 
    }
list<Account> acclist=[select id, Name, (select id ,Owner.Name from opportunities) from account where Name != 'null'];
    for (Opportunity op:trigger.new){
    for(Account accc : acclist){
        op.Name = accc.Owner.Name;
        system.debug('Account' + accc);
        oppolist.add(op);
    }
    }
    insert oppolist;
     }


thanks in advance.
Best Answer chosen by jishan roy
AnkaiahAnkaiah (Salesforce Developers) 
Hi Jishan,

try with below code.
trigger oppOwnerTrigger on Opportunity (before insert,before update) {
    set<id> setAccountId = new set<id>();
    for(Opportunity opp: trigger.new){
	if(opp.AccountId !=Null){
        setAccountId.add(opp.AccountId); 
		}
    }

Map<id,Account> mappaccidwithvalues = new map<id,Account>();

for(Account acc:[select id,ownerid from Account where id=:setAccountId]){
mappaccidwithvalues.put(acc.id,acc);

}

    for (Opportunity op:trigger.new){
      if(mappaccidwithvalues.containskey(op.accountid)){
	  
	  op.ownerId = mappaccidwithvalues.get(op.accountid).ownerid;
	  }

    }
 }

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​

All Answers

AnkaiahAnkaiah (Salesforce Developers) 
Hi Jishan,

can you confirm the below scenario?

When ever Account owner changes then related opportunity owner change or whenever opportunity owner changes then related account owner should change?

Thanks!!
jishan royjishan roy
account is created in user1 owner and those account opn in user 2 but when i created related opportunity in user 2 then opportunity owner should same as account owner.
AnkaiahAnkaiah (Salesforce Developers) 
Hi Jishan,

try with below code.
trigger oppOwnerTrigger on Opportunity (before insert,before update) {
    set<id> setAccountId = new set<id>();
    for(Opportunity opp: trigger.new){
	if(opp.AccountId !=Null){
        setAccountId.add(opp.AccountId); 
		}
    }

Map<id,Account> mappaccidwithvalues = new map<id,Account>();

for(Account acc:[select id,ownerid from Account where id=:setAccountId]){
mappaccidwithvalues.put(acc.id,acc);

}

    for (Opportunity op:trigger.new){
      if(mappaccidwithvalues.containskey(op.accountid)){
	  
	  op.ownerId = mappaccidwithvalues.get(op.accountid).ownerid;
	  }

    }
 }

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​
This was selected as the best answer
jishan royjishan roy
hi ankaiah
thankyou for helping