【问题标题】:google-apps-script: No "source" field on event triggergoogle-apps-script:事件触发器上没有“源”字段
【发布时间】:2018-09-27 14:54:41
【问题描述】:

我已经设置了一个触发器来提交一个 Google 表单来运行我的一个 Google 脚本:

ScriptApp.newTrigger('onFormSubmitted')
    .forForm(form).onFormSubmit().create();

我的onFormSubmitted 函数被触发,但提供给该函数的事件参数没有source 属性。它有 the documentation says it should have 的 4 个字段中的 3 个。

那么我应该如何获得对触发此事件的表单的引用?

TMI

function onFormSubmitted(data, arg) {
  log(8, data['triggerUid'], -1) // => 1874727473075378640
  log(9, data['authMode'], -1) // => FULL
  log(10, data['response'], -1) // => FormResponse
  log(11, data['source'], -1) // => undefined
}

【问题讨论】:

  • 显示onFormSubmitted函数代码和确切的错误。
  • 如果apps脚本文件绑定在Form上,则可以获取到活动的Form。 var form = FormApp.getActiveForm(); 这也适用于作为附加组件安装的独立文件。不用作附加组件的独立文件将无法触发 On Form Submit 事件。我不确定图书馆。但除非您将应用程序脚本文件用作库,否则我会尝试获取活动表单。
  • @SandyGood : 嗯...我正在使用这个脚本来创建许多表单并注册一个触发器。一个脚本可以绑定多个表单吗?
  • @SandyGood :是的,我对多个表单使用相同的功能。 (表单以编程方式生成。)当我的onFormSubmit 函数调用FormApp.getActiveForm() 时,我得到undefined
  • developers.google.com/apps-script/guides/bound 我相信@tehhowch 的回答可以满足您的问题。

标签: google-apps-script triggers google-forms


【解决方案1】:

documentation for the event object 中所述,如果脚本未绑定,则没有关联的source 属性。您可以通过使用触发器 uid 将表单 id 存储在 properties 中来克服这个问题。然后在您的表单提交代码中,使用触发器 uid 来获取正确的表单。

function getFormId_(triggerId) {
  const store = PropertiesService.getScriptProperties();
  var formId = store.getProperty(triggerId);
  if (!formId) console.warn("No form ID found for trigger ID '" + triggerId);
  return formId;
}
function createSubmitTrigger_(form, functionName) {
  const formId = form.getId();
  const trigger = ScriptApp.newTrigger(functionName).forForm(form)
      .onFormSubmit()
      .create();

  const store = PropertiesService.getScriptProperties();
  store.setProperty(trigger.getUniqueId(), formId);
}

function myFormSubmit(e) {
  const form = FormApp.openById(getFormId_(e.triggerUid));
  ...
}

这种方法(存储和检索)可能可以向后应用,但这取决于触发器之前的配置方式 - 您不能以编程方式(或以其他方式)与其他触发器交互。

function storeAll() { // Run once (more is ok too, will just overwrite existing keys).
  function cb(acc, t, i, allVals) { // callback for Array#reduce
    acc[t.getUniqueId()] = t.getTriggerSourceId();
    return acc;
  }

  const newProps = ScriptApp.getProjectTriggers().reduce(cb, {});
  PropertiesService.getScriptProperties().setProperties(newProps);
}

参考文献

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2023-03-03
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多