I'm trying to pre fill the date in google form. so It will put the date of the day it filled as default.
I tried using the TODAY() function in google sheets . so i change the url to get the date from cell in google sheets . works for everything except the Date..
https://docs.google.com/forms/d/e/1FAIpQLSf7cdT34eHp-GXagq3DsnxX1MD_c-G6lbF6yFWOMnUvtPYUUQ/viewform?entry.178275308=**&A6&**
Any idea how can i do it in the simplest way?
Deploy your script as a Web App
Publish your Apps Script as a Web App and provide the URL of the web deployment to the users
Write your code inside a doGet() function, so it gets evaluated every time a user open the link
Get the current date with new Date() and pass it as an itemResponse to a prefilled Form
Create a redirection to the URL to the prefilled form with the Java Script method window.top.location.href inside of <script> </script> tags and return it with HtmlService
// will be automatically run every time the user opens the URL of the web deployment
function doGet(){
//open your form
var form = FormApp.openById('1Zs5Wo0wS9esNkcq8ztOZmQs3f5NrO7hgJ_0fYk262z4');
//get the questions
var questions = form.getItems();
//get the question where you want to prefill the date as an answer, e.g. first question
var question1=questions[0];
//get the current date
var time=Utilities.formatDate(new Date(), "GMT+2", "dd-MM-yyyy");
// prefill form with current date
var prefilledTime=form.createResponse().withItemResponse(question1.asTextItem().createResponse(time));
// Get the link to the prefilled form
var URL=prefilledTime.toPrefilledUrl();
// redirect to the prefilled form URL dynamically created above
return HtmlService.createHtmlOutput("<script>window.top.location.href=\"" + URL + "\";</script>");
}
If you just want the date the Form is submitted, Google Forms provides this automatically in it's Timestamp.
If you want to pre-fill a date from an existing spreadsheet, then provided you obey Google's date-format, you can use the URL approach (months & days must be 2 digits i.e. "01" not "1").
=substitute('Sheet_with_Form_Link'!$A$1,"2099-01-01",text(Sheet_with_date!A1,"yyyy-mm-dd"))
WhereSheet_with_Form_Link'!$A$1 is a cell in a Sheet in a Google SpreadSheet containing the URL obtained via 'Get Prefilled Link'
"2099-01-01" is the data you Pre-filled into the Form whilst using 'Get Pre-filled Link'
Sheet_with_date!A1 is a cell in a Sheet in a Google SpreadSheet containing your desired date e.g. one of
=today()
1920/03/26
17Oct2002
I took the code from ziganotschka as base, but I had to make some changes, maybe it helps somebody:
function doGet(){
//open your form open by URL
var form = FormApp.openByUrl('https://docs.google.com/forms/d/1M-zgHyDOz2ob5StkwIoDCShJ9tePw-I5TGhdx/prefill')
//get the questions
var questions = form.getItems();
//get the question where you want to prefill the date as an answer, e.g. first question
var question1=questions[0];
//get the current date
var time=new Date();
// prefill form with current date
var prefilledTime=form.createResponse().withItemResponse(question1.asDateItem().createResponse(time));
// Get the link to the prefilled form
var URL=prefilledTime.toPrefilledUrl();
// redirect to the prefilled form URL dynamically created above
return HtmlService.createHtmlOutput("<script>window.top.location.href=\"" + URL + "\";</script>");
}
And when you're done, don't forget to Publish -> Deploy as a Web App...
Related
I have an existing Google Form in which there is a TextItem with a title "Which location was this performed at?".
Whenever the form is loaded (opened), I need to set a location value (loc) to this existing textbox and show it to the user.
function populateMemberIds(loc){
var form = FormApp.openById(formUrl);
var questions = form.getItems();
for (var i=0; i<questions.length; i++){
if(questions[i].getTitle()=="Which location was this performed at?"){
var textItem = questions[i].asTextItem();
//I get stuck here
}
}
I already setup the openForm trigger which allows to run the populateMemberIds function to be run on each form load. Again, what I need is to change the value of the "Your answer" section of the text item with the location value (loc).
I would appreciate any help.
You can't modify a form response filled by a user, you can either create a form response programmatically or edit a response after being submitted. The onOpen form trigger runs when someone opens the form to edit it rather than answer it [1]:
This event does not occur when a user opens a form to respond, but
rather when an editor opens the form to modify it.
Moreover, triggers functions comes with an event parameter already defined [1] so you can't set your own function parameter(s) as you're doing with your loc parameter.
EDIT
You can programmatically create and submit a form response [2], from which you can also get a URL with a prefilled form for the user to finish [3].
function populateMemberIds(loc){
var form = FormApp.openById("[FORM-ID]");
var questions = form.getItems();
var response = form.createResponse();
for (var i=0; i<questions.length; i++){
if(questions[i].getTitle()=="title form"){//Which location was this performed at?"){
var textItem = questions[i].asTextItem();
var itemResponse = textItem.createResponse(loc) ;
response.withItemResponse(itemResponse);
}
}
//Submit programmatically the form response
response.submit();
//URL with prefilled form response
Logger.log(response.toPrefilledUrl());
}
function test () {
populateMemberIds("US");
}
[1] https://developers.google.com/apps-script/guides/triggers/events#google_forms_events
[2] https://developers.google.com/apps-script/reference/forms/form-response
[3] https://developers.google.com/apps-script/reference/forms/form-response#toprefilledurl
The onOpen Google Apps Script triggers (simple and installable) for Google Forms are executed only when the form is opened in the form editor, not when the form is opened by using the view / edit response links.
There are two ways to "prefill" a Google Forms response:
Use the prefilled response URL
Create a response programmatically, then use the editResponseUrl
Related
Is it possible to 'prefill' a google form using data from a google spreadsheet?
How to generate a pre-filled form URL for Google Form
I have multiple Google Forms with identical response fields inputting into a certain Google Sheets, and there is no way of telling them apart other than their names and descriptions. Using Google Apps Script, is there any way I can add the name and/or description of the Google Form into the Sheets, along with everything that is normally added to the Sheets? I did a bit of research about something with "source" but I have no idea how to implement it.
Thanks!
You can accomplish this by going to your form in edit mode selecting "Script Editor" and pasting the below code into the script. You will need to click on the "Trigger" button (looks like a clock, if you can't find it follow here https://developers.google.com/apps-script/guides/triggers/installable). Click Add Trigger and select event type "On Form Submit"
function writeFormTitle(){
//Get Form
var form = FormApp.getActiveForm();
//Get Form's Title
var formTitle = form.getTitle();
//Get the Write To Spreadsheet ID where the data will be written to
var destinationSpreadsheet = form.getDestinationId();
//Activate that Spreadsheet by the destinationSpreadsheet ID
var sheet = SpreadsheetApp.openById(destinationSpreadsheet).getActiveSheet();
//Find the last column and row
var writeToColumn = sheet.getLastColumn()+1;
var writeToRow = sheet.getLastRow();
//Write title to Spreadsheet next to submitted data.
sheet.getRange(writeToRow, writeToColumn, 1, 1).setValue(formTitle);
}
I am creating a submission document through Google Forms & Google Spreadsheets. I have created a form that emails data for approval. The email includes a URL link which is contains a unique ID. This link is connected to a second form for approval/denial of the submission. I am having difficulty getting this unique ID linked to the approval/denial process form. I believe I need to reference this ID so that it will approve the correct entry in my spreadsheet. Can someone point me in the right direction on how to reference my ID through my second form or give me another idea on how to do this?
var d = new Date();
var ID = d.getTime();
approvalLink = "docs.google.com/forms";
approvalLink = approvalLink + "?id=" + ID
Unfortunately, there is no way to do this on the live forms. Form Script code doesn't run until after the form is submitted.
However you could generate a pre-filled form url for the 2nd approval/denial form that fills in a question with your ID (PS. Think about using a UUID instead of timestamp).
var form = FormApp.openById("2nd Form ID");
var response = form.createResponse();
var items = form.getItems();
var item = items[0].asTextItem();
var itemResponse = text.createResponse('my text');
response.withItemResponse(itemResponse);
var url = response.toPrefilledUrl();
You use this url to present a form with that questions that already has your ID filled in. Then when your 2nd form is submitted you can reference that question.
The url this generates will end in something like: ?entry.2623445234=SomeText.
I have a Google Spreadsheet that a form is linked to and all form responses are stored in. What I am trying to find is the ID of the FORM itself. I tried this but this does not work..
(I'm running the following code FROM The script editor IN the spreadsheet that the form is linked to.)
function getID()
{
var form = FormApp.getActiveForm();
var formID = form.getId();
Logger.log(formID);
}
That returns NULL since the script is container-bound to the spreadsheet itself. Is there any other way to get the ID of the linked form or even the URL of the linked form?
I can MANUALLY get it by doing the following from the Spreadsheet.
Form > Edit form
This will show me the URL.
IF I knew the NAME of the form I could get it by name using the DriveApp.getFilesByName(), iterate through it and then use the File.getId() but I don't necessarily know the name.
Any ideas?
To avoid parsing the url, the safest way would be:
Logger.log( (FormApp.openByUrl(SpreadsheetApp.getActiveSpreadsheet().getFormUrl())).getId() );
or long hand version:
function logFormId_LongHand(){
var formURL = SpreadsheetApp.getActiveSpreadsheet().getFormUrl();
var form = FormApp.openByUrl(formURL);
var formId = form.getId();
Logger.log( formId );
}
To get the form object in a spreadsheet app script I use the following function:
function getLinkedForm(){
return FormApp.openByUrl( SpreadsheetApp.getActiveSpreadsheet().getFormUrl() );
}
To anyone else who stumbles upon this: The new spreadsheets allow this. I've tried it already and it works for me. Here is how I get the ID:
var formUrl = SpreadsheetApp.getActiveSpreadsheet().getFormUrl();
var formID = formUrl.match(/[-\w]{25,}/);
I got the regex from this question: Easiest way to get file ID from URL on Google Apps Script
Hope this helps.
If you only want the Form ID for the attached Form, and don't need to keep the Form URL for any reason, this one-liner should suffice:
var formID = SpreadsheetApp.getActiveSpreadsheet().getFormUrl().match(/\/d\/(.{25,})\//)[1];
Yes.
It would be a script like this that would be ran from within the spreadsheet:
function getFormUrl()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formUrl = ss.getFormUrl();
Logger.log(formUrl);
}
However, if you try and run this in the new spreadsheets you receive this error message:
The api method 'getFormUrl' is not available yet in the new version of Google Sheets.
So, until they add support it will only work in older versions.
You can also find out / connect to the original form from the "Help" menu. Type form and then click "Edit Form." It will locate the original form. This was helpful when a search in drive was unsuccessful through the name of the form (???). So if you need the original editable form for whatever reason, can't find it, and have the linked Sheets doc, then you can now backtrack and go from there. :)
I have a problem to update the values on the fields of a form. I cannot update the date in its respective text box and the spreadsheet that receives the values only shows the values after i refresh the page (both Ui and spreadsheet are embbeded in the Google Sites)
The var date, explicited as a global var
var date=new Date();
The TextBox
var DataTextBox=app.createTextBox().setId('Data').setName('Data').setValue(date).setReadOnly(true).setText(Utilities.formatDate(date, 'GMT -02:00', 'dd/MM/yyyy HH:mm:ss'))
The handler
var clickHandler2=app.createServerHandler('updateAll');
button.addClickHandler(clickHandler2);
clickHandler2.addCallbackElement(panel);
The function (have others fields updated, but they are working fine)
function updateAll(e) {
//DataTextBox.setValue(date).setReadOnly(true).setText(Utilities.formatDate(date, 'GMT -02:00', 'dd/MM/yyyy HH:mm:ss'));
var newDate=date;
app.getElementById("Data").setValue(newDate);
app.getElementById("TicketId").setValue("");
app.getElementById("TicketType").setValue(TicketTypeArray[0]);
app.getElementById("DemandedBy").setValue(DemandedByArray[0]);
app.getElementById("Analyst").setValue(AnalystArray[0]);
app.getElementById("Description").setValue("");
}
How do i update the date field and how can i make the spreadsheet shows the last data submited by the form?
You have to add 'return app' in order to show updated fields in gui.