[SalesForce] Roll-up Summary FIeld is not calculated on after insert trigger

I have a custom object that has a master-detail relationship with another object, which has a master-detail relationship with another object. To simplify, consider them as: order, order item and receipt note.

Every time an item arrives, a "receipt" record is created, which specifies the amount of items that arrived. So if an order has 10 units of 1 item, it is possible to receive 10 or less at once.

On the order item I have a field called "received amount" which sums the "quantity" field from related receipts. So I know, for example, when X out of Y items arrived. I have a similar relationship with the item and the parent, that shows how many items were totally delivered.

The problem is that on the grand-children record (receipt) I have a trigger running on after insert which is supposed to check on the parent (order) if all the items were received (AmountOfItems == DeliveredItems), but the parent record, when queried on the trigger, doesn't display the updated value on the DeliveredItems roll-up field when the trigger code is running.

After the trigger runs, right before my test method exists, I query the parent again to check the fields, and I can see the value updated.

My guess is that this is either a bug, or the fields are calculated only after all the trigger context is run by the platform (which includes the after insert event). Am I right? How can I get around this?

Best Answer

According to Trigger order or execution.

  • Execute after trigger
  • If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.
  • If the parent record is updated, and a grandparent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the grandparent record. Grandparent record goes through save procedure
  • Commits all DML operations to the database

Now, during after insert of grand children (receipt) record, you are querying the parent record's rollup summary field, that moment record is not committed to database.

After transaction is committed then only then you will see the updated rollup value of the Parent.

Related Topic