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
Aurora Ganguly 10Aurora Ganguly 10 

trigger for creating orderlineitems automatically when we create new order based on quote lineitems from quote.

Hi 
plz help me in solving this code 
trigger Testordersopp 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.QuoteId != NULL)
        {
            opportunityIds.add(o.QuoteId);
            orderList.add(o);
        }
    }

    // Query for all opportunities with their related opportunity line items
    //Map<Id,Quote> oppsWithLineItems = new Map<Id,quote>([SELECT Id, (SELECT Description,Id,ListPrice,Name,QuoteId,Product2Id,ProductCode,Quantity,TotalPrice,UnitPrice FROM QuoteLineItems) WHERE Id IN :opportunityIds]);
    Map<Id, Quote> oppsWithLineItems = new Map<Id, Quote>([SELECT Id, (SELECT Description,Id,ListPrice,Name,QuoteId,Product2Id,ProductCode,Quantity,TotalPrice,UnitPrice FROM QuoteLineItems) WHERE Id IN :opportunityIds]);

    if(opportunityIds.size() > 0)
    {
        // Loop through orders
        List<OrderItem> orderItemsForInsert = new List<OrderItem>();
        for(Order o : ordersList)
        {
            // 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
            Quote oppWithLineItem = oppsWithLineItems.get(o.QuoteId);
            for(QuoteLineItem oli : oppWithLineItem.QuoteLineItems)
            {
                orderItemsForInsert.add(new OrderItem(AvailableQuantity=Quantity,OrderId=o.Id));
            }
        }
        // If we have order line items, insert data
        if(orderItemsForInsert.size() > 0)
        {
            insert orderItemsForInsert;
        }
    }


}

lokking for your reply
Thanks​
VamsiVamsi
Hi,

Does this Map "oppsWithLineItems " retrieve any contents while processing? Becasue I could see you didn't specified the parent object in the Query after "(SELECTDescription,Id,ListPrice,Name,QuoteId,Product2Id,ProductCode,Quantity,TotalPrice,UnitPrice FROM QuoteLineItems) "