[SalesForce] Delaying Trigger until all related records are inserted

I'm working on an app that integrates with an external web service, so saving a record in SF will fire an insert trigger that sends the new record data to the web service.

We're working with 3 custom objects:

Invoice (main object) – required
——— Line (child of Invoice) – required
————— Revenue Entry (child of Line) – optional

The trigger is connected to the Invoice object.

Since we're using JS remoting for the insert, the trigger ends up firing before the related records are inserted, leading to an incorrect or failed API request.

Is there a way to delay the trigger from firing until all related records are inserted?

As I write this question, one workaround that comes to mind is to create another object whose record is inserted only after all the required records are in. This object can capture the main record's id which can be used to query all the data.

Are there any other (hopefully more elegant) ways around this problem?

Best Answer

Create a web service method, and have your client code call that method. Use a static variable to keep your trigger from firing when using this web service.

global class WebServices {
    static webservice String createInvoice(InvoiceData data) {
        String result;
        try {
            executeTrigger = false;
            // Insert Invoice
            // Insert Line Item
            // Insert Revenue
        } catch(exception e) {
            result = 'failed: '+e.getMessage();
        }
        return result; // 
    }

    global class InvoiceData {
        // describe invoice data
    }

    global static boolean executeTrigger = true; // for non-ws updates
}

Edit: You could also use REST instead of SOAP; the end result is the same.

Related Topic