ScriptApp.newTrigger().forForm Issue - google-apps-script

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?

Related

Why my Google Form FormResponse doesn't submitted?

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.

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);

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.

Google Apps Script: create a pdf by editing response to google form

I'm hoping that someone can help me, What i want to do is to make a Google form create a new document and send that pdf via email when the form is edited.
I understand that when you edit a form the script inside a spreadsheet does not run, So i have put the script into a form and that is where i am having problems. I can not get the script to read the values that are been resubmitted on the form, it just keeps on coming up as "undefined" on the return
This is the script that i have got so far.
function Test(e) {
var form = FormApp.openById('****Form Key****'); //Enter Form ID here
var docTemplate = "***doc to be used***";
var docName = "***Name of document***";
var formResponse = form.getResponses();
var one = e.response; //I have tried e.value but does not pull through
var two = e.response; // Column 2
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('one', one);
copyBody.replaceText('two', two);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
//Sends the email
var email_Address = "***Email Address***"
var subject = "***Subject";
var body = "**Body***";
MailApp.sendEmail(email_Address, subject, body, {attachments: pdf});
}}
Any help will be greatly appreciated as i have been stuck on this for a while. thank you.
In a Form Response Trigger function, the event is an instance of Class FormResponse. Because of that, you don't need to open the form, or get responses... you've just had one handed to you, which you access via e.response. (See Form Response Events in Understanding Events.)
// Handle form response event
// This function must be a Form Response Trigger, attached to
// a Form (not a Spreadsheet).
function rightTest( e ) {
var formResponses = e.response.getItemResponses(); // array of responses
var one = formResponses[0];
var two = formResponses[1];
...
}
As of April 2015, DocsList is not supported, simply replace DocsList. with DriveApp. How to update DocsList to DriveApp in my code

Blank Multiple Choice Item Responses

I am attempting to create a response to a Google Form using the updated API. Below is my code:
function submitResponse() {
var form = FormApp.openByUrl('some url');
var items = form.getItems();
var itemResponse = items[0].asMultipleChoiceItem().createResponse('No');
var formResponse = form.createResponse().withItemResponse(itemResponse);
formResponse.submit();
return;
}
The form contains a Yes/No question. Yes and No are the only options and there is only one question. The script runs but it submits a FormResponse containing a blank response to the item. Any ideas?
Thanks for any and all help!
I just built a quick copy and this worked for me. The only thing I changed was the typo you have in itemResponse.
from:
var formResponse = form.createResponse.withItemResponse(itemREsponse);
to:
var formResponse = form.createResponse.withItemResponse(itemResponse);
Hope this helps.