Why my Google Form FormResponse doesn't submitted? - google-apps-script

I try to submit my Google Form response programmaticaly with Google Apps Script to set unique id to answer (I did it when response heading off to Google Spreadsheet, but it is not useful solution for me because I want to send id in Email Notification generated by add-on while form submitted). I follow to Google Apps Script documentation:
Creates a new response to the form. To answer a question item, create an ItemResponse from the item, then attach it to this form response by calling FormResponse.withItemResponse(response). To save the assembled response, call FormResponse.submit(),
and tried to execute this method in onFormSubmit event.
But it failed on FormResponse.submit() with Exception: Failed to send response. Wait a few minutes and try again. at onFormSubmit.
function onFormSubmit(e){
var response = '5';
var form = FormApp.getActiveForm();
var questions = form.getItems();
var textItem=questions[2].asTextItem();
var itemResponse=textItem.createResponse(response);
Logger.log(textItem.getTitle()); //Logs right title 'MyTitle'
Logger.log(itemResponse.getResponse()); //Logs right response '5'
var formResponse=form.createResponse();
formResponse.withItemResponse(itemResponse);
formResponse.submit(); //An exeception occurs here
}
What could be the problem? Thanks.

Related

Send Form response from prefilled link in Apps Script

I've tried to find some topic about it but without results
I would need only send Form from copied prefilled link in apps script but i am not able to find out where doing misstakes.
Here are two options what i've found but without good results.
Form doesn't send any response
I've replace in prefilled Link "viewform" for "formResponse" according to some instructions in web, but it does't work.
Do you can help me anyone?
function send() {
var config = {
muteHttpExceptions: true,
method: "get"
};
var url = "https://docs.google.com/forms/d/e/<form_id>/formResponse?usp=pp_url&entry.231322462=ANO&entry.133135319=1&entry.1743053173=2023-01-15";
var response = UrlFetchApp.fetch(url, config);
//Logger.log(response)
}
or:
function send() {
var url = "https://docs.google.com/forms/d/e/<form_id>/formResponse?usp=pp_url&entry.231322462=ANO&entry.133135319=1&entry.1743053173=2023-01-15";
var response = UrlFetchApp.fetch(url);
//Logger.log(response)
}
You have an existing Google Form and you want to write a script in order to edit existing Form Responses in in the Form.
At the time of writing, this isn't possible.
Refer:
Edit Form Responses as soon as it is submitted

Set pre-filled value of Google Form item from google apps script

What I want to achieve?
I want to track the review status of a google document with a google form with dropdown options as "To do, In progress, Done". I have google form items as "URL of document, Status". I have created a google form template that I'll be using to create forms for various users. I want to be able to create a copy of the template form, and set predefined value of "URL" from google apps script, so that the users just have to select the status of the document.
What I tried?
I came across createResponse() method from this answer, but this requires .submit() to be used to save the response and the answer is recorded in sheets. I don't want to submit the form from the script itself. Here is the code:
function form()
{
var form = FormApp.create("Test");
form.addTextItem().setTitle("URL");
form.addTextItem().setTitle("Status");
var items = form.getItems();
var url = items[0].asTextItem();
var fr = url.createResponse('my predefined url');
var FormResponse = form.createResponse();
FormResponse.withItemResponse(fr);
FormResponse.submit();
Logger.log(form.getPublishedUrl());
}
Final query:
How do I get the published URL of the form with the pre-filled answer to the URL item from the apps script? Is it possible?
Turns out there is a method .toPrefilledUrl() which resturns the published url of form with prefilled values. Here is an example:
var form = FormApp.openByUrl("url");
var items = form.getItems();
var url = items[0].asTextItem();
var d= "some.url"
var fr = url.createResponse(d);
var FormResponse = form.createResponse();
var urlPub = FormResponse.withItemResponse(fr).toPrefilledUrl();
Logger.log(urlPub);

ScriptApp.newTrigger().forForm Issue

I am attempting to create a Google Form that when fed a different Google Form URL, it would create an onFormSubmit() trigger for the given form url.
function createFormSubmitTrigger(e) {
var formResponse = e.response;
var itemResponses = formResponse.getItemResponses();
var url = itemResponses[0].getResponse();
var formCopy = FormApp.openByUrl(url);
ScriptApp.newTrigger('onFormSubmit').forForm(formCopy).onFormSubmit().create();
}
When I log the details of formCopy, it is definitely retrieving the details of the correct given form. And yet, the only triggers getting created are for the Google Form that is accepting the URLs
Triggers Description
Am I understanding TriggerBuilder incorrectly? Is this some sort of bug?

