How can I know if it's the last execution of an After Trigger?












2















Imagine one object with 20 fields, field1 to field20. Some of these fields I have Process Builder in place, some of them I have Worflow Updates, and some of them are 'bare field' (i.e. PB and WF does not touch it).



My problem is that, depending on the operation that the record performs, these tools (PB and WF) are fired or not, and it implies in how many times the After Trigger is fired.




  • If the operation performed is 'clean' (i.e. it will not fire WF or PB), the After Trigger fires only once.


  • If the operation causes a WF to fire, the After Trigger fires twice.


  • If the operation causes a WF and PB to fire, the After Trigger fires three times.



I need to execute certain things only on the last time that the After Trigger fires.



Is it possible to isolate it without getting rid of the current PB and WF implementation?










share|improve this question























  • Possible duplicate: Execute some code after all trigger batches complete?

    – Adrian Larson
    1 hour ago
















2















Imagine one object with 20 fields, field1 to field20. Some of these fields I have Process Builder in place, some of them I have Worflow Updates, and some of them are 'bare field' (i.e. PB and WF does not touch it).



My problem is that, depending on the operation that the record performs, these tools (PB and WF) are fired or not, and it implies in how many times the After Trigger is fired.




  • If the operation performed is 'clean' (i.e. it will not fire WF or PB), the After Trigger fires only once.


  • If the operation causes a WF to fire, the After Trigger fires twice.


  • If the operation causes a WF and PB to fire, the After Trigger fires three times.



I need to execute certain things only on the last time that the After Trigger fires.



Is it possible to isolate it without getting rid of the current PB and WF implementation?










share|improve this question























  • Possible duplicate: Execute some code after all trigger batches complete?

    – Adrian Larson
    1 hour ago














2












2








2








Imagine one object with 20 fields, field1 to field20. Some of these fields I have Process Builder in place, some of them I have Worflow Updates, and some of them are 'bare field' (i.e. PB and WF does not touch it).



My problem is that, depending on the operation that the record performs, these tools (PB and WF) are fired or not, and it implies in how many times the After Trigger is fired.




  • If the operation performed is 'clean' (i.e. it will not fire WF or PB), the After Trigger fires only once.


  • If the operation causes a WF to fire, the After Trigger fires twice.


  • If the operation causes a WF and PB to fire, the After Trigger fires three times.



I need to execute certain things only on the last time that the After Trigger fires.



Is it possible to isolate it without getting rid of the current PB and WF implementation?










share|improve this question














Imagine one object with 20 fields, field1 to field20. Some of these fields I have Process Builder in place, some of them I have Worflow Updates, and some of them are 'bare field' (i.e. PB and WF does not touch it).



My problem is that, depending on the operation that the record performs, these tools (PB and WF) are fired or not, and it implies in how many times the After Trigger is fired.




  • If the operation performed is 'clean' (i.e. it will not fire WF or PB), the After Trigger fires only once.


  • If the operation causes a WF to fire, the After Trigger fires twice.


  • If the operation causes a WF and PB to fire, the After Trigger fires three times.



I need to execute certain things only on the last time that the After Trigger fires.



Is it possible to isolate it without getting rid of the current PB and WF implementation?







trigger workflow process-builder after-trigger






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 6 hours ago









Leandro Ferreira FernandesLeandro Ferreira Fernandes

875




875













  • Possible duplicate: Execute some code after all trigger batches complete?

    – Adrian Larson
    1 hour ago



















  • Possible duplicate: Execute some code after all trigger batches complete?

    – Adrian Larson
    1 hour ago

















Possible duplicate: Execute some code after all trigger batches complete?

– Adrian Larson
1 hour ago





Possible duplicate: Execute some code after all trigger batches complete?

– Adrian Larson
1 hour ago










3 Answers
3






active

oldest

votes


















5














AFAIK there is no way to do this without adding explicit logic. And that explicit logic is pretty ugly e.g. make the WF and PB set database data or static variables that signal they have run and then have the trigger check those. Which couples the pieces together horribly.



If possible, write the trigger so it is idempotent i.e. nothing bad happens even if it does run multiple times, so the problem goes away.






