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
Guru Vemuru 1Guru Vemuru 1 

Trigger on purchase order?

Hi,

1. I Have Indent__c and Indent_Line_Item_c Objects which are in master detail relationship.
2. Similarly Purchase_Order__c and Order_Line_Item__c which are in master detail relationship.
3.Indent and Purchase oreder having look up relation.
4. Now i want to achive when ever user clicks on  create purchase order check box  in indent then a purchase order has to generate.(Copy of    indent) --- It is Achived Through Process builder.
5.Now when ever purchase order created then purchase order line item should create and it fetch data from Indent line item.
6. I Written one trigger but is not working properly.
    Here is My Code:

trigger createPurchaseOrderDetails on Purchase_Order__c (after insert,after update)
 {

Purchase_Order__c ord=trigger.new[0];
Indent__c oppId=[select id from Indent__c where id=:ord.Indent__c];
List<Indent_line_item__c> opplines=[select id, Quantity__c,Product__c
from Indent_line_item__c where Id=:oppId.id];

        for(Indent_line_item__c oppline:opplines){
        
        Order_Line_item__c OrderLine = new Order_Line_item__c();
        OrderLine.Product__c = oppline.Product__c;
        OrderLine.Quandity__c = oppline.Quantity__c;
        OrderLine.Unit_Price__c = oppline.Unit_Price__c;
        OrderLine.Total_Price__c = oppline.Total_Price__c;
        insert OrderLine;
    }

}

 
Best Answer chosen by Guru Vemuru 1
Abhishek BansalAbhishek Bansal
Hi,

I have missed one where condition in the code. Please find the updated code below:
trigger createPurchaseOrderDetails on Purchase_Order__c (after insert){
	Set<Id> setOfIndentIds = new Set<Id>();
	
	for(Purchase_Order__c purchaseOrder : trigger.new){
		if(purchaseOrder.Indent__c != null){
			setOfIndentIds.add(purchaseOrder.Indent__c);
		}
	}
	
	Map<Id,Indent__c> mapOfIndents = new Map<Id,Indent__c>([Select id,(select id, Quantity__c,Product__c from Indent_line_items__r) from Indent__c where ID IN :setOfIndentIds]);
	
	List<Order_Line_item__c> listOfOrderLineItemsToInsert = new List<Order_Line_item__c>();
	
	for(Purchase_Order__c purchaseOrder : trigger.new){
		if(purchaseOrder.Indent__c != null && mapOfIndents.containsKey(purchaseOrder.Indent__c)){
			for(Indent_line_item__c  indentLineItem : mapOfIndents.get(purchaseOrder.Indent__c).Indent_line_items__r){
				Order_Line_item__c orderLineItem = new Order_Line_item__c();
				orderLineItem.Product__c = indentLineItem.Product__c;
				orderLineItem.Quandity__c = indentLineItem.Quantity__c;
				
				listOfOrderLineItemsToInsert.add(orderLineItem);
			}
		}
	}
	
	if(listOfOrderLineItemsToInsert.size() > 0){
		insert listOfOrderLineItemsToInsert;
	}
}
//Replace the field names with the original API name
//Replace Indent_line_items__r with the child relationship name as mentioned in the Indent lookup field on the Indent Line Item object

Please let me know if you still face any issue.

Thanks,
Abhishek Bansal.

All Answers

Abhishek BansalAbhishek Bansal
Hi ,