pre-fill google form from google apps script

I have a student registration form, there's student id which is a required field. I have a google apps script function which tells if this student is registered for any class or not. Is there a way to auto-fill the field course registered via calling the google apps script function yes or no.
Yes you can create a pre filled response with the forms ID, not that the pre filled fields are showed in the URL
Function formPrefill(formId){
var form = FormApp.openById(formId);
try{
var items = form.getItems();
var formResponse = form.createResponse();
// Prefill SessionId
var formItem = "SOMETHING HERE"
var response = formItem.createResponse(sessionId);
formResponse.withItemResponse(response);
//--------ANOTHER FIELD-------------
formItem = items[4].asMultipleChoiceItem();
response = formItem.createResponse('YOUR FIELD NAME');
formResponse.withItemResponse(response);
}catch(e){catch an error here}
}
check https://developers.google.com/apps-script/reference/forms/form#createresponse

Google form url point to last updated answer

I have created a Google form with a Google spreadsheet associated to it that can be accessed (using the form URL) by each recipient I am sending it to. Right now the URL isn't unique to each recipient. The recipient can access the form then submit it. Upon submit, I am generating an edit URL via the GetEditResponse() function available in the Google FormResponse Class. The recipient can then edit their response using the edit url I provide them once they submit the form.
Here is my Google App Script code:
function myFunction() {
assignEditUrls();
}
function assignEditUrls() {
var form = FormApp.openById('formId');
//enter form ID here
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form Responses');
//Change the sheet name as appropriate
var data = sheet.getDataRange().getValues();
var urlCol = 5; // column number where URL's should be populated; A = 1, B = 2 etc
var responses = form.getResponses();
var timestamps = [], urls = [], resultUrls = [];
for (var i = 0; i < responses.length; i++) {
timestamps.push(responses[i].getTimestamp().setMilliseconds(0));
urls.push(shortenUrl(responses[i].getEditResponseUrl()));
}
for (var j = 1; j < data.length; j++) {
resultUrls.push([data[j][0]?urls[timestamps.indexOf(data[j][0].setMilliseconds(0))]:'']);
}
sheet.getRange(2, urlCol, resultUrls.length).setValues(resultUrls);
}
function shortenUrl(longUrl) {
// google url shortener api key
var key = "apiKey";
var serviceUrl="https://www.googleapis.com/urlshortener/v1/url?key="+key;
var options={
muteHttpExceptions:true,
method:"post",
contentType: "application/json",
payload : JSON.stringify({'longUrl': longUrl })
};
var response=UrlFetchApp.fetch(serviceUrl, options);
if(response.getResponseCode() == 200) {
var content = JSON.parse(response.getContentText());
if ( (content != null) && (content["id"] != null) )
return content["id"];
}
return longUrl;
}
You can also view the Spreadsheet associated with the form.
The problem with this model is that the recipients need to get back an edited URL in order to edit their response at a later time. Instead I want them to keep the same URL I originally provided them with and each time they come back to that URL I should identify which recipient it is and redirect them with the last updated URL.
For that scenario to happen I would need to:
1. Create a unique URL (identifier) for each recipient.
2. The same URL should point to the last updated URL (Form) so that they can always use the same URL originally provided (backend process).
Is this possible to achieve using Google's available tools? If it is, how can I create a unique url to identify which recipient responded to the form?
Staying within the confines of Google Apps Script, you cannot provide a redirection to a Google Form.
Here are two ideas off the top of my head...
If you're willing to use another service to handle the redirection, you could have it do the redirection for you. (I'm not recommending any, just saying it's an option.)
You could write a Google Apps Script web service that would present a mock-up of your real form. Users would have a unique URL to pass their unique identifier as a HTTP query parameter; heck, you could use goo.gl to produce a short URL for each of them as you do now. Based on the identifier, pre-fill the fake form with their last results. Upon commit, your web service can submit the form programmatically.
Create a unique URL (identifier) for each recipient.
Creating a separate Google Form for each person will give you this.
The same URL should point to the last updated URL
Assuming your go with creating a separate Form for each user, try placing the edit URL back into each Form's description or 1st page some where after submission of the 1st response. You'd have to make it clear that they have to click on that link going forward. There isn't a setting to automatically re-direct original Google Form URLs to their corresponding Edit Response ones AFAIK, if that's what you are asking for.