I have the following configuration:
I have a trigger in which I am trying to add an Inventory record when a treatment gets created. This inventory record requires an order ID as it has a master detail relationship to order. This treatment record has a lookup to the Visit Object which in turn has a lookup to a Work Order object which in turn has a lookup to the Order object. The inventory record itself is not directly related to the treatment record that is creating it - it is only by the order id. In simple form.
Inventory - child (what I am trying to insert via the trigger) Treatments - parent Visits - grand parent Work Order - great grand parent Orders - great great grand parent (Order ID from inventory comes from here)
Essentially I have a simple trigger as follows, ran on after insert via a trigger handler. It executes when i expect:
Apex code
public class TreatmentsActions {
public static void createTreatmentInventory(List<Treatments__c> NewTreatments){
List<Inventory__c> InventoryToCreate = new list<Inventory__c>{};
for(Treatments__c t: NewTreatments) {
InventoryToCreate.add(new Inventory__c( Product_InventoryLookup__c = t.product_treatmentlookup__c,
Quantity__c = t.Quantity__c * -1, Order__c = t.Visit__r.Work_Order__r.Order__r.Id ));
}
try {
insert InventoryToCreate;
}
catch(DMLException e){
System.debug('--------------Exception in createTreatmentInventory');
System.debug('Exception occurred '+String.valueOf(e));
}
}
}
As you probably expect the t.Visit__r.Work_Order__r.Order__r.Id
and
t.product_treatmentlookup__c
are null. The record is not inserted.
I currently "think" it is down to context, the treatment record has id values for the visit and product fields but if I try and use system.debug to access the related fields (visits__r.work_order__r.order__r.id etc) I just receive nulls.
Edit: if I run the following SOQL "select visit__r.work_order__r.order__r.id FROM Treatments__c" it returns [object object] which maybe a console bug!?
Edit: I have actually been able to make a really simple Flow in the Process Builder that worked 2nd time. I'd still like to know where I went wrong above but interesting how easy it was in the process builder :(