Since you mentioned that whenever Purchase Order is created you need to insert Purchse Order Line Items on the basis of Indent LIne Items so your trigger should only run on the after insert. Your trigger code will look like something as below:
trigger createPurchaseOrderDetails on Purchase_Order__c (after insert){
	Set<Id> setOfIndentIds = new Set<Id>();
	
	for(Purchase_Order__c purchaseOrder : trigger.new){
		if(purchaseOrder.Indent__c != null){
			setOfIndentIds.add(purchaseOrder.Indent__c);
		}
	}
	
	Map<Id,Indent__c> mapOfIndents = new Map<Id,Indent__c>([Select id,(select id, Quantity__c,Product__c from Indent_line_items__r) from Indent__c]);
	
	List<Order_Line_item__c> listOfOrderLineItemsToInsert = new List<Order_Line_item__c>();
	
	for(Purchase_Order__c purchaseOrder : trigger.new){
		if(purchaseOrder.Indent__c != null && mapOfIndents.containsKey(purchaseOrder.Indent__c)){
			for(Indent_line_item__c  indentLineItem : mapOfIndents.get(purchaseOrder.Indent__c).Indent_line_items__r){
				Order_Line_item__c orderLineItem = new Order_Line_item__c();
				orderLineItem.Product__c = indentLineItem.Product__c;
				orderLineItem.Quandity__c = indentLineItem.Quantity__c;
				orderLineItem.Unit_Price__c = indentLineItem.Unit_Price__c;
				orderLineItem.Total_Price__c = indentLineItem.Total_Price__c;
				
				listOfOrderLineItemsToInsert.add(orderLineItem);
			}
		}
	}
	
	if(listOfOrderLineItemsToInsert.size() > 0){
		insert listOfOrderLineItemsToInsert;
	}
}
//Replace the field names with the original API name
//Replace Indent_line_items__r with the child relationship name as mentioned in the Indent lookup field on the Indent Line Item object

Please let me know if you face any issue with the above code or if you need any further information on this.

Thanks,
Abhishek Bansal.
Guru Vemuru 1Guru Vemuru 1
Thank you Abhishek,

It Giving Error Like
Error: Compile Error: Field is not writeable: Order_Line_item__c.Unit_Price__c at line 20 column 30
Abhishek BansalAbhishek Bansal

Hi Arpit,

Just want to let you know that triggers always run in a system context so the User Permissions will not be an issue here. 

@Guru : Please check data type of the field and if it is a formula field then please remove it from the trigger since we cannot write values in a formula field.

Thanks,
Abhishek Bansal.

Guru Vemuru 1Guru Vemuru 1
Hi Abhishek,
You are correct. Unit Price and total price are formula fields. Now code saved but Order line Item Not Created when ever Purchase order created.
Abhishek BansalAbhishek Bansal
Hi,

I have missed one where condition in the code. Please find the updated code below:
trigger createPurchaseOrderDetails on Purchase_Order__c (after insert){
	Set<Id> setOfIndentIds = new Set<Id>();
	
	for(Purchase_Order__c purchaseOrder : trigger.new){
		if(purchaseOrder.Indent__c != null){
			setOfIndentIds.add(purchaseOrder.Indent__c);
		}
	}
	
	Map<Id,Indent__c> mapOfIndents = new Map<Id,Indent__c>([Select id,(select id, Quantity__c,Product__c from Indent_line_items__r) from Indent__c where ID IN :setOfIndentIds]);
	
	List<Order_Line_item__c> listOfOrderLineItemsToInsert = new List<Order_Line_item__c>();
	
	for(Purchase_Order__c purchaseOrder : trigger.new){
		if(purchaseOrder.Indent__c != null && mapOfIndents.containsKey(purchaseOrder.Indent__c)){
			for(Indent_line_item__c  indentLineItem : mapOfIndents.get(purchaseOrder.Indent__c).Indent_line_items__r){
				Order_Line_item__c orderLineItem = new Order_Line_item__c();
				orderLineItem.Product__c = indentLineItem.Product__c;
				orderLineItem.Quandity__c = indentLineItem.Quantity__c;
				
				listOfOrderLineItemsToInsert.add(orderLineItem);
			}
		}
	}
	
	if(listOfOrderLineItemsToInsert.size() > 0){
		insert listOfOrderLineItemsToInsert;
	}
}
//Replace the field names with the original API name
//Replace Indent_line_items__r with the child relationship name as mentioned in the Indent lookup field on the Indent Line Item object

