• Nilesh Shende 6
  • NEWBIE
  • 0 Points
  • Member since 2023

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
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.
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;
  
                                              
}