The script is triggered when a Google form is submitted and then auto-fills a Google doc.
It worked perfectly before I added var servicesPTY = e.values[117]; and replaced all the placeholders perfectly. But as soon as I add it then the executions indicator show completed but no documents are produced anymore. The document has placeholders that look like this: {{servicesPTY}} {{regNumberPTY}} {{tradingNamePTY}}
And the code looks like this:
function myFormSubmitPTY(e) {
var regNumberPTY = e.values[112];
var taxNumberPTY = e.values[111];
var tradingNamePTY = e.values[113];
var servicesPTY = e.values[117];
var file = DriveApp.getFileById("16OwyBIZAD2pwkuUXZnYSj-9WB6ObGGRXiEjDLa1tcjw");
var folder = DriveApp.getFolderById("1kogpJdxHLwuEhbVyh2oiIgTPH0SNac2m");
var copy = file.makeCopy(tradingNamePTY, folder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
if (type == "PTY (LTD)") {
body.replaceText("{{servicesPTY}}",servicesPTY);
body.replaceText("{{regNumberPTY}}", regNumberPTY);
body.replaceText("{{tradingNamePTY}}", tradingNamePTY);
doc.saveAndClose();
}
}
This works for me:
function testmyFormSubmit() {
var e={values:["one","two","three","four"]};
myFormSubmitPTY(e);
}
var type="PTY (LTD)";//global
function myFormSubmitPTY(e) {
var regNumberPTY = e.values[0];
var taxNumberPTY = e.values[1];
var tradingNamePTY = e.values[2];
var servicesPTY = e.values[3];
var file = DriveApp.getFileById("fileid");
var folder = DriveApp.getFolderById("folderid");
var copy = file.makeCopy(tradingNamePTY, folder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
if (type=="PTY (LTD)") {
body.replaceText("{{servicesPTY}}",servicesPTY);
body.replaceText("{{regNumberPTY}}", regNumberPTY);
body.replaceText("{{tradingNamePTY}}", tradingNamePTY);
doc.saveAndClose();
}
}
file name: three
pattern order:
{{servicesPTY}}
{{regNumberPTY}}
{{tradingNamePTY}}
output order:
four
one
three
I must have deselected the trigger for PTY. When I looked at the stackdriver logs I noticed PTY had none. Must have happened in the early hours of the morning. Thanks though. You guys put me on the right track
Related
Have collected info through a google form to a google sheet. Part of that info is the path to an image stored on drive. I have an app script that replaces key words on a document with the data collected in the sheet. I can get it to replace a piece of text, {{image}} for example with the url stored but I cannot get it to actually put a copy of the image into the document.
Any suggestions.
Code below
// #ts-nocheck
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var timestamp = e.values[0];
var email = e.values[1];
var who = e.values[2];
var employeeorcon = e.values[3];
var location = e.values[4];
var roomorarea = e.values[5];
var type = e.values[6];
var dateofworks = e.values[7];
var imageofcompletedcon = e.values[8];
var checkedoffintext = e.values[9];
var checkname = e.values[10];
var checkco = e.values[11];
var checkeddate = e.values[12];
//file is the template file, and you get it by ID
var file = DriveApp.getFileById("1WcYKvsRFbKK73J-ep66mR9drZyrkWap-x30rO-kVUcM");
//We can make a copy of the template, name it, and optionally tell it what folder to live in
//file.makeCopy will return a Google Drive file object
var folder = DriveApp.getFolderById("1MeU3-N3BMqOPvoaSGr2XassibR2XajdN")
var copy = file.makeCopy(roomorarea + '_' + timestamp, folder);
//Once we've got the new file created, we need to open it as a document by using its ID
var doc = DocumentApp.openById(copy.getId());
//Since everything we need to change is in the body, we need to get that
var body = doc.getBody();
//Then we call all of our replaceText methods
body.replaceText('{{location}}', location);
body.replaceText('{{room}}', roomorarea);
body.replaceText('{{completedby}}', who);
body.replaceText('{{checkedby}}', checkname);
body.replaceText('{{checkeddate}}', checkeddate);
body.replaceText('{{insdate}}', dateofworks);
body.replaceText('{{Empcon}}', employeeorcon);
body.replaceText('{{Type}}', type);
body.replaceText('{{image}}', imageofcompletedcon);
body.replaceText('{{methchk}}', checkedoffintext);
body.replaceText('{{checker}}', checkname);
body.replaceText('{{cocheck}}', checkco);
body.replaceText('{{datecheck}}', checkeddate);
//Lastly we save and close the document to persist our changes
doc.saveAndClose();
}
New to this, but tried insertimage etc, but really a bit beyond me.
I am trying to automate the population of the footer of a google doc that I have with the values that a pop up dialogue gathers from the users when they open the document. The code that I am using can be seen below, however it only works with the footer of the first page, when and only when I activate the option "Different first page". If I de-activate it (because I want the footer to be consistent within the whole document) nothing changes (not even the first page of the document) when I run the script.
The footer looks like this:
Blablbla / ##value1##
Title: “##value2##” - blablabla
The script to substitute value1 and value2 looks like this:
function myFunction() {
// Display a dialog box for each field you need information for.
var ui = DocumentApp.getUi();
var value1Response = ui.prompt('Enter the value1');
var value2Response = ui.prompt('Enter the value2');
var date = new Date();
//Make a copy of the template file
var documentId = DriveApp.getFileById('google document Id').makeCopy().getId();
//Rename the copied file
DriveApp.getFileById(documentId).setName(value2Response.getResponseText() + date);
//Get the document footer as a variable
var footer = DocumentApp.openById(documentId).getFooter();
footer.replaceText('##value1##', value1Response.getResponseText());
footer.replaceText('##value2##', value2Response.getResponseText());
}
This works for me.
function myFunction() {
var doc=DocumentApp.getActiveDocument();
var ui = DocumentApp.getUi();
var value1Response = ui.prompt('Enter the value1');
var value2Response = ui.prompt('Enter the value2');
var value3Response = ui.prompt('Enter FileName');
var date = new Date();
var documentId = doc.getId();
var footer = doc.getFooter();
footer.replaceText('##value1##', value1Response.getResponseText());
footer.replaceText('##value2##', value2Response.getResponseText());
var doc=DocumentApp.openById("Doc Id");
var footer=doc.getFooter();
doc.setName(value3Response.getResponseText());
footer.replaceText('##value1##', value1Response.getResponseText());
footer.replaceText('##value2##', value2Response.getResponseText());
}
I am trying to get the name of the Parent Folder for a spreadsheet that is determined by url and then place the name in a specified cell. Debugging the script below tells me "TypeError: Cannot find function getParents in object Spreadsheet." I have tried every tweak I can think of and read multiple similar articles that may answer my question, but I am unable to understand them. (Forgive the newbie?) Can somebody tell me what I am doing wrong?
function getParent(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("VALUES");
var ll = s.getRange("B11");
var url = ll.getValue();
var driveFile = SpreadsheetApp.openByUrl(url);
var parentFolder = driveFile.getParents();
while (parentFolder.hasNext()) {
var folder = parentFolder.next();
var title = folder.getName();
}
s.getRange("B5").setValue(title);
}
It seems like this code has two small issues which we'll fix to get you up and running on this.
If possible, it is generally a better practice to work with document
IDs rather than URLs. Also, for a reason I'm not aware of, DriveApp
does not have a getFileByURL method. So I have changed your "url" variable for "fileId", and changed the contents of cell B11 to the Id of the file, which is part of the URL itself.
In order to return a Drive File, you should call getFileByID() not on your Spreadsheet itself, but on the DriveApp service.
I've tested the following code and I believe it does what you expect:
function getParent(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("VALUES");
var ll = s.getRange("B11");
var fileId = ll.getValue();
var driveFile = DriveApp.getFileById(fileId);
var parentFolder = driveFile.getParents();
while (parentFolder.hasNext()) {
var folder = parentFolder.next();
var title = folder.getName();
}
s.getRange("B5").setValue(title);
}
Try this:
function getParent(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName("VALUES");
var url=sh.getRange("B11").getValue();
var file=DriveApp.getFileById(url.split('/')[5]);//gets the id out of the url
var parentFolder=file.getParents();
while (parentFolder.hasNext()) {
var folder = parentFolder.next();
var title = folder.getName();
}
sh.getRange("B5").setValue(title);
}
In a Spreadsheet cell I have a link to a Google doc and I want to recuperate it in order to open the Google Doc and modify it. So in my cell I've put this format https://docs.google.com/document/d/1Gb48I...... (without the /edit in the end) and I've tried
var body = '=HYPERLINK("'data[n][COLUMN_URL-1]'+'/edit'")'.getBody();
var body = '=HYPERLINK("'data[n][COLUMN_URL-1]'+'/edit'")'.getBody();
// this one works but I want to use data[n][COLUMN_URL-1] because I have several Google Docs links
var body = DocumentApp.openByUrl('https://docs.google.com/document/d/1Gb48IXos......../edit').getBody();
if(body){
//edit the Google doc
If you have ideas what to do thank you because with the concatenation of the /edit(3rd line of code) it works
Edit: The cell is not formatted(hyperlinked)/formula i have only the https://...
Edit 2: I've tried with a code from Suhail Ansari thank you but I have an error that the document is missing and I don't have nothing for the logs if you have others ideas:
var COLUMN_URL = 10 ;
function getIdFrom(url) {
var id = "";
var parts = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
if (url.indexOf('?id=') >= 0){
id = (parts[6].split("=")[1]).replace("&usp","");
return id;
} else {
id = parts[5].split("/");
//Using sort to get the id as it is the longest element.
var sortArr = id.sort(function(a,b){return b.length - a.length});
id = sortArr[0];
return id;
}
}
var sheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(SHEET_NAME);
var numRows = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var data = sheet.getRange(1,1,numRows,lastColumn).getDisplayValues();
for(n=1;n < data.length;n++) {
var URL =data[n][COLUMN_URL-1];
Logger.log('The URL ',URL);
var id = getIdFrom(URL);
Logger.log('The ID ',id);
var body = DocumentApp.openById(id).getBody();
if(body)
{......//edit Google Doc
This is the 10 column with the URLs from the Google Docs
In fact I have docs.google.com/open?id=1qo0B_HCbjcBrYyJ ... as URL for the others rows I tried to do by hand for 3rd one as you can see in the picture
Edit 3: So I am very confused in this moment because the column I have in the spreadsheet commes from a loop where I put the URL of the Google Docs in the cell like this : var trange = sheet.getRange.. trange.setValue(doc.getUrl()); and now if i look at the table i have the links in this format
https://docs.google.com/open?id=1RYRVotAq6IOz5tys1krnENfgN_pU0KYuUzR24i
so now if i want to get back the Google Doc I have the following :
// var body = DocumentApp.openByUrl('https://docs.google.com/open?id=1Xb4QjiWwpn2TJ8-9kkIhU6m1rgmb48g6xYVopN').getBody();
//var body = DocumentApp.openByUrl('https://docs.google.com/1Xb4QjiWwpn2TJ8-9kkIhU6m1rgmb48g6xYVopN/edit').getBody();
var body = DocumentApp.openByUrl('https://docs.google.com/document/d/1Xb4QjiWwpn2TJ8-9kkIhU6m1rgmb48g6xYVopN/edit').getBody();
only the 3rd one works.Where I am doing wrong? Because I want to
for(n=1;n < data.length;n++) {... make a loop for and var URL =
data[n][COLUMN_URL-1];
You could add some code for getting the Doc ID from the URL and then open the doc by using
DocumentApp.openById(id);
Here is a link to do that.
A sample code below with help from the above linked answer:
function myFunction() {
var URL = SpreadsheetApp.getActiveSheet().getRange('A1').getValue();
var id = getIdFrom(URL);
var doc = DocumentApp.openById(id);
var body = doc.getBody();
Logger.log(body.getText());
}
function getIdFrom(url) {
var id = "";
var parts = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
if (url.indexOf('?id=') >= 0){
id = (parts[6].split("=")[1]).replace("&usp","");
return id;
} else {
id = parts[5].split("/");
//Using sort to get the id as it is the longest element.
var sortArr = id.sort(function(a,b){return b.length - a.length});
id = sortArr[0];
return id;
}
}
Demo Google Sheet
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();
}
`