如何识别多个 Google 表单喂养一个 Google Sheet?

How to identify multiple Google Forms feeding one Google Sheet?

我有一个 Google Sheet,底部有许多不同的“sheet 标签”。其中一些与 Google 表单相关联,因此当填充该表单时,条目会显示在该“选项卡”上。

我也在尝试将这些条目注入到 MySQL 数据库中。我已经通过使用绑定到 Sheet 的 Google Apps 脚本的 Google Sheet/Form 配对成功地实现了此功能,它会侦听 onFormSubmit。该代码如下:

// These are the Database connections values
var user = 'dbUsername';
var userPwd = 'dbPassword';
var db = 'databaseName';

var dbUrl = 'jdbc:mysql://192.168.0.0:3306/' + db;

/**
 * @param {Object} e The event parameter for form submission to a spreadsheet;
 *     see https://developers.google.com/apps-script/understanding_events
 */
function onFormSubmit(e) {
  console.log(e);
  var color = e.namedValues['Color1'][0]; // these names ('Color', 'Number') come from the Form's Question 
  var number = e.namedValues['Number1'][0];
  writeColor(color, number);
}

/**
 * Write one row of data to a table.
 */
function writeColor(color, number) {
  var conn = Jdbc.getConnection(dbUrl, user, userPwd); // this connects to the database

  var stmt = conn.prepareStatement('INSERT INTO test_google_forms '
      + '(`color`, `number`) values (?, ?)');
  stmt.setString(1, color);
  stmt.setString(2, number);
  stmt.execute(); // this performs the SQL that was "prepared" in the previous 3 lines
}

但似乎 Google 会在提交任何附加表单时触发该功能。因此,如果我有两个表单提供相同 Sheet 的不同选项卡,它会执行此代码,而不管提交的是哪个表单(或它正在写入哪个选项卡)。

此外,我在传递的事件对象中看不到任何关于它来自哪个表单(或它正在写入的选项卡)的信息,所以我不知道如何对这些响应进行分类以转到正确 MySQL 个表格。

有什么方法可以过滤这些调用,或者我是否需要将我的 Sheet 拆分为每个 Sheet 1 个制表符以避免这种冲突?

您可以根据sheet姓名进入表格:

function getFormNameBySheetName(e) {
  //assume that this function is installable onEdit trigger handler
  const fObj = {'Sheet1Name':'Form1Name',
                'Sheet2Name':'Form2Name'
     }; // You can build this form you personal knowledge of which form is to which sheet
  const sh = e.range.getSheet();
  const name = sh.getName();
  if(!fObj.hasOwnProperty(name)) return;
  const formname = fObj[name];
  return formname;
}

onFormSubmit trigger event obj