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












3















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
    Jan 11 at 13:59











  • Not really. This question is about the last execution of the afterTrigger of the same context of execution (i.e. CODE_UNIT). The one that you mentioned is regarding the end of a batch of contexts.

    – Leandro Ferreira Fernandes
    Jan 16 at 17:03
















3















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
    Jan 11 at 13:59











  • Not really. This question is about the last execution of the afterTrigger of the same context of execution (i.e. CODE_UNIT). The one that you mentioned is regarding the end of a batch of contexts.

    – Leandro Ferreira Fernandes
    Jan 16 at 17:03














3












3








3


0






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 Jan 11 at 9:12









Leandro Ferreira FernandesLeandro Ferreira Fernandes

947




947













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

    – Adrian Larson
    Jan 11 at 13:59











  • Not really. This question is about the last execution of the afterTrigger of the same context of execution (i.e. CODE_UNIT). The one that you mentioned is regarding the end of a batch of contexts.

    – Leandro Ferreira Fernandes
    Jan 16 at 17:03



















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

    – Adrian Larson
    Jan 11 at 13:59











  • Not really. This question is about the last execution of the afterTrigger of the same context of execution (i.e. CODE_UNIT). The one that you mentioned is regarding the end of a batch of contexts.

    – Leandro Ferreira Fernandes
    Jan 16 at 17:03

















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

– Adrian Larson
Jan 11 at 13:59





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

– Adrian Larson
Jan 11 at 13:59













Not really. This question is about the last execution of the afterTrigger of the same context of execution (i.e. CODE_UNIT). The one that you mentioned is regarding the end of a batch of contexts.

– Leandro Ferreira Fernandes
Jan 16 at 17:03





Not really. This question is about the last execution of the afterTrigger of the same context of execution (i.e. CODE_UNIT). The one that you mentioned is regarding the end of a batch of contexts.

– Leandro Ferreira Fernandes
Jan 16 at 17:03










3 Answers
3






active

oldest

votes


















5














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































    6














    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


























    • even though I set some static variables that it was already executed, how could I determine if that is the last After Trigger or not?

      – Leandro Ferreira Fernandes
      Jan 11 at 17:55






    • 1





      @LeandroFerreiraFernandes You can't unless you also have variables that confirm the preceding WF and PB operations have also run.

      – Keith C
      Jan 11 at 18:31



















    5














    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














      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




























        5














        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


























          5












          5








          5







          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 Jan 11 at 13:04









          Charles TCharles T

          6,3561922




          6,3561922

























              6














              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


























              • even though I set some static variables that it was already executed, how could I determine if that is the last After Trigger or not?

                – Leandro Ferreira Fernandes
                Jan 11 at 17:55






              • 1





                @LeandroFerreiraFernandes You can't unless you also have variables that confirm the preceding WF and PB operations have also run.

                – Keith C
                Jan 11 at 18:31
















              6














              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


























              • even though I set some static variables that it was already executed, how could I determine if that is the last After Trigger or not?

                – Leandro Ferreira Fernandes
                Jan 11 at 17:55






              • 1





                @LeandroFerreiraFernandes You can't unless you also have variables that confirm the preceding WF and PB operations have also run.

                – Keith C
                Jan 11 at 18:31














              6












              6








              6







              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 Jan 11 at 12:17

























              answered Jan 11 at 10:37









              Keith CKeith C

              95k1090206




              95k1090206













              • even though I set some static variables that it was already executed, how could I determine if that is the last After Trigger or not?

                – Leandro Ferreira Fernandes
                Jan 11 at 17:55






              • 1





                @LeandroFerreiraFernandes You can't unless you also have variables that confirm the preceding WF and PB operations have also run.

                – Keith C
                Jan 11 at 18:31



















              • even though I set some static variables that it was already executed, how could I determine if that is the last After Trigger or not?

                – Leandro Ferreira Fernandes
                Jan 11 at 17:55






              • 1





                @LeandroFerreiraFernandes You can't unless you also have variables that confirm the preceding WF and PB operations have also run.

                – Keith C
                Jan 11 at 18:31

















              even though I set some static variables that it was already executed, how could I determine if that is the last After Trigger or not?

              – Leandro Ferreira Fernandes
              Jan 11 at 17:55





              even though I set some static variables that it was already executed, how could I determine if that is the last After Trigger or not?

              – Leandro Ferreira Fernandes
              Jan 11 at 17:55




              1




              1





              @LeandroFerreiraFernandes You can't unless you also have variables that confirm the preceding WF and PB operations have also run.

              – Keith C
              Jan 11 at 18:31





              @LeandroFerreiraFernandes You can't unless you also have variables that confirm the preceding WF and PB operations have also run.

              – Keith C
              Jan 11 at 18:31











              5














              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




























                5














                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


























                  5












                  5








                  5







                  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 Jan 11 at 13:57









                  Adrian LarsonAdrian Larson

                  107k19113241




                  107k19113241






























                      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

                      Mario Kart Wii

                      The Binding of Isaac: Rebirth/Afterbirth

                      What does “Dominus providebit” mean?