Ensure form submission trigger runs only one sheet

前端 未结 1 642
梦谈多话
梦谈多话 2021-01-23 22:32

I have two sheets in a particular spreadsheet both of which have form submissions tied to them. The first sheet/form is supposed to send an email containing the form submission

相关标签:
1条回答
  • 2021-01-23 22:54

    A Sheets form submission trigger will be invoked for all forms submitted to the spreadsheet. Once upon a time, only one form could be associated with a spreadsheet, but now, with multiple form associations possible, you need to allow for that possibility. You can't specify which form a trigger function is for, but you can check the source of the event and respond appropriately.

    One effective way to do this is to use a director function which will receive all form submission events, and direct them to unique trigger functions depending on which sheet received the response.

    Here, we are associating "Form Responses 1" with SendConfirmationMail(), and assuming that "Form Responses 2" has its own form submission handler, handleForm2(). (If there is no handler for that form, then the specific case can be deleted, and submissions will end up in the default case.)

    /**
     * This director function should be used as the "top level" form submission trigger
     * function for spreadsheets accepting responses from multiple forms. Events are
     * directed to the appropriate trigger sub-functions according to the name of the
     * sheet which received the current response.
     * 
     * From: https://stackoverflow.com/a/37839189/1677912
     */
    function formSubmitted(e) {
      var sheetName = e.range.getSheet().getName();
      switch (sheetName) {
        case "Form Responses 1":
          SendConfirmationMail(e);
          break;
        case "Form Responses 2":
          handleForm2(e);
          break;
        default:
          // do nothing
          break;
      }
    }
    

    If you use a Forms form submission trigger instead, you can avoid this altogether, since the destination spreadsheet would not be a direct consideration.

    I suppose the script thinks Sheet2 is active (which if I have the spreadsheet open could be the case)

    Not quite. The trigger function is invoked outside of the context of any spreadsheet UI, so what any user is doing in the spreadsheet has no effect on it. Rather, the "active" sheet is related to the submission event being handled. Regardless, it is a much better idea to reference the event object itself, rather than rely on "normal" operations. It does become trickier to test and debug, but not terribly so. For more about testing trigger functions, see How can I test a trigger function in GAS?

    0 讨论(0)
提交回复
热议问题