Fill Google form using Google Apps Script - google-apps-script

I just tried my coding below...but the problem is, my google apps script just submit the form with blank value for both "short answer" field. Can someone show me somelight how i can solve my problem. TQ.
function myFunction() {
var dapatkanForm = FormApp.openByUrl('https://docs.google.com/forms/d/1S1F3cKMwkXm3gVt00RegQ-GCzRfELOq74IH9WEk8SlU/edit?usp=sharing');
var nama = dapatkanForm.getTitle();
var listIsiText = dapatkanForm.getItems(FormApp.ItemType.TEXT);
var panjangArray = listIsiText.length;
for(var i=0; i<panjangArray; i++)
{
var textTemp = listIsiText[i];
var nakSet = textTemp.asTextItem();
var response = nakSet.createResponse('MOHD ANIS BIN AZINAN');
}
var formResponse = dapatkanForm.createResponse();
formResponse.submit();
Logger.log(nama);
}

Your code is very close to the solution. You just need one additional method. The following line…:
var formResponse = dapatkanForm.createResponse();
…should end up looking like:
var formResponse = dapatkanForm.createResponse().withItemResponse(response);
By using .withItemResponse() the form submit will upload your responses instead of being void. Please, ask me for more clarifications if you still need help.

Related

Form title from FormResponse

I have created a bunch of forms programmatically from a spreadsheet and bound a response trigger to each. When a form is filled out I can't seem to figure out which form was completed.
I tried:
Event.source.getId()
But that returns the id of the spreadsheet. I want to get the title of the form.
Edit: Clarification
This is how I set up the trigger:
ScriptApp.newTrigger('responseTrigger').forForm(form)
.onFormSubmit()
.create();
And when I try to get the title:
function responseTrigger(e) {
var source = e.source;
var title = e.source.getTitle().
Logger.log(title);
}
I get the following error:
Execution failed: TypeError: Cannot find function getTitle in object Spreadsheet.
I have finally solved this issue.
There is a know Google Scripts issue that is causing my problem. You would expect e.source.getID() to give you the form's ID, however it gives you the spreadsheet's ID. I found a solution in this question. What you do is find the unique ID of the trigger and cross reference it with all of the project triggers as follows:
function getFileByTriggerId(triggerId){
var triggers = ScriptApp.getProjectTriggers();
for(var i =0; i<triggers.length; i++){
if(triggers[i].getUniqueId() == triggerId){
return triggers[i].getTriggerSourceId();
}
}
}
And then in your response trigger you write:
function responseTrigger(e) {
var realEvent = getFileByTriggerId(e.triggerUid);
var form = FormApp.openById(realEvent);
var title = form.getTitle();
}
How about this?
If you want to retrieve the title when the form was submitted, you can use following script.
var title = e.source.getTitle()
If you always want to retrieve the title, you can use following script.
var form = FormApp.openById( form ID );
var title = form.getTitle();

Directly Update Doc Template from Form

Is it possible to submit a form and update a Doc template from the form contents? The only way I have seen for doing anything similar was submitting the form to a spreadsheet and having an onFormsubmit function within the spreadsheet update the template.
Is this not possible via forms and a container bound script?
Thanks
yes it's possible, but it's not easy (essentially using doc as template, there is no evident tools for that)
I have initially gotten this to work replacing a few lines in my document template, but now nothing is working for some reason. I did edit the text in the template at one point so I am not sure if that changes the file ID. It creates the copy, but the replaceText is not working. Code attached:
`function onFormSubmit(e) {
var dt = Utilities.formatDate(new Date(), 'GMT', "MM/dd/yyyy")
var submitter = Session.getActiveUser().getEmail();
var copyDoc = DriveApp.getFileById('1t5r8IxLgunJ17J2tXkHfw3LRfuXQeTlP5MZURC-23e0').makeCopy('tmpAddress').getId();
var newDoc = DocumentApp.openById(copyDoc);
var body = newDoc.getBody();
var itemResponse = e.response;
var name = itemResponse.getItemResponses()[0].getResponse();
var email = itemResponse.getItemResponses()[1].getResponse();
var pphone = itemResponse.getItemResponses()[2].getResponse();
var paddress = itemResponse.getItemResponses()[3].getResponse();
var palot = itemResponse.getItemResponses()[4].getResponse();
var pcity = itemResponse.getItemResponses()[5].getResponse();
var pstate = itemResponse.getItemResponses()[6].getResponse();
var pzip = itemResponse.getItemResponses()[7].getResponse();
var nphone = itemResponse.getItemResponses()[8].getResponse();
var naddress = itemResponse.getItemResponses()[9].getResponse();
var nalot = itemResponse.getItemResponses()[10].getResponse();
var ncity = itemResponse.getItemResponses()[11].getResponse();
var nstate = itemResponse.getItemResponses()[12].getResponse();
var nzip = itemResponse.getItemResponses()[13].getResponse();
body.replaceText('#{name}', name);
body.replaceText('#{email}', email);
body.replaceText('#{pphone}', pphone);
body.replaceText('#{paddress}', paddress);
body.replaceText('#{palot}', palot);
body.replaceText('#{pcity}', pcity);
body.replaceText('#{pstate}', pstate);
body.replaceText('#{pzip}', pzip);
body.replaceText('#{nphone}', nphone);
body.replaceText('#{naddress}', naddress);
body.replaceText('#{nalot}', nalot);
body.replaceText('#{ncity}', ncity);
body.replaceText('#{nstate}', nstate);
body.replaceText('#{nzip}', nzip);
body.replaceText('#{dt}', dt)
body.replaceText('#{submitter}',submitter)
newDoc.saveAndClose();
}
`

