How to write a Opportunity handler class for a trigger. My requirement is whenever an opportunity is created with Stagename = 'Closed Won' and an account record needs to be created opp.name = acc.name ---- Please help
Hi Ram,
Please check the below code, it will help you...
// Trigger
Trigger CreateAccountOnClosedWon on Opportunity (after insert, after update){
CreateAccountonClosedWonHelper.OppAfterUpdate(trigger.New, trigger.old, trigger.newMap, trigger.oldMap);
}
// Helper class
public class CreateAccountonClosedWonHelper{
public static void OppAfterUpdate(list<Opportunity> newOpps, list<Opportunity> oldOpps, map<Id,Opportunity> newMap, map<Id,Opportunity> oldMap) {
map<Id,Opportunity> justWonOppsMap = new map<Id,Opportunity>();
for (Opportunity o : newOpps) {
//this checks the current opp value
if(o.stageName == 'Closed Won'){
justWonOppsMap.put(o.Id, o);
}
}
List<Account> accounts = new list<Account>();
for(Opportunity opp : justWonOppsMap.values()){
If(opp.stageName == 'Closed Won'){
Account a = New Account();
// Your all account mandatory fields
accounts.add(a);
}
}
If (accounts.size()>0)
Insert accounts;
}
}
Please use below class and trigger:
public class OpportunityHandler
{
list<Account> oppList = new list<Account>();
public void oppInsert(List<Opportunity> oppLists)
{
for(Opportunity opp : oppLists)
{
if(opp.StageName =='Closed Won')
{
Account a = new Account();
a.Name = opp.Name;
oppList.add(opp)
}
}
insert oppList
}
}
********************************************Trigger***********************************************
trigger OppTrigger on Opportunity(after insert)
{
OpportunityHandler oppHandler =new OpportunityHandler();
oppHandler.oppInsert(Trigger.New);
}
Please let me know if this help !
Thanks
Shivdeep
Hi,
Hope the above trigger and class worked for you!
If not please let me know.
Thanks
Deepak
dpkm20@gmail.com