Please let me know if you still face any issue.

Thanks,
Abhishek Bansal.
This was selected as the best answer
Guru Vemuru 1Guru Vemuru 1
Hi AbhiShek,

I Updated That code. Still Order Line Item not Created.
Purchase Order created (Through Process Builder). But not Line Items.
Abhishek BansalAbhishek Bansal

Hi,

You mentioned that Purchase Order and PO Line items have Master-Detail relationshiop. Have you populated the value in the Purchse Order lookup field present on the PO Line Item object. If it is a master-detail then it must be a required field, Please verify this. Everything else looks fine to me.

Thanks,
Abhishek Bansal.

Guru Vemuru 1Guru Vemuru 1
Hi ,
I am Giving you snap shots also
Indent:

User-added image

Indent Line Item:


User-added image

Purchase Order:


User-added image
Abhishek BansalAbhishek Bansal
Hi,

There must be a lookup field "Purchase Order" on the PO Line Item object. Have you set the value in this field in the trigger. Only after setting the value in that field the PO Line Items will come under the Purchase Order.

You should add one ,ore line in trigger as : orderLineItem.Purchase_Order__c = ipurchaseOrder.id;

Let me know if this works for you.

Thanks,
Abhishek Bansal.
Guru Vemuru 1Guru Vemuru 1
Hi,

Not workig Abhishek,
It giving same error:

The record couldn’t be saved because it failed to trigger a flow. A flow trigger failed to execute the flow with version ID 3015C000000HEAx. Flow error messages: <b>An unhandled fault has occurred in this flow</b><br>An unhandled fault has occurred while processing the flow. Please contact your system administrator for more information. Contact your administrator for help.
Abhishek BansalAbhishek Bansal
Hi,

You did not mention about any error in your previous chatters so this is soemthing new which might be relatd to the Flows that have been setup in your org. Please take help about this error from the link given below:
https://help.salesforce.com/articleView?id=000239860&type=1 (http://​https://help.salesforce.com/articleView?id=000239860&type=1)

If you have any urgency on this then please contact me on Gmail or Skype.
Gmail: abhibansal2790@gmail.com
Skype: abhishek.bansal2790

Thanks,
Abhishek Bansal.
Guru Vemuru 1Guru Vemuru 1
Hi Abhishek,
Thankyou for all your help and support,
After updating trigger with other new lines of code. Now it showing error.(When Trigger is in active mode only)
Any how you helped me so much.
I achived same funtionality between Standard objects ie. (Quote and Order).
This is the code and it is working perfectly.

trigger insertdataorditem on Order (after insert) {
    
    Map<ID,ID> data = new Map<ID,ID>();
    for(Order allorder : Trigger.new)
    {
       data.put(allorder.Quote__c,allorder.Id);        
    }
    
    
    List<QuoteLineItem> Qitm = [select Product2Id,Quantity,QuoteId,UnitPrice,TotalPrice,Tax__c,PricebookEntryId,Discount,Amount_After_Tax__c,Amount_Before_Tax__c  from QuoteLineItem where QuoteId In :data.keyset()];
    for(QuoteLineItem eachQL : Qitm)
    {
        OrderItem orditm = new OrderItem ();
        orditm.Quantity =  eachQL.Quantity;  
        orditm.UnitPrice =  eachQL.UnitPrice;
        orditm.PricebookEntryId = eachQL.PricebookEntryId;
        orditm.OrderId = data.get(eachQL.QuoteId);
        orditm.Tax__c=eachQL.Tax__c;
        orditm.Discount__c=eachQL.Discount;
        
        
        orditm.Amount_Before_Tax__c= eachQL.Amount_Before_Tax__c;
        orditm.Amount_After_Tax__c=eachQL.Amount_After_Tax__c;
        
        insert orditm;
    }
}