share|improve this answer

































    4














    Conceivably what you could do is set up a Queueable class. On the first pass through the trigger, instantiate and enqueue it, and then save that in a static variable so you know it's already been created. It will run once after all executions are done, in a separate transaction.



    The trouble is, once you have enqueued it, you can no longer alter any data you've passed into that instance. But if you need to alter such data, what you could do is either a) store the extra data it needs to pick up somewhere in the database, indexed to the job ID retrieved when it was enqueued, or b) cancel the job (delete the AsyncApexJob) and enqueue it again with the new data added to it.



    Downside of b) is that each time you enqueue it counts against the limit of how many jobs can be enqueued in one transaction, even if you later dequeue it.






    share|improve this answer































      3














      It sounds like you are looking for an exit event. If doesn't exist yet, but you can vote for the idea, the description of which is pasted below:




      Since triggers only handle 200 records at a time, it would be convenient if we could schedule some code that runs in the same transaction as the current transaction, but after all other triggers, recursion, etc has executed. The registration function could be called repeatedly, but would only execute once at the end of the transaction. Here's some code that demonstrates this interface:



      public class MyAfterEverythingElseHandler implements System.AtExitHandler {
      public void atExit() {
      // Perform some cleanup. For example, perform one last DML, send emails regarding the transaction, etc.
      }
      }


      The class only triggers if called at least once through System.atExit, such as:



      System.atExit(MyAfterEveryElseHandler.class);


      This is similar to the @future annotation, but doesn't spawn a new process, has access to the full static environment of the current transaction, and remains subject to the governor limits of the current transaction. Multiple handlers could be registered via this mechanism, but the calling order would be undefined.



      Typical uses might be to aggregate together a @future call on many thousands of records at once, debug logging, aggregate email sends across triggers, etc. Ideally, this interface should restrict DML operations, perhaps calling a "plain" commit for any records modified during the handler (e.g. no triggers, workflow rules, etc), or disabled completely, but could still call @future methods, System.executeBatch, System.scheduleBatch, and System.schedule.







      share|improve this answer























        Your Answer








        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "459"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: false,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: null,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f246315%2fhow-can-i-know-if-its-the-last-execution-of-an-after-trigger%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        5














        AFAIK there is no way to do this without adding explicit logic. And that explicit logic is pretty ugly e.g. make the WF and PB set database data or static variables that signal they have run and then have the trigger check those. Which couples the pieces together horribly.



        If possible, write the trigger so it is idempotent i.e. nothing bad happens even if it does run multiple times, so the problem goes away.






        share|improve this answer






























          5














          AFAIK there is no way to do this without adding explicit logic. And that explicit logic is pretty ugly e.g. make the WF and PB set database data or static variables that signal they have run and then have the trigger check those. Which couples the pieces together horribly.



          If possible, write the trigger so it is idempotent i.e. nothing bad happens even if it does run multiple times, so the problem goes away.






          share|improve this answer




























            5












            5








            5







            AFAIK there is no way to do this without adding explicit logic. And that explicit logic is pretty ugly e.g. make the WF and PB set database data or static variables that signal they have run and then have the trigger check those. Which couples the pieces together horribly.



            If possible, write the trigger so it is idempotent i.e. nothing bad happens even if it does run multiple times, so the problem goes away.






            share|improve this answer















            AFAIK there is no way to do this without adding explicit logic. And that explicit logic is pretty ugly e.g. make the WF and PB set database data or static variables that signal they have run and then have the trigger check those. Which couples the pieces together horribly.



            If possible, write the trigger so it is idempotent i.e. nothing bad happens even if it does run multiple times, so the problem goes away.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 3 hours ago

























            answered 4 hours ago









            Keith CKeith C

            94.7k1089204




            94.7k1089204

























                4














                Conceivably what you could do is set up a Queueable class. On the first pass through the trigger, instantiate and enqueue it, and then save that in a static variable so you know it's already been created. It will run once after all executions are done, in a separate transaction.



                The trouble is, once you have enqueued it, you can no longer alter any data you've passed into that instance. But if you need to alter such data, what you could do is either a) store the extra data it needs to pick up somewhere in the database, indexed to the job ID retrieved when it was enqueued, or b) cancel the job (delete the AsyncApexJob) and enqueue it again with the new data added to it.



                Downside of b) is that each time you enqueue it counts against the limit of how many jobs can be enqueued in one transaction, even if you later dequeue it.






                share|improve this answer




























                  4














                  Conceivably what you could do is set up a Queueable class. On the first pass through the trigger, instantiate and enqueue it, and then save that in a static variable so you know it's already been created. It will run once after all executions are done, in a separate transaction.



                  The trouble is, once you have enqueued it, you can no longer alter any data you've passed into that instance. But if you need to alter such data, what you could do is either a) store the extra data it needs to pick up somewhere in the database, indexed to the job ID retrieved when it was enqueued, or b) cancel the job (delete the AsyncApexJob) and enqueue it again with the new data added to it.



                  Downside of b) is that each time you enqueue it counts against the limit of how many jobs can be enqueued in one transaction, even if you later dequeue it.






                  share|improve this answer


























                    4












                    4








                    4







                    Conceivably what you could do is set up a Queueable class. On the first pass through the trigger, instantiate and enqueue it, and then save that in a static variable so you know it's already been created. It will run once after all executions are done, in a separate transaction.



                    The trouble is, once you have enqueued it, you can no longer alter any data you've passed into that instance. But if you need to alter such data, what you could do is either a) store the extra data it needs to pick up somewhere in the database, indexed to the job ID retrieved when it was enqueued, or b) cancel the job (delete the AsyncApexJob) and enqueue it again with the new data added to it.



                    Downside of b) is that each time you enqueue it counts against the limit of how many jobs can be enqueued in one transaction, even if you later dequeue it.






                    share|improve this answer













                    Conceivably what you could do is set up a Queueable class. On the first pass through the trigger, instantiate and enqueue it, and then save that in a static variable so you know it's already been created. It will run once after all executions are done, in a separate transaction.



                    The trouble is, once you have enqueued it, you can no longer alter any data you've passed into that instance. But if you need to alter such data, what you could do is either a) store the extra data it needs to pick up somewhere in the database, indexed to the job ID retrieved when it was enqueued, or b) cancel the job (delete the AsyncApexJob) and enqueue it again with the new data added to it.



                    Downside of b) is that each time you enqueue it counts against the limit of how many jobs can be enqueued in one transaction, even if you later dequeue it.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 2 hours ago









                    Charles TCharles T

                    6,2961822




                    6,2961822























                        3














                        It sounds like you are looking for an exit event. If doesn't exist yet, but you can vote for the idea, the description of which is pasted below:




                        Since triggers only handle 200 records at a time, it would be convenient if we could schedule some code that runs in the same transaction as the current transaction, but after all other triggers, recursion, etc has executed. The registration function could be called repeatedly, but would only execute once at the end of the transaction. Here's some code that demonstrates this interface:



                        public class MyAfterEverythingElseHandler implements System.AtExitHandler {
                        public void atExit() {
                        // Perform some cleanup. For example, perform one last DML, send emails regarding the transaction, etc.
                        }
                        }


                        The class only triggers if called at least once through System.atExit, such as:



                        System.atExit(MyAfterEveryElseHandler.class);


                        This is similar to the @future annotation, but doesn't spawn a new process, has access to the full static environment of the current transaction, and remains subject to the governor limits of the current transaction. Multiple handlers could be registered via this mechanism, but the calling order would be undefined.



                        Typical uses might be to aggregate together a @future call on many thousands of records at once, debug logging, aggregate email sends across triggers, etc. Ideally, this interface should restrict DML operations, perhaps calling a "plain" commit for any records modified during the handler (e.g. no triggers, workflow rules, etc), or disabled completely, but could still call @future methods, System.executeBatch, System.scheduleBatch, and System.schedule.







                        share|improve this answer




























                          3














                          It sounds like you are looking for an exit event. If doesn't exist yet, but you can vote for the idea, the description of which is pasted below:




                          Since triggers only handle 200 records at a time, it would be convenient if we could schedule some code that runs in the same transaction as the current transaction, but after all other triggers, recursion, etc has executed. The registration function could be called repeatedly, but would only execute once at the end of the transaction. Here's some code that demonstrates this interface:



                          public class MyAfterEverythingElseHandler implements System.AtExitHandler {
                          public void atExit() {
                          // Perform some cleanup. For example, perform one last DML, send emails regarding the transaction, etc.
                          }
                          }


                          The class only triggers if called at least once through System.atExit, such as:



                          System.atExit(MyAfterEveryElseHandler.class);


                          This is similar to the @future annotation, but doesn't spawn a new process, has access to the full static environment of the current transaction, and remains subject to the governor limits of the current transaction. Multiple handlers could be registered via this mechanism, but the calling order would be undefined.



                          Typical uses might be to aggregate together a @future call on many thousands of records at once, debug logging, aggregate email sends across triggers, etc. Ideally, this interface should restrict DML operations, perhaps calling a "plain" commit for any records modified during the handler (e.g. no triggers, workflow rules, etc), or disabled completely, but could still call @future methods, System.executeBatch, System.scheduleBatch, and System.schedule.







                          share|improve this answer


























                            3












                            3








                            3







                            It sounds like you are looking for an exit event. If doesn't exist yet, but you can vote for the idea, the description of which is pasted below:




                            Since triggers only handle 200 records at a time, it would be convenient if we could schedule some code that runs in the same transaction as the current transaction, but after all other triggers, recursion, etc has executed. The registration function could be called repeatedly, but would only execute once at the end of the transaction. Here's some code that demonstrates this interface:



                            public class MyAfterEverythingElseHandler implements System.AtExitHandler {
                            public void atExit() {
                            // Perform some cleanup. For example, perform one last DML, send emails regarding the transaction, etc.
                            }
                            }


                            The class only triggers if called at least once through System.atExit, such as:



                            System.atExit(MyAfterEveryElseHandler.class);


                            This is similar to the @future annotation, but doesn't spawn a new process, has access to the full static environment of the current transaction, and remains subject to the governor limits of the current transaction. Multiple handlers could be registered via this mechanism, but the calling order would be undefined.



                            Typical uses might be to aggregate together a @future call on many thousands of records at once, debug logging, aggregate email sends across triggers, etc. Ideally, this interface should restrict DML operations, perhaps calling a "plain" commit for any records modified during the handler (e.g. no triggers, workflow rules, etc), or disabled completely, but could still call @future methods, System.executeBatch, System.scheduleBatch, and System.schedule.







                            share|improve this answer













                            It sounds like you are looking for an exit event. If doesn't exist yet, but you can vote for the idea, the description of which is pasted below:




                            Since triggers only handle 200 records at a time, it would be convenient if we could schedule some code that runs in the same transaction as the current transaction, but after all other triggers, recursion, etc has executed. The registration function could be called repeatedly, but would only execute once at the end of the transaction. Here's some code that demonstrates this interface:



                            public class MyAfterEverythingElseHandler implements System.AtExitHandler {
                            public void atExit() {
                            // Perform some cleanup. For example, perform one last DML, send emails regarding the transaction, etc.
                            }
                            }


                            The class only triggers if called at least once through System.atExit, such as:



                            System.atExit(MyAfterEveryElseHandler.class);


                            This is similar to the @future annotation, but doesn't spawn a new process, has access to the full static environment of the current transaction, and remains subject to the governor limits of the current transaction. Multiple handlers could be registered via this mechanism, but the calling order would be undefined.



                            Typical uses might be to aggregate together a @future call on many thousands of records at once, debug logging, aggregate email sends across triggers, etc. Ideally, this interface should restrict DML operations, perhaps calling a "plain" commit for any records modified during the handler (e.g. no triggers, workflow rules, etc), or disabled completely, but could still call @future methods, System.executeBatch, System.scheduleBatch, and System.schedule.








                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 1 hour ago









                            Adrian LarsonAdrian Larson

                            105k19112237




                            105k19112237






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Salesforce Stack Exchange!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f246315%2fhow-can-i-know-if-its-the-last-execution-of-an-after-trigger%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                404 Error Contact Form 7 ajax form submitting

                                How to know if a Active Directory user can login interactively

                                Refactoring coordinates for Minecraft Pi buildings written in Python