Get the current response onSubmit - google-apps-script

Is there any way to find out the current response of the Google Form (programmatically)?
In the onSubmit function.
Looked over their documentation but I have to provide the respondId.
How do I find the respondId?
A snipped code from them about this is:
// Open a form by ID and log the responses to each question.
var form = FormApp.openById('1234567890abcdefghijklmnopqrstuvwxyz');
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var itemResponses = formResponse.getItemResponses();
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
Logger.log('Response #%s to the question "%s" was "%s"',
(i + 1).toString(),
itemResponse.getItem().getTitle(),
itemResponse.getResponse());
}
}
UPDATE:
function onSubmit(e) {
/* Get values entered by filling the form */
var itemResponses = e.response.getItemResponses();
var myWantedValue = itemResponses[COLUMN_NUMBER].getResponse();
}
Note: By passing the e(vent) as parameter the values can be accessed by submitting the live form, NOT by the script editor!

This code gives you the values for the last form response, is that what you're looking for ?
function myFunction() {
var formResponses = FormApp.getActiveForm().getResponses();
Logger.log(formResponses.length);
var formResponse = formResponses[formResponses.length-1];
var itemResponses = formResponse.getItemResponses();
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
Logger.log('Last response to the question "%s" was "%s"',
itemResponse.getItem().getTitle(),
itemResponse.getResponse());
}
}

You are trying to read the exact response that triggered the execution of onSubmit(), to run another process on particular data, such as sending a confirmation email.
If the above is correct:
Instead of using the form as a data source for your later processing, try to read the Google Sheet storing the responses. It may seem the problem is the same: reading either data source (the form itself, or the sheet storing the data), doesn't point you to the exact entry that has triggered the onSubmit() event.
The difference is that in a sheet you can create a "reply_sent" column, to timestamp the instant each form response has been postprocessed, for example, having sent an automated reply based on its contents.
Then, when onSubmit() is run, it goes through all responses and processes not only the last one received, or the one having triggered the onSubmit() funtion, but also any other response that may have been left unreplied for whatever reason ("reply_sent" field blank). A last benefit from this approach is that your script is logging how it is behaving, since a date is recorded along with each response as it triggers obSubmit().

You cannot set up a custom confirmation message for each user.

Related

Sending Google Forms responses to specified e-mail address on Submit

I am trying to setup Google Form in a way that once Form Submiter hits "Submit" button the responses are not only populated in dedicated spreadsheet but also sent via e-mail to particular mailing group
Probably the best way would be to use Google Scripts and Triggers, including "onsubmit", "Mailapp.sendmail" functions but my struggles here are:
a) to get the responses directly from just submitted form
b) to change "send from" e-mail address (that would send an e-mail to mailing group) to submiter's e-mail
c) connect the form responses with mailapp.sendmail function
I have tried something like this but it holds the issues mentioned above:
function OnSubmit(e) { var formResponses =
FormApp.getActiveForm().getResponses();
Logger.log(formResponses.length);
var formResponse = formResponses[formResponses.length-1];
var itemResponses = formResponse.getItemResponses();
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
Logger.log('Last response to the question "%s" was "%s"',
itemResponse.getItem().getTitle(),
itemResponse.getResponse());
MailApp.sendEmail ("email#mydoiman.com", "Form Submited " + Date.now(),
FormApp.getActiveForm().getResponses());
}}
I really appreciate all your help! Because I am total amateur in this one.
a) to get answer in an email you can do that :
function sendAnswers(e) {
var items = e.response.getItemResponses();
var emailRespondent = e.response.getRespondentEmail();
var html = "";
for(var i = 0; i< items.length; i++) {
var item = items[i];
html += "<b>"+item.getItem().getTitle()+"</b> : "+ item.getResponse() + "<br>";
}
MailApp.sendEmail("EMAIL_RECIPIENT", "Form answers", "", {htmlBody:html})
}
b) it is not possible to change the 'To' of email.
c) Yes we use the MailApp function.
=> do not forget to create a trigger to have the function run on onFormSubmit.
=> in emailRespondent you have email of person that submit the form if you click to collect email of respondent. if you don't do that comment the line i.e.
// var emailRespondent = e.response.getRespondentEmail();
Stéphane

