Ensure form submission trigger runs only one sheet

蓝咒 提交于 2019-12-02 04:13:40
Mogsdad

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!