Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Salesforce Apex Trigger "isAPI" Context Variable

Is there a way to determine if a trigger is being executed by an API call or through the Salesforce Web Interface?

I'd like to do something like this:

trigger Update_Last_Modified_By_API on My_Object__c (before update) {

    for (My_Object__c o : Trigger.New) {

        if (isAPI) {
            o.Last_Modified_By_API__c = datetime.now();
        }

    }

}

(Currently using API version 25.0, though will soon be updating to 26.0)

like image 532
Greg Avatar asked Sep 19 '12 13:09

Greg


2 Answers

There is currently no standard way to tell within the trigger what actually caused an update or insert to happen (API, standard page layout, VF page & controller, some other Apex code, etc.). Here's a full list of Trigger Context Variables.

To achieve this, I would suggest creating a custom checkbox field on the object, something like IsAPI__c (with a default value of false). Then all you would need to do is pass in true for that field with any API call, and then check the field in your trigger for each record in the batch (just make sure you remember to reset it to false when you're done so subsequent calls from the UI aren't treated as API calls).

trigger Update_Last_Modified_By_API on My_Object__c (before update) {
    for ( My_Object__c o : Trigger.New ) {
        if ( o.IsAPI__c ) {
            o.Last_Modified_By_API__c = datetime.now();
        }
        o.IsAPI__c = false;
    }
}
like image 123
JCD Avatar answered Sep 30 '22 19:09

JCD


If you're just trying to determine whether a transaction was initiated via the UI or not, using the System.URL.getCurrentRequestUrl() method might give you an indication.

like image 32
Jesper Bjerrum Avatar answered Sep 30 '22 18:09

Jesper Bjerrum