在表单提交时指定表单'触发器

Specifying form for 'on form submit' trigger

本文关键字:触发器 表单 表单提交      更新时间:2023-09-26

我有两个google表单,它们将数据发送到单个电子表格中的两个选项卡。

我已经设置了一个具有两个函数的脚本。我想第一个功能运行在第一个表单的提交。以及在提交第二个表单时运行的第二个函数。

问题是:当设置触发器onformsubmit时,它不允许您指定哪个表单。

因此,无论何时完成第一个表单,它都运行两个函数。

问题:如何限制函数仅在提交特定表单时才运行?

正如我在评论中建议的那样,您可以通过分析响应对象的内容来确定表单提交的来源。

这里有一个基本的例子来说明:它会给你发一封电子邮件,告诉你哪个表单已经提交了,但是你当然可以使用相同的条件测试来选择你想要运行的操作。

function formSubmitOriginTest(e){
//  Logger.log(JSON.stringify(e));
// example value : {"namedValues":{"Untitled Question 2":["test"],"Timestamp":["8/17/2014 11:22:47"]},"values":["8/17/2014 11:22:47","test"],"source":{},"range":{"rowStart":3,"rowEnd":3,"columnEnd":2,"columnStart":1},"authMode":{}}
  if(e.namedValues["Untitled Question 2"]!=undefined){// only form B has one question with this exact title, that's enough to identify it.
    MailApp.sendEmail(Session.getActiveUser().getEmail(),'form B has been submitted','');// optionally include the answers in the email body if you want
  }else{
    MailApp.sendEmail(Session.getActiveUser().getEmail(),'form A has been submitted','');// optionally include the answers in the email body if you want
  }
}

另一种方法是查看通过range属性出现在响应事件对象中的sheet名称。下面是我如何确定触发提交的表单的示例:

// set the sheet name that stores the form responses you care about here:
function getSourceSheetName() { return 'Form Responses 1'; }
function submit(eventObj) {
    var range = eventObj.range;
    var eventSourceSheetName = range.getSheet().getName();
    var givenSourceSheetName = getSourceSheetName();
    // if the source sheet (from form response sheet) is not the same as the specified form response sheet, quit (return) so extra forms don't trigger the code
    if (eventSourceSheetName.toUpperCase() !== givenSourceSheetName.toUpperCase() ) {
        Logger.log('A different form just submitted data - quit code');
        return;
    }
    // you now know which form submitted the response, so do whatever you want!
    // ... your code goes here
}
基本上,这段代码通过range.getSheet().getName()获取表单响应来自的表的名称。接下来,它检查该名称是否为我们正在查找的指定名称(在函数getSourceSheetName()中指定)。

我认为也可以通过:

获取活动表单名称
eventObj.source.getActiveSheet().getName();

如果你不想使用"Range"

我希望这对你有帮助!

我只是在看一些文档,发现了这个:

文档forForm

:

创建并返回一个绑定到给定表单的FormTriggerBuilder。

:

var form = FormApp.openById('1234567890abcdefghijklmnopqrstuvwxyz');
 ScriptApp.newTrigger('myFunction')
     .forForm(form)
     .onFormSubmit()
     .create();

onFormSubmit