0
votes

I've been trying to get Apps script to do an action after a Google Form has been submitted.

My trouble is, the triggers only work if

  1. The Apps Script is bound to a Google Form
  2. And the trigger is created on that Google Form it is bound to

That's not to say the triggers aren't created in other scenarios. They just don't fire.

What I'm trying to do is have a stand alone app script create a trigger on any form. This is done by running Run > Test as addon and picking any form I like. I have a menu that opens a dialog containing my button which runs google.script.run.withSuccessHandler(function(data) { }).makeTrigger();

When I open my dashboard at script.google.com and look at My Triggers, it does create them for any form I open with Test as addon. They are properly set with the event "From form - On form submit" and when I open the menu to "Open triggering container" it goes to the correct form. But when I open the form and make a response, they are never actually triggered (the "Last executed" column in My Triggers remains empty, and my endpoint gets no post.)

They are only triggered on submit if the above 2 conditions are met (I remade my apps script as a bound version to test this.) My bound version also does not work if I use it on any other form besides the one it's bound to -- it does the same thing, making the untriggerable triggers.

Code.gs

function formIsSubmitted(e) {
  UrlFetchApp.fetch("https://test.free.beeceptor.com", {
    'method': 'post',
    'payload': 'from apps script'
  });
}

function makeTrigger() {
  var form = FormApp.getActiveForm();
  ScriptApp.newTrigger('formIsSubmitted')
    .forForm(form)
    .onFormSubmit()
    .create();
}

I have put my addon to be unlisted-published in the market place (waiting for it to be reviewed.) Will this fix the problem, or am I missing something?

1
There's two onFormSubmit Triggers. One is attached to the Form and One is attached to the linked spreadsheet. Read this section:developers.google.com/apps-script/guides/triggers/events - Cooper
@Cooper I haven't attached any spreadsheets to these forms. Could this still be my issue? How would I change my trigger creation function to be for form submits? I couldn't see any code examples in the documentation. - Ayub

1 Answers

1
votes

In this case you will want to use a onFormSubmit trigger attached to the form itself. To achieve that be sure to use the .forForm(key) signature method to attach the trigger from a standalone script. Once you get the Forms keys from your custom dialog you should use them in your makeTrigger() function:

function makeTrigger(keys) {
  keys.map(key => {
    ScriptApp.newTrigger('formIsSubmitted')
      .forForm(key)
      .onFormSubmit()
      .create();
  });
}

function formIsSubmitted(e) {
  UrlFetchApp.fetch("https://test.free.beeceptor.com", {
    'method': 'post',
    'payload': 'from apps script'
  });
}

References:

Installable Triggers