Uploading Google Spreadsheet to a Google Site

I'd like to begin by stating that the end goal is to display our company directory (a list of our employees names/job title/extension#/office location/email), which is in a Google Sheet, on a page in one of our Google Sites.
I tried to use Google's embed function, and it works... but it is very clunky, does not have a "Sort" function, and it just looks weird.
I pulled a Google Apps Script from somewhere online like 3 months ago and it actually did pull in a way that made me happy:
(This is as it appears currently on the Google Sites page. So in this screenshot, the embedded Sheet is at the top. The Sheet when, imported via the script, is below. Yes, they are both on the same page. I'm in testing!)
This is the code I used (I THINK - I don't remember how I implemented it):
function myFunction() {
}
function onOpen(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
if(ScriptProperties.getProperty("page url") == null){
ss.addMenu("List page", [{name: "Create list", functionName: "create_list"},null,
{name: "Fetch list items", functionName: "fetch_items"}]);
}
else{
ss.addMenu("List page", [{name: "Push Items", functionName: "push_items"}]);
}
}
function create_list() {
var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var parent_page = Browser.inputBox("URL of the parent page:");
var title = Browser.inputBox("Choose a name for your list page:");
var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var list = SitesApp.getPageByUrl(parent_page).createListPage(title, title.split(' ').join(''), '', data[0]);
ScriptProperties.setProperty("page url", list.getUrl());
onOpen();
push_items();
}
function push_items(){
var done = false;
while(!done){
try{
var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var list = SitesApp.getPageByUrl(ScriptProperties.getProperty("page url"));
var list_items = list.getListItems();
for(i in list_items){
list_items[i].deleteListItem();
}
for(var i = 1; i < data.length; i++){
var item = list.addListItem(data[i]);
}
done = true;
}
catch(e){
}
}
SpreadsheetApp.getActiveSpreadsheet().toast(ScriptProperties.getProperty("page url"), "List page updated", 10);
}
function fetch_items(){
var url = Browser.inputBox("URL of your list page:");
var col_number = Browser.inputBox("Number of columns in the list:");
var data = new Array();
var list_items = SitesApp.getPageByUrl(url).getListItems();
for(i in list_items){
var row = new Array();
for(j = 0; j < col_number; j++){
row.push(list_items[i].getValueByIndex(j));
}
data.push(row);
}
SpreadsheetApp.getActiveSheet().getRange(1, 1, data.length, data[0].length).setValues(data);
}
[I do not take credit for writing this!]
So I would like to ask (since this ceases to make much sense to me) is if this is viable code for a Google Apps Script, and if so, how do I implement it to output Sheet data similarly in the same type of format as in the screenshot?
Alternatively, is there a better way to display this Sheet data in Google Sheets?
A totally different alternative would be to use Romain Vialard's "awesome tables" gadget. It works... awesome, and it is really easy to use. Besides, it admits filters, ...

get the form attached to a spreasheet

I'm working with the "new" version of google SS.
I'd like to get the form attached to the spreadsheet I'm in, like this:
function findFormURL() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
return ss.getFormUrl();
}
However, this function does not work yet in the new version.
Anyway,it gives the URL of the form, which is interesting, but I'd like to have the form ID or object so I can then work with it, change some stuff etc. Is that possible ?
This is indeed annoying but there is a possible way to get around this missing feature using the drive search capabilities... I tested it with the code below and it worked.
I agree that this is far from ideal and requires to have a form that has the same unique name as your spreadsheet but it's better than nothing.
function getFormTest() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var nameToSearch = ss.getName();
Logger.log('title contains "'+nameToSearch+'"');
var forms = DriveApp.searchFiles('title contains "'+nameToSearch+'"');
while (forms.hasNext()){
var formDoc = forms.next();
Logger.log(formDoc.getMimeType());
if(formDoc.getMimeType()=='application/vnd.google-apps.form'){
break;
}
}
Logger.log('formDoc = '+formDoc);
var form = FormApp.openById(formDoc.getId());
var items = form.getItems();
for(var i in items){
Logger.log(items[i].getTitle()+' '+items[i].getType());
}
}

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.