0

I'm trying to create a before insert trigger that will prevent creating an order task if the order item has a checkbox not marked. If it is checked then let the task get created. It throws the error when the checkbox is checked or not checked.

Not sure what I'm missing.

 trigger PreventOrderTaskCreationonOrderItem on Order_Task__c(before insert) {
    for (order_Task__c o: trigger.new) {
        System.debug(o.Order_Phase__r.Order__Item__r.Order_Project__c);

        If(o.Order_Phase__r.Order__Item__r.Order_Project__c == FALSE) {
            o.addError('You cannot add an order project category to this item.');
        }
        Else {}

    }
}
1
  • 2
    Jellybea, it helps a LOT if you include the type of error and where it happens (debug logs, line nr). Sep 25 '14 at 15:00
2

I'm going to guess you're receiving a System.NullPointerReference exception because you're trying to access fields which are not available to the trigger.

o.Order_Phase__r.Order__Item__r.Order_Project__c

This information isn't available unless you get it from the database.

  • you can loop through all your Order_Task__c records and store their Order_Phase__c fields in a set.
  • you can query the Order_Phase__c object for all the ID's in the above set, including the Order__Item__r.Order_Project__c field, and store the results in a map
  • iterating your order_Task__C records again you can now fetch the necesairy boolean field from the map through the Order_Phase__c field and execute your logic.
2

The relationship fields are not populated in triggers. You are most likely getting a "Null Pointer Exception" when executing the code: o.Order_Phase__r.Order__Item__r.Order_Project__c. This is because o.Order_Phase__r is null, hence the NPE

If you need to reference other objects in a trigger you will need to do a SOQL query to get the results. See the example below, which is completely untested but hopefully will give you the idea of what you need to do.

trigger PreventOrderTaskCreationonOrderItem on Order_Task__c (before insert) {

    List<Id> orderPhaseIds = new List<Id>();
    for (order_Task__c o: trigger.new){
        orderPhaseIds.add(o.Order_Phase__c);
    }
    Map<Id, Order_Phase__c> opMap = Map<Id, Order_Phase__c>();
    if (orderPhaseIds.size() > 0) {
        for (Order_Phase__c op : [select Order__Item__r.Order_Project__c from Order_Phase__c where Id in:orderPhaseIds]) {
            opMap.put(op.Id, op);
        }
    }
    for (order_Task__c o: trigger.new){
        Order_Phase__c op = opMap.get(o.Order_Phase__c);
        if(op != null && op.Order__Item__r.Order_Project__c == FALSE) {
            o.addError('You cannot add an order project category to this item.');
        }
    }
} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy