I have a Google Form and a Google Spreadsheet.
timestamp | name | email | revenue | Edit Url
2015-2-2 02:22:22 | David | | |
2015-2-2 07:22:22 | Paul | | |
2015-2-2 09:22:22 | Olive | | |
What I am trying to accomplish:
- Based on the information in the Spreadsheet (name, email, revenue) I'd like to programmatically iterate through each row, populate the Form based on the information in each row then submit the form and for each form submitted generate an edit URL which will be stored in the Edit Url column.
So far this is my Google app Script:
function myFunction() {
createSurveyResponses();
}
function createSurveyResponses() {
// Open a form by ID and add a new text item.
var form = FormApp.openById('form_id');
var response = form.createResponse();
var sheet = SpreadsheetApp.openById('spreadsheet_id');
var getAct = sheet.getActiveSheet();
var data = sheet.getDataRange().getValues();
// Access the text item as a generic item.
var items = form.getItems();
var item = items[0];
var urls = [];
var resultUrls = [];
for (var j = 1; j < data.length; j++) {
var dop = data[j][0]
if (item.getType() == 'TEXT') {
var textItem = item.asTextItem();
var itemResponse = textItem.createResponse(data[j][0]);
var another = response.withItemResponse(itemResponse);
response.submit();
}
}
// get the responses from the spreadsheet
var fresponses = form.getResponses();
for (var i = 0; i < fresponses.length; i++) {
var resp = [fresponses[i]];
urls.push([shortenUrl(fresponses[i].getEditResponseUrl())]);
}
var getdata = getAct.getRange(2,5,fresponses.length)
getdata.setValues(urls);
}
function shortenUrl(longUrl) {
// google url shortener api key
var key = "AIzaSyBVG4Q5i1mNI0YAO0XVGZ3suZU8etTvK34";
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;
}
However, when I run the code, after the first iteration (first row) I get an error Sorry, this response has already been submitted. (line 34, file "")
which is when I'm submitting the response response.submit();
.
What am I doing wrong?
My ultimate goal is to generate a unique URL for each row so that my recipients can use that URL to update their responses whenever they want (getEditResponseUrl()
).