Hi Jhony, Please look at the below code, it ll help you bcoz its working fine for me.
// Trigger
Trigger CreateAssetonClosedWon on Opportunity (after insert, after update){
CreateAssetonClosedWonHelper.OppAfterUpdate(trigger.New, trigger.old, trigger.newMap, trigger.oldMap);
}
// Helper class
public class CreateAssetonClosedWonHelper{
Private static Map <Id,boolean> oldIsWonMap = null;
public static void OppAfterUpdate(list<Opportunity> newOpps, list<Opportunity> oldOpps, map<Id,Opportunity> newMap, map<Id,Opportunity> oldMap) {
if(oldIsWonMap == null) {
oldIsWonMap = new map<Id,boolean >();
}
map<Id,Opportunity> justWonOppsMap = new map<Id,Opportunity>();
for (Opportunity o : newOpps) {
//This checks to see if there was a value set in a previous trigger run
boolean oldIsWon = (oldIsWonMap.containsKey(o.id)) ? oldIsWonMap.get(o.id) : oldmap.get(o.id).isWon;
//this checks the current opp value with the 'correct' old value
if(o.isWon && !oldIsWon){
justWonOppsMap.put(o.Id, o);
}
//this puts in the 'correct' old value in case the trigger is run again in the same context
if(oldIsWon != o.isWon) {
oldIsWonMap.put(o.id,o.isWon);
}
}
Map<id, opportunityLineItem> mapOpp = new Map<id, opportunityLineItem>([Select UnitPrice, Quantity, PricebookEntry.Product2Id, PricebookEntry.Product2.Name,Converted_to_Asset__c
From OpportunityLineItem where opportunityId IN : justWonOppsMap.KeySet() and converted_to_Asset__c = false]);
List<Asset> assets = new list<Asset>();
for(Opportunity opp : justWonOppsMap.values()){
For (opportunityLineItem Oli : mapOpp.values()){
If(opp.iswon == true && opp.hasopportunitylineitem ==true){
Asset a = new asset();
a.name = Oli.pricebookentry.product2.name;
a.Accountid = opp.Accountid;
a.product2id = Oli.pricebookentry.product2id;
a.quantity = Oli.quantity;
a.price = Oli.unitprice;
a.purchasedate = opp.closedate;
assets.add(a);
}
}
}
If (assets.size()>0)
Insert assets;
}
}
public Class OpportunityTriggerHandler{
public static void onAfterInsert(List<Opportunity> newOpp){
}
public static void onAfterUpdate(List<Opportunity> newOpp, List<Opportunity> oldOpp){
}
}
This is the basic to create a handler, newOpp and oldOpp is the value from trigger.new and trigger.old respectively. now you can perform your operations in this method, let me know if you need more help.
Please look at the below code, it ll help you bcoz its working fine for me.
Please let me know if this help !
Thanks
Shivdeep
Apex Trigger
Handler Class
Please follow above code. Please mark my answer as a solution if it is helpful.
Thanks,
Harshit Garg
harshitgarg2591@gmail.com
Please try below code:
Apex Trigger; Handler: This is the basic to create a handler, newOpp and oldOpp is the value from trigger.new and trigger.old respectively. now you can perform your operations in this method, let me know if you need more help.
Hope this helps.
Regards,
Nagendra.