How to make a statement that checks if there's a response to an item in a google form

I want to make some kind of statement that checks if an item in the form has a response or not. Like if the item has no response it does nothing further but if it does it will continue on.
If you have a look at the documentation
https://developers.google.com/apps-script/reference/forms/
You will find a couple of useful methods. So, getItemResponses() returns a string object and allows you to check if the string is not empty (which would mean that there is no response) .
Example code:
// This code gets all the form responses and checks if the response to question number 3 empty
function myFunction()
{
// Open a form by ID and log the responses to each question.
var form = FormApp.openById('1DUR5CfnI3Dk3LfFC4tiYJiaKRGd1DViYwQBWi9jxC4A');
var formResponses = form.getResponses();
var formResponse;
var itemResponses;
var itemResponse;
//i loops through different submissions of a form, e.g. if 3 users submitted a form - there will be three entries for formResponse
for (var i = 0; i < formResponses.length; i++)
{
formResponse = formResponses[i];
itemResponses = formResponse.getItemResponses();
// j loops through the different questions of each submitted form
for (var j = 0; j < itemResponses.length; j++)
{
itemResponse = itemResponses[j];
// the if loop checks if the response is an empty string
if(j==2&&(itemResponse.getResponse()==""||itemResponse.getResponse()==" "))
{
Logger.log('There is no response for question %s in form submission #%s', (j + 1).toString(),(i + 1).toString())
}
}
}
}
Useful for you could be also isRequired()
to make the response to a question obligatory and thus, make sure that there will be a response to the item. Hope this helps!

Google Apps Script: "Script function not found" error

I have been searching around for a solution for my issue but have not been able to find one, and as a result am writing my first question in Stack Overflow.
I am currently writing a simple program on Google Apps Script that sends out an email reminder to a user if they forget to submit a Google Form by a certain date. Right now I have 3 different functions: onFormSubmit, scheduleTrigger, and reminderEmail. Below is the code I have written out thus far:
/**
This function searches the Google Form for the date when the previous
session was held & the date when the next session will be held.
This function also calculates the date when to remind the user if they
forget to submit the Google Form. This reminder date is calculated to be 2
days after the date when the next session is held.
This function calls the next function: scheduleTrigger.
*/
function onFormSubmit(e) {
var form = FormApp.getActiveForm();
var frm = FormApp.getActiveForm().getItems();
var futureDate = new Date(e.response.getResponseForItem(frm[3]).getResponse());
var pastDate = new Date(e.response.getResponseForItem(frm[0]).getResponse());
var reminderDate = new Date(futureDate.setDate(futureDate.getDate() + 2));
futureDate.setDate(futureDate.getDate() - 2);
scheduleTrigger(reminderDate, futureDate, pastDate, form);
}
/**
This function schedules the reminder email trigger at a specific date. The
specific date is the reminder date that was calculated in the previous function.
This function calls the next function: reminderEmail.
*/
function scheduleTrigger(reminderDate, futureDate, pastDate, form) {
ScriptApp.newTrigger('reminderEmail(reminderDate, futureDate, pastDate, form)').timeBased().atDate(reminderDate.getFullYear(), reminderDate.getMonth(), reminderDate.getDate()).inTimezone('America/New_York').create();
}
/**
This function checks the submissions if the form has been submitted.
If there is no submission, then it sends out an email reminder.
*/
function reminderEmail(reminderDate, futureDate, pastDate, form) {
var count = 0;
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var itemResponses = formResponse.getItemResponses();
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
if (itemResponse == futureDate) {
count++;
}
}
}
if (count != 2) {
MailApp.sendEmail("test#gmail.com",
"Submit Form Reminder",
"Hey! You didn't fill out the form yet!");
};
}
The issue I am running into is that I receive an error message stating "The selected function cannot be found" for function reminderEmail whenever I run the program. I have looked around and followed previous posts made to solve this issue, such as renaming the function and restarting with a whole new different Google From but nothing has worked. I also have full ownership and authorization to the script so permissions shouldn't be an issue.
Please let me know if you have any ideas on how to solve this problem. Any and all feedback is welcome! If there is any part of my question that is unclear please let me know. Thank you for taking the time to read through this lengthy post.
The reason it's failing is because you need to only pass the function name to ScriptApp.newTrigger. You can't send parameters with it, that's something you'll have to handle in other ways.
Documentation
/**
This function searches the Google Form for the date when the previous session was held & the date when the next session will be held.
This function also calculates the date when to remind the user if they forget to submit the Google Form. This reminder date is calculated to be 2 days after the date when the next session is held.
This function calls the next function: scheduleTrigger.
*/
function onFormSubmit(e) {
var form = FormApp.getActiveForm();
var frm = FormApp.getActiveForm().getItems();
var futureDate = new
Date(e.response.getResponseForItem(frm[3]).getResponse());
var pastDate = new
Date(e.response.getResponseForItem(frm[0]).getResponse());
var reminderDate = new Date(futureDate.setDate(futureDate.getDate() + 2));
futureDate.setDate(futureDate.getDate() - 2);
scheduleTrigger(reminderDate);
}
/**
This function schedules the reminder email trigger at a specific date. The specific date is the reminder date that was calculated in the previous function.
This function calls the next function: reminderEmail.
*/
function scheduleTrigger(reminderDate) {
ScriptApp.newTrigger('reminderEmail').timeBased().atDate(reminderDate.getFullYear(), reminderDate.getMonth(), reminderDate.getDate()).inTimezone('America/New_York').create();
}
/**
This function checks the submissions if the form has been submitted. If there is no submission, then it sends out an email reminder.
*/
function reminderEmail() {
var form = FormApp.getActiveForm();
var count = 0;
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var itemResponses = formResponse.getItemResponses();
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
if (itemResponse == futureDate) { // Unsure what this part is for, perhaps you should find another way to calculate this.
count++;
}
}
}
if (count != 2) {
MailApp.sendEmail("test#gmail.com",
"Submit Form Reminder",
"Hey! You didn't fill out the form yet!");
};
}
I was able to clean up your code to a way it should work, but not sure about futureDate in the reminderEmail function.

Using a script to edit data from a form submission

It appears the data submitted to a Google Form is saved not just in the associated spreadsheet, but also in the Form itself I have an HTML interface that displays the data to internal staff in a Non-Profits account. Some of this data may change or may not be known at the time of submission. Other information is saved in additional fields in the associated spreadsheet. I can add and edit that data, but is it possible to edit the data in the form file as well?
It is possible to get the data saved as a response in the form itself, and you can submit new responses programmatically. I don't think you can alter existing responses with Google Apps Script. See https://developers.google.com/apps-script/reference/forms
// Open a form by ID and log the responses to each question.
var form = FormApp.openById('1234567890abcdefghijklmnopqrstuvwxyz');
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var itemResponses = formResponse.getItemResponses();
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
Logger.log('Response #%s to the question "%s" was "%s"',
(i + 1).toString(),
itemResponse.getItem().getTitle(),
itemResponse.getResponse());
}
}

Problems retrieving formResponse title

I'm working on Google Apps Script which should process data submitted from the Google Form.
Problem is that I'm getting this error after execution of itemResponse.getItem().getTitle():
Execution failed: Failed to retrieve form data. Please wait and try again. (line 20, file "Code") [0.664 seconds total runtime]
Example:
I created a sample form with sample questions (question1, question2 ... question10).
In Script editor i created a simple script to log the question titles:
function checkSubmitted() {
var form = FormApp.getActiveForm();
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var itemResponses = formResponse.getItemResponses();
Logger.log(itemResponses.length);
for (var j = 0; j < itemResponses.length; j ++) {
var itemResponse = itemResponses[j];
var item = itemResponse.getItem();
Logger.log(item.getTitle()); //this is the problematic line
Logger.log(item.getId());
}
}
}
Sometimes it gets logged just 9 question sometimes about 16 question, looks to me like it is random, because in some forms with fewer question this code get through some formResponses and than it die on third question.
Any suggestions what could be wrong?
I'm having the exact same problem with a script that was working fine just yesterday. Honestly, I think there's a problem with the platform. Googling it return no results but this very post. The closer I've seen is this, and the answers did not help.