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
nagarjuna gurajanagarjuna guraja 

Need Exact Trigger

Hello,
 Write a trigger on Opportunity that create a task on Opportunity whenever Account Owner is Changed.

I need an apex trigger.Could anyone please help me with this
AnkaiahAnkaiah (Salesforce Developers) 
Hi Nagarjuna,

try with below code.
trigger createopptaskonownerchange on Account (after update) {
    
    set<id> accids = new set<id>();
    for(account acc :trigger.new){
        
        if(acc.ownerid != trigger.oldmap.get(acc.id).ownerid){
          accids.add(acc.id) ; 
        }
    }
    
    List<task> tasktoinsert = new List<task>();
    
    for(opportunity opp:[select id,Accountid from opportunity where accountid=:accids limit 1]){
      
        Task t = new task();
        t.Subject = 'Follow Up Test Task'; 
        t.WhatId = opp.Id;
        tasktoinsert.add(t);
                
    }
  
    insert tasktoinsert;
    

}
Let me know if any issues.

If this helps, Please mark it as best answer.

Thanks!!
mukesh guptamukesh gupta
Hi Nagarjun,

Please follow below code:-
 
trigger ownerCheck on Opportunity (before insert, before update) {
    Set<Id> accountIds = new Set<Id>();
    Map<Id, Id> accountOwnerIds = new Map<Id, Id>();
    for(Opportunity opps : Trigger.New) {
        accountIds.add(opps.AccountId);
    }
 List<task> tasktoinsert = new List<task>();
    Map<Id, Account> accountsIdMap  = new Map<Id, Account>([SELECT Id, OwnerId FROM Account where Id IN :accountIds]);
    for(Opportunity opp : Trigger.New) {
        if(opp.OwnerId <> accountsIdMap.get(opp.AccountID).OwnerId) {
             Task t = new task(); 
             t.Subject = 'Follow Up Test Task'; 
             t.WhatId = opp.Id; 
             tasktoinsert.add(t);
        }
    }

if(tasktoinsert.size() > 0)
insert tasktoinsert;
}


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

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

Thanks
Mukesh