I have a requirement of creating Service Contracts when Order is Approved and add Order Products inside to Contract Line Items in Service Contract. Following is the code I am using to accomplish what I need.
public class GenerateServiceContract {
@InvocableMethod
public static void fetchOrderItems(List<Id> orderId) {
List<Order> relatedOrder = [SELECT Id, AccountId, Order_Name__c FROM Order WHERE Id = :orderId];
ServiceContract scontract = new ServiceContract(
Order__c = relatedOrder[0].Id,
Name = relatedOrder[0].Order_Name__c,
AccountId = relatedOrder[0].AccountId
);
try {
insert scontract;
List<OrderItem> oproduct = [SELECT Id, Product2Id, Quantity, Contact_Name__c, UnitPrice FROM OrderItem WHERE OrderId = :orderId];
List<ContractLineItem> citemsToInsert = new List<ContractLineItem>();
for (OrderItem oitem: oproduct) {
citemsToInsert.add(new ContractLineItem(
ServiceContractId = scontract.Id,
Product2Id = oitem.Product2Id,
Quantity = oitem.Quantity,
UnitPrice = oitem.UnitPrice
));
}
insert citemsToInsert;
} catch (Exception e) {}
}
}
I am getting this Error "Field is not writeable: ContractLineItem.Product2Id"
Can anyone help me with this? as I found nothing to make Product2Id field writeable.