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
BCDBSABCDBSA 

Trigger to compare the same field value of the newest record and the previous record within the same parent record

Hi all,

Let's say we have a parent sObject called ParentObj with a QuoteNumber custom field, and a child sObject called ChildObj. There are two custom fields in ChildObj, Product and Price. 

Within the same record of ParentObj, the ChildObj is a related list in ParentObj record page. When a new record of ChildObj is created in the same parent record, we would like to compare the price value of the previous record with the same product name. If the price is different, then I would receive an email alert.
--------------------
ParentObj:
ParentID: P00000012
QuoteNumber: QN0001
--------------------
ChildObj:
RecordId         Product            Price
  001                Item1                100
  002                Item1                100
  003                Item2                 60
  004                Item1                 200  
----------------
As shown above, I should receive an email alert when a child record 004 is created. Any ideas? I would really appreciate if sample code for this issue is provided or urls to similar Apex trigger. 

Thank you.
William TranWilliam Tran
Have you explored with Workflow/Process Builder to do this?

I believe there's a good chance you may be able to do it without coding.

Thx
BCDBSABCDBSA
@William

I have tried. And I also asked salesforce support. They say it is impossible to use Workflow to achieve that.

Thank you for your answer anyway. 
William TranWilliam Tran
I am pretty sure you can do it with process builder. 

But if you don't want to go that route than you definitely should be able to do with trigger.

Why don't you start something and post it , I will review and fix it for you. 

Be sure to put it in the real object names with real field names and everything.

Thx
BCDBSABCDBSA
@ William

I have tried the workflow for more than 2 days, but none of the method works, and that's the reason I asked Salesforce support. Writing a trigger is time consuming. As a user who has never written a trigger before, I would have not to write a trigger if it is not necessary.

The workflow doesn't work when you
1. create an empty field in the parent object and update whenever a new record with different price is created. What if the newest record is not the same item as the previous record?
2. create an empty field in the child object and update the field when a new record with different price is created. (for the same reason)

And most importantly, how do you extract the previous record value? Using the formula? I have talked to 3 Salesforce supports, and they said they were not able to do that, only trigger helps.

If you have some good ideas, please let me know.