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
Priya MishraPriya Mishra 

Auto creation of order and order line item when meeting to the certain condition

Hi All,

I Have a requirment to  auto create the record when when meeting certain condtion with specified values.

1. Create new order with the order line item type='exchange In'  condtion is there is a retun required field is is true.
2.In created order fileds should populate are Account (coming from thre work order object), Work Order from word order object.
3. Created Order Line Item with some fields like product from Asset 
Asset from Repair history object.

How we can acheive this is that flow will work here or coding we have to do or is there other way to do this. pls guide me its an urgent work.

Thanks in advance.
Best Answer chosen by Priya Mishra
VinayVinay (Salesforce Developers) 
Hi Priya,

As per my understanding you can acheive this by using flow,  try to implement and come back and post question again if you see any errors.

Below sample example of creating orderlineitems automatically when we create new order based on quote lineitems from quote
 
trigger Test on Order (after insert,after update) {
       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);
        }
    }

    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)
    {
        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(orderItemsForInsert.size() > 0)
        {
            insert orderItemsForInsert;
        }
    }


}

Please mark as Best Answer if above information was helpful.

Thanks,