You need to sign in to do that
Don't have an account?
Csaba Czimer
Trigger question - newbie
Hi All,
I have a question regarding the trigger below. I would like to update the price of a new order when created, ideally from a relationship field.
In the below code, first, I tried to set the price to 10. If I use the below code, I don't receive an error, however when creating a new order, the price is filled with zero.
However if I don't use the below SOQL query, just write the "for" cycle for the "neworder" list, then it fills the price as expected.
I would like to use the relationship price, though, for which I suspect I need the SOQL query.
Could someone help how to achieve this?
Thanks,
Csaba
trigger setPrice on Order__c (before insert) {
Order__c[] neworder = Trigger.new;
WHERE Order__c.Id IN :neworder]) {
ord.Unit_Price__c = 10;
}
}
I have a question regarding the trigger below. I would like to update the price of a new order when created, ideally from a relationship field.
In the below code, first, I tried to set the price to 10. If I use the below code, I don't receive an error, however when creating a new order, the price is filled with zero.
However if I don't use the below SOQL query, just write the "for" cycle for the "neworder" list, then it fills the price as expected.
I would like to use the relationship price, though, for which I suspect I need the SOQL query.
Could someone help how to achieve this?
Thanks,
Csaba
trigger setPrice on Order__c (before insert) {
Order__c[] neworder = Trigger.new;
for (Order__c ord :[SELECT Order__c.Name, Order__c.Unit_Price__c, Order__c.Product_Name__r.Name , Order__c.Product_Name__r.Unit_Price__c
FROM Order__cWHERE Order__c.Id IN :neworder]) {
ord.Unit_Price__c = 10;
}
}
You need to use a map to first get all product unit price and then popuate. In this case, it's a before insert.
Added below sample code for guidelines:
All Answers
The issue is you are using a 'before insert' event.
In Before insert, you won't get an ID, since the record is not actually commited to the database.
I am not sure on what relationship you need to update the price, but if you are trying to access a seperate object, use 'áfter insert' and it will start working.
Note: For reference: Trigger order of execution (https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_order_of_execution.htm)
Product_Name__c is the master-detail relationship field in Order__c to Product__c object, and I need to update the order's Unit_Price__c field based on the Unit_Price__c field of the Product__c object.
You need to use a map to first get all product unit price and then popuate. In this case, it's a before insert.
Added below sample code for guidelines:
I have made some minor corrections in the above code, and now it works as expected!
Many thanks,
Csaba