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
si risi ri 

Trigger On Order to get Opportunity Line Item from opportunity to add in orderlineitem

Hi all,
1.When Order is created, copy the OpportunityLineItem
2.When OpportunityLineItems are changed (added/updated/deleted), resync to OrderItem (presumably once Opportunity is closed, this can't happen)
But when i edit and save the record duplicate orderitems are creating, my requirement is to create only once, if the new product is added on the opportunity then it only that product should be added in the Orderitem. can anyone help me.Thanks in advance
trigger creatingMenuDetails on Order (after insert, after update)
{
    // Get all related opportunities from orders
    Set<Id> opportunityIds = new Set<Id>();
    List<Order> orderList = new List<Order>();
    for(Order o : Trigger.new)
    {
        if(o.Opportunity__c != NULL)
        {
            opportunityIds.add(o.Opportunity__c);
            orderList.add(o);
        }
    }

    // Query for all opportunities with their related opportunity line items
    Map<Id, Opportunity> oppsWithLineItems = new Map<Id, Opportunity>([SELECT Id,Pricebook2Id, (SELECT Description,Id,ListPrice,Name,OpportunityId,Product2Id,ProductCode,Quantity,TotalPrice,UnitPrice FROM OpportunityLineItem) WHERE Id IN :opportunityIds]);
   List<Order>  updateorderList = new List<Order>();
    if(opportunityIds.size() > 0)
    {
        // Loop through orders
        List<OrderItem> orderItemsForInsert = new List<OrderItem>();
        for(Order o : ordersList)
        {
              o.Pricebook2Id = oppsWithLineItems.get(o.OpportunityId).pricebook2Id;
            // For each order get the related opportunity and line items, loop through the line items and add a new order line item to the order line item list for each matching opportunity line item
            Opportunity oppWithLineItem = oppsWithLineItems.get(o.Opportunity__c);
            for(OpportunityLineItem oli : oppWithLineItem.OpportunityLineItems)
            {
                orderItemsForInsert.add(new OrderItem(AvailableQuantity=Quantity,OrderId=o.Id,etc,etc,etc));
            }
        }
          update updateorderList;
        // If we have order line items, insert data
        if(orderItemsForInsert.size() > 0)
        {
            insert orderItemsForInsert;
        }
    }
}
Lokesh KumarLokesh Kumar
Remove the update event from the Order trigger and you need to create a trigger on the Opportunity Products whenever a new line item is added or deleted if an order is created for the opportunity update the order line item. I hope you understand the logic.
 
si risi ri
Hi Lokesh kumar,
can you guide me with sample code