You need to sign in to do that
Don't have an account?

whenever Opportunity is "closed won" create an order and orderitem
My task is when opportunity is "closed won" automaticlly it should create order(populate opportunity fields) and orderitems(all opportunitylineitem products should be created in it).
I am pretty new to Salesforce development. Can anyone give me suggestion to do this.
I am pretty new to Salesforce development. Can anyone give me suggestion to do this.
trigger name on Opportunity (after update) { set<id> ids = new set<id>(); for(opportunity O:trigger.new) { if(O.StageName =='ClosedWon'){ ids.add(O.id); }} orderItem orl = new orderItem(); Opportunity opp = [select id,AccountId,CloseDate,(select Name,ProductCode,Quantity,OpportunityId from OpportunityLineItems) from Opportunity where id in:Trigger.NewMap.keySet() AND Opportunity.StageName =: 'Closed Won']; Order ord = new Order(); ord.OpportunityId=opp.id; ord.AccountId =opp.AccountId; ord.EffectiveDate = opp.CloseDate; ord.Status= 'Draft'; insert ord; for(OpportunityLineItem opl : opp.OpportunityLineItems){ orl.Order= ord; orl.Quantity=opl.Quantity; } insert orl; }
Please find the below trigger: I also tested the above code in DE environment and everything is working fine.
Note: On Opportunity Account is required to create Order and Order Item records.
Please do let me know if it helps.
Regards,
Mahesh
All Answers
Try like below and add mandatory fields .
Let me know if any helps you need !!
Thanks
Manoj
Please find the below trigger: I also tested the above code in DE environment and everything is working fine.
Note: On Opportunity Account is required to create Order and Order Item records.
Please do let me know if it helps.
Regards,
Mahesh
Thank you for your help it's working good but i have changed the 5th line
if(Trigger.OldMap.get(opp.Id).StageName != 'Closed Won' && opp.StageName == 'Closed Won' ).
You can below code only if the trigger is on update action:
In insert action, Trigger.OldMap will be null and we will get NullPointerException.
If the trigger is on both insert and update action:
Regards,
Mahesh
Thank you for your reply. i need the action only for an updation action only.