为“提交表​​单”触发器指定表单

bea*_*ano 3 javascript triggers google-sheets google-apps-script google-forms

我有两个Google表单,可将​​数据发送到单个电子表格中的两个标签中。

我已经设置了具有两个功能的脚本。我希望第一个函数在提交第一个表单时运行。并且,第二个函数在提交第二个表单时运行。

问题是:在设置触发器onformsubmit时,它不允许您指定哪种形式。

因此,无论何时填写第一个表格,它都会运行两个功能。

问题:如何限制仅在提交特定表单后才能运行的功能?

Ser*_*sas 5

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

这是一个基本示例:它将向您发送电子邮件,告知您已提交了哪个表单,但是您当然可以使用相同的条件测试来选择要执行的操作。

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
  }
}
Run Code Online (Sandbox Code Playgroud)


Blu*_*her 5

可以完成此操作的另一种方法是通过属性查看sheet响应的事件对象中的名称range。这是我如何确定触发提交的表单的示例:

// 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
}
Run Code Online (Sandbox Code Playgroud)

基本上,此代码获取Form响应来自的工作表的名称range.getSheet().getName()。接下来,它会检查该名称是否是我们要查找的指定名称(在函数中指定)getSourceSheetName()。

我认为也可以通过以下方式获取活动工作表名称:

eventObj.source.getActiveSheet().getName();
Run Code Online (Sandbox Code Playgroud)

如果您不想使用“范围”。

我希望这有帮助!