Friday 9 November 2012

Understanding the Form Submission Trigger

Let's assume you want to automate some of the processing of this data - how can you set up a script which will run whenever somebody submits your form? Well, let's look at our triggers.

To view the triggers for the current scripts, click on the aptly named Current script's triggers in Resources.
Resources > Current script's triggers

If you've not set any up yet you'll see this. Click the link!

We want a Spreadsheet trigger - specifically from a form submit event

While you're here, make sure you set up Notifications
Notifications is a really handy feature nestled away with your triggers. If you set up notifications, you will receive an email if your script fails to successfully finish with a little bit of information about what went wrong. Obviously it's helpful to know that there's something to fix as soon as possible and knowing where to start looking will save you some time.

Now you've set up a trigger which will cause your function to run every time somebody submits your form! Let's test it out with a function which will email us a copy of their submission as soon as they submit it. Note; in the spreadsheet of form responses you can opt to receive email notifications every time a form is submitted simply by checking a box (Tools > Notification rules... > A user submits a form) however this is plain notification and doesn't add any detail from the submission.


Before this script will work we need to authorise the script to send email from our account. Copy and paste the script in to your project, make sure you've set up your triggers correctly and click on the save button. Now, click on the Run button (Play icon) and you'll see an authorisation window pop up. You'll need to click the authorise button if you're happy for the script to send email on your behalf.

Notes on the function

  • The function OnSubmit expects one parameter, "e". In this case, e represents the submission event and e.values is an array with values in the same order as they appear in the Spreadsheet (documentation). We asked two questions and each response has a time stamp so each submission will contain three values. As JavaScript is zero-based, the first value is the 0th ("zeroth"), the second value is the 1st, the third value is the 2nd etc.
  • "\n" indicates a new line - helpful to make our email easier to read.

And here's the result:
The fruit of our labour: an automatically generated email




2 comments:

  1. thanks, i'm just starting to crawl

    ReplyDelete
  2. I can't just figure out how to know in the onsubmit() if the response has been edited or is new. There is no such function.
    getId() always return a value, and Services.getUrl returns null.
    My point is (not) sending a different email if the response is updated.

    ReplyDelete