在表单提交上指定表单'触发

时间:2014-08-10 11:10:14

标签: javascript google-apps-script google-sheets triggers google-form

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

我已经设置了一个包含两个函数的脚本。我想第一个函数在提交第一个表单时运行。并且,第二个函数在提交第二个表单时运行。

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

因此,每当完成第一个表单时,它都会运行这两个函数。

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

3 个答案:

答案 0 :(得分: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
  }
}

答案 1 :(得分: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
}

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

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

eventObj.source.getActiveSheet().getName();

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

我希望这有帮助!

答案 2 :(得分:1)

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

Documentation forForm

它声明:

  

创建并返回与给定表单关联的FormTriggerBuilder。

此外:

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

onFormSubmit

该代码似乎与特定表格相关联。

相关问题