Salesforce Apex Trigger "isAPI" Context Variable
Asked Answered
L

3

6

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)

Lumenhour answered 19/9, 2012 at 13:34 Comment(2)
I think that there is no way to know that >> success.salesforce.com/ideaView?id=08730000000BpsCAASHyland
@MartinBorthiry thanks, I just "promoted" it, hopefully this will be available in the futureLumenhour
U
4

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;
    }
}
Unchristian answered 19/9, 2012 at 14:18 Comment(1)
this is the same situation few years lates?Plerre
P
3

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.

Producer answered 7/8, 2020 at 20:36 Comment(0)
N
0

When an API call is made in salesforce, it usually has the format similar to https://mydomain.my.salesforce.com/services/data/v58.0/sobjects/Account

/service/ is always present in API calls. If you check the URL for this pattern you can always be sure the request came from an API call.

trigger Update_Last_Modified_By_API on My_Object__c (before update) {
        String currentRequestUrl = System.URL.getCurrentRequestUrl().toExternalForm();

        if (currentRequestUrl != null && currentRequestUrl.contains('/services/')) {
            // The change was triggered via the API.

            /* Code Here */
        } else {
            // The change was triggered via the UI.

            /* Code Here */
        }   
}
Nabal answered 21/7, 2023 at 11:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.