Skip to content

Instantly share code, notes, and snippets.

@nithesh1992
Created February 22, 2017 14:59
Show Gist options
  • Save nithesh1992/fa697e9b309566e7ab922464a48fa764 to your computer and use it in GitHub Desktop.
Save nithesh1992/fa697e9b309566e7ab922464a48fa764 to your computer and use it in GitHub Desktop.
Whenever order is created,This needs to copy related opportunity line items to order line items.
/**
* TriggerName : copyOppLineItems
* @description : Whenever order is created,
* This needs to copy related opportunity line items to order line items.
*/
trigger copyOppLineItems on Order (after insert) {
List<OrderItem> orderItemList = new List<OrderItem>();
List<Order> orderList = [SELECT Id, OpportunityId, EffectiveDate, EndDate, IsDeleted,
IsReductionOrder, Name, OrderNumber, OrderReferenceNumber,
OriginalOrderId,TotalAmount FROM Order WHERE Id IN :Trigger.New];
System.debug(orderList); // first step, Getting all new order(s) from trigger.new
if(orderList.size() > 0){
List<Id> oppIds = copyOppItemHelper.getOppIds(orderList); // Second step, get opportunityId(s) from all those order(s).
System.debug(oppIds);
if(oppIds.size() > 0) {
List<OpportunityLineItem> oppItemList = copyOppItemHelper.getOppItemList(oppIds);
// Third step, Get related Opportunity Item Lists from all those Opportunity(s).
System.debug(oppItemList);
if(oppItemList.size() > 0) {
orderItemList = copyOppItemHelper.getOrderItemList(orderList, oppItemList);
// fourth step, opportunity list items to new order items that match the Criteria.
System.debug(orderItemList);
}
else{
System.debug('There are zero number of Opportunity Line Items That matches the Criteria');
}
}
else{
System.debug('No opportunities are associted with the new Orders');
}
}
else {
System.debug('Order List is Empty - No New Orders');
}
if(orderItemList.size() > 0) {
//Finally, Save the records in to database, and log the errors.
Database.SaveResult[] srList = Database.insert(orderItemList, false);
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// fetching the ids of successful records
System.debug('Successfully Copied Opportunity Line Item, ID: ' + sr.getId());
}
else
{
// This is for failed records
for(Database.Error err : sr.getErrors()) {
System.debug('Error --> '); //Printing error message in Debug log
System.debug(err.getStatusCode() + ': ' + err.getMessage());
}
}
}
}
else {
System.debug('No Items to Copy from Opportunity Line Items');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment