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
nothingisreal68nothingisreal68 

Matching Line Items on Insert

Hi Community,

 

I have a trigger that needs to match line items of the same custom object type and populate lookups to one another. The logic to find these matching items is straight forward, but I am wondering if I am overlooking the best way to actually populate the lookups.

 

The problem arises when one or both of the line items are being inserted (vs. updated), and therefore do not have access to a salesforce ID to use to populate the lookups in the context of the before trigger. These line items do have external Ids.

 

I tried populating the external ids in a reference to the other record in the trigger, and this seems to work when an actual insert DML statement is made in apex code - but does not work when used in the trigger (without a DML call). Example:

 

Line_Item__c first = new Line_Item__c();

Line_Item__c second = new Line_Item__c(External_ID__c = 'externalId2');

first.Line_Item__r = second;

 

This seemingly does not work in a trigger.

 

My thought now is to use an @future method. When the items are matched in the trigger, it will pass the two external id's of the line items to the @future method which will query the database for the correct ids and populate the lookups, and finally update the line items. 

 

Is there a better way to do this? Any help is appreciated. 

h8r41dh8r41d

You have to save the first record before you can set up the relationship to the second, which is why I see you have this problem in the trigger.

 

You would have to have a field to specify the level of the line item. If you create a new item and call it level 1, you can use an after insert trigger to create the second level based on values in the first level, then in the trigger you'd also have to make sure it's only running if you saved a first level record so you don't go into an infinite loop when you save the second level.

 

If I had some further information about what your relationships are based on, I could give you a more detailed answer.

 

Gabriel Alack
Contact Us - We Can Help!
Salesforce Superheroes
------------------------------
help@salesforcesuperheroes.com
www.salesforcesuperheroes.com
1-888-407-9578 x122