Moving a created file from template to folder with google script - google-apps-script

I need help with a google script that I have written which takes the responses from a google form and transfers the responses from the response spreadsheet into a google doc template. The script that I have written now has the proper trigger needed to create the google doc that I want to create but I do not know what needs to be added to have the new document save in a folder that is a created folder in my drive NOT just the my drive folder. Any help would be appreciated. Below is the script I already have written.
// Get template from Google Docs and name it
var docTemplate = "1NPiAbaB2wciyJUhJE4AvxZ1dCB_Uu5kf24eSxLC_BfI";
var docName = "AttrVaRepairTemp";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var timestamp = e.values[0];
var contact_name = e.values[1];
var company_name = e.values[2];
var phone_number = e.values[3];
var email_address = e.values[4];
var contact_address = e.values[5];
var item_type = e.values[6];
var manufacturer = e.values[7];
var model_number = e.values[8];
var serial_number = e.values[9];
var description = e.values[10];
var symptoms = e.values[11];
var accepted_by = e.values[12];
var warranty = e.values[13];
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy('Repair Form- '+contact_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keytimestamp', timestamp);
copyBody.replaceText('keyacceptedby', accepted_by);
copyBody.replaceText('keycontactname', contact_name);
copyBody.replaceText('keycompanyname', company_name);
copyBody.replaceText('keycontactphone', phone_number);
copyBody.replaceText('keycontactemail', email_address);
copyBody.replaceText('keycontactaddress', contact_address);
copyBody.replaceText('keymanufacturer', manufacturer);
copyBody.replaceText('keymodel', model_number);
copyBody.replaceText('keyserial', serial_number);
copyBody.replaceText('keyitemtype', item_type);
copyBody.replaceText('keywarranty', warranty);
copyBody.replaceText('keydescription', description);
copyBody.replaceText('keysymptoms', symptoms);
// Save and close the temporary document
copyDoc.saveAndClose();

(Copied Serge Insas answer from a similar question elsewhere)
See this old post : (https://stackoverflow.com/questions/13532114/google-apps-script-addtofolder-adds-to-folder-and-mydrive/13536275#13536275)
code is as follows :
function moveFromRoot(){
folder=DocsList.createFolder("MyFolder");
var file=DocsList.createFile('File2', 'Empty');
file.addToFolder(folder);
file.removeFromFolder(DocsList.getRootFolder());
}
but as mentioned in the answer, you can create the file using the folder object itself (folder.createFile('blabla'))

Related

App Script to insert an image from google drive to a google doc

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.

How can I automate the adding of an image to a Google Doc from a url to a Drive file located in Google Sheets?

I have created a script to Auto Fill a Google Doc from a Google Form Submission (via Google Sheets) but I am struggling to auto fill an image into the Google Doc from a Drive url created in the Google Sheet (via an IF formula).
Essentially the Google doc is designed to simplify some admin work. The person submitting the Form chooses who the document is being written by and the digital signature of that person should be auto populated.
Here is what I have tried. Everything works well except the replaceTextToImage function - I am lost! Thanks in advance for your help.
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
// #ts-ignore
var timestamp = e.values[0];
var COMPANYNAME = e.values[2];
var CONTACTNAME = e.values[7];
var DATE = e.values[9];
var STREET = e.values[3];
var TOWN = e.values[4];
var POSTCODE = e.values[5];
var COUNTRY = e.values[6];
var PURPOSE = e.values[10];
var JOBTITLE = e.values[8];
var DIRECTOR = e.values[11];
var ADDRESS_2 = e.values[12];
//file
var file = DriveApp.getFileById('1Dd78JKEHDr6JY3b3N9zxNHu6_7tK3-NSJPIdNVp_SNQ');
//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('1zyodJvnwabTRM7horzM0HRBw04b0IxbI')
var copy = file.makeCopy(COMPANYNAME + ',' + DATE, 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('{{COMPANYNAME}}', COMPANYNAME);
body.replaceText('{{CONTACTNAME}}', CONTACTNAME);
body.replaceText('{{DATE}}', DATE);
body.replaceText('{{STREET}}', STREET);
body.replaceText('{{ADDRESS_2}}', ADDRESS_2);
body.replaceText('{{TOWN}}', TOWN);
body.replaceText('{{POSTCODE}}', POSTCODE);
body.replaceText('{{COUNTRY}}', COUNTRY);
body.replaceText('{{PURPOSE}}', PURPOSE);
body.replaceText('{{JOBTITLE}}', JOBTITLE);
body.replaceText('{{DIRECTOR}}', DIRECTOR);
//function embedding image to document with a specified size
var replaceTextToImage = function(body, searchText, fileId) {
var width = 600; // Please set this.
var blob = DriveApp.getFileById('1Dd78JKEHDr6JY3b3N9zxNHu6_7tK3-NSJPIdNVp_SNQ').getBlob();
var r = body.findText(searchText).getElement();
r.asText().setText("");
var img = r.getParent().asParagraph().insertInlineImage(0, blob);
var w = img.getWidth();
var h = img.getHeight();
img.setWidth(width);
img.setHeight(width * h / w);
}
// Get the image fileID
var image = e.values[13]; // xx being the row number in which the link to the uploaded image is
var imageID = String(image).split("=")[1]; //gives you the fileID of the uploaded image
// Use the function replaceTextToImage
replaceTextToImage(body,'{{imageID}}', imageID); // replaces the {{image}} tag with the uploaded image
//Lastly we save and close the document to persist our changes
doc.saveAndClose();
}
So I think the problematic line in the code is this one:
var blob = DriveApp.getFileById('1Dd78JKEHDr6JY3b3N9zxNHu6_7tK3-NSJPIdNVp_SNQ').getBlob();
Please replace it with the following:
var blob = DriveApp.getFileById(fileId).getBlob();
What was happening is that since fileId is actually a defined parameter of the function replaceImageToText, removing it from inside the function and replacing it with an actual ID of a file resulted in the file with ID 1Dd78JKEHDr6JY3b3N9zxNHu6_7tK3-NSJPIdNVp_SNQ being considered as the image every single time the function was called instead of the image that was uploaded through your form.
I tried this out myself and it worked with a random image I uploaded to my drive. Please try this fix and see if it works for you too. Hope this helps!

Google Form Document Automation

I have been receiving 2 main issues back upon a google form submission- the first being that the e.values I have set up cannot be read and the second that the Doclist is not defined. I have already set the triggers for the e.values and tried using e.namedvalues as well. I would like to eliminate the second issue by sending a doc and not a pdf to the form submitter, however it is most important that I get the first issue addressed first.
I am using framework that I have modified to fit my own documents, so that may be where I am encountering issues.
// G. Hopper
// Subcontract Generator
// Get template from Google00 Docs and name it
var docTemplate = "16bdl2myh7f0ywlxmf3iimq4Nz6-j8VTs7hkMbshRjp0";
var docName = "Subcontract";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var sub_name = e.namedValues["Subcontractor Name"].toString();
var sub_address = e.namedValues["Subcontractor address"].toString();
var proj_name = e.namedValues["Project Name"].toString();
var own_name = e.namedValues["Owner Name"].toString();
var own_address = e.namedValues["Owner Address"].toString();
var designer = e.namedValues["Design Firm"].toString();
var design_address = e.namedValues["Design Firm Address"].toString();
var proj_address = e.namedValues["Project Address"].toString();
var scope = e.namedValues["Scope of work"].toString();
var date_bid = e.namedValues["Date on bid"].toString();
var sub_value = e.namedValues["Subcontract Value"].toString();
var date_pay = e.namedValues["Date of the month pay applications are due"].toString();
var email = e.namedValues["Your email address"].toString();
var day = e.namedValues["Day"].toString();
var month_year = e.namedValues["Month and Year"].toString();
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy('Subcontract for '+sub_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keySubName', sub_name);
copyBody.replaceText('keySubAddress', sub_address);
copyBody.replaceText('keyProject', proj_name);
copyBody.replaceText('keyOwner', own_name);
copyBody.replaceText('keyOwnAddress', own_address);
copyBody.replaceText('keyDesigner',designer);
copyBody.replaceText('keyDesignAddress', design_address);
copyBody.replaceText('keyProjAdd', proj_address);
copyBody.replaceText('keyScope', scope);
copyBody.replaceText('keyBidDate', date_bid);
copyBody.replaceText('KeySubValue', sub_value);
copyBody.replaceText('keyPayApp', date_pay);
copyBody.replaceText('keyDay', day);
copyBody.replaceText('keyMonthDay', month_year);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = 'Subcontract'
var body = "Here is your subcontract for " + sub_name + "";
MailApp.sendEmail(email, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DocsList.getFileById(copyId).setTrashed(true);
}

Broken Submission Form

I have a survey form that we use for our clients. It is a series of multiple choices questions, and a few text field entries. At the end, you click "submit" and an email is sent containing all the responses to our Quality Manager. Recently, the form stopped working, and I found many people who successfully fixed the issue by changing docslist to DriveApp. However, now I am getting the error:
TypeError: Cannot read property "response" from undefined. (line 10, file "")
The entire code reads as follows:
/// Get template from Google Docs and name it
var docTemplate = "1vCv-NR9c2G5q6f6EJ2CL4zAEQe_37OE7MgsSLTIKheY"; // *** replace with your template ID ***
var docName = "ClientSurvey";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
Logger.log(Utilities.jsonStringify(e));
var formResponses = e.response.getItemResponses();
Logger.log(formResponses[0].toString());
var service_type = formResponses[0].getResponse().toString();
var email_address = "notrealaddress#ntainc.com, notrealaddress#ntainc.com"
//var service_type = e.values[0];
var d = new Date();
var timeStamp = d.getTime();
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+timeStamp)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyServiceType', service_type);
for (var i = 0; i < formResponses.length; i++) {
copyBody.appendParagraph(formResponses[i].getItem().getTitle().toString());
copyBody.appendParagraph(formResponses[i].getResponse().toString());
copyBody.appendParagraph(" ");
}
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "Customer Survey";
var body = "Here is a New Customer Survey";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DriveApp.getFileById(copyId).setTrashed(true);
}
Please help!
This is more of a comment than an answer, but I dont have enough rep to comment yet.
Check your trigger, there is two types of FormSubmit triggers, one for sheets and one for forms, if you are using the wrong one that could be what is causing your issues.

How do I create a form letter where some text is not printed if a field on a Google form is left blank

My company recently switched to Google Apps and I am trying to covert Word and Excel docs to Google Docs. I am completely new to Google App Script and am stuck. I have been searching for a few days a have not found what I am looking for.
I have a Google form that is emailed to a sales person. After it is completed the Google spreadsheet is updated and then sends a form letter to the sales person summarizing their input. Some of the fields on the form are optional. How do I create a template that does not include some of the form letter text if the question was left unanswered?
For example, one of the optional fields is for a customer website address, if the customer does not have a website I don’t want the words website to show up on the form.
If anyone has any “For Dummies” instructions on how to do this I would really appreciate it.
Thanks.
Here is what I have so far:
// Business Review Report
// Get template from Google Docs and name it
var docTemplate = "1gRk2irahyW2Sf4pQMTDykXlMQqYgbe1Ba1vkh20KDYo";
var docName = "Business Review";
// When Form Gets submitted
function onFormSubmit (e) {
//Get information from form and set as variables
var variablename = "static entry or form value"
var email_address = e.values[1];
var Business_Name = e.values[2];
var Business_Address = e.values[3];
var Phone_Number = e.values[4]
var Email_address = e.values[5];
var Website = e.values[6];
var Participants = e.values[7];
var Agenda = e.values[8];
var Updates_and_Progress1 = e.values[9];
var Updates_and_Progress2 = e.values[10];
var Updates_and_Progress3 = e.values[11];
var Current_Issues1 = e.values[12];
var Current_Issues2 = e.values[13];
var Current_Issues3 = e.values[14];
var Next_Steps = e.values[15];
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+ Business_Name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyBusinessName', Business_Name);
copyBody.replaceText('keyBusinessAddress', Business_Address);
copyBody.replaceText('keyPhoneNumber', Phone_Number);
copyBody.replaceText('keyEmailaddress', email_address);
copyBody.replaceText('keywebsite', Website);
copyBody.replaceText('keyParticipants', Participants);
copyBody.replaceText('keyAgenda', Agenda);
copyBody.replaceText('keyUpdatesAndProjects1', Updates_and_Progress1);
copyBody.replaceText('keyUpdatesAndProjects2', Updates_and_Progress2);
copyBody.replaceText('keyUpdatesAndProjects3', Updates_and_Progress3);
copyBody.replaceText('keyCurrentIssues1',Current_Issues1);
copyBody.replaceText('keyCurrentIssues2', Current_Issues2);
copyBody.replaceText('keyCurrentIssues3', Current_Issues3);
copyBody.replaceText('keyNextSteps', Next_Steps);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "Business Review";
var body = "Business Review for " + Business_Name + "";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DocsList.getFileById(copyId).setTrashed(true);
}
It works, but the resulting PDF also includes text for the unfilled fields like CurrentIssues2.
I am not sure if I am explaining this clearly so please respond with any questions and I will try to be more clear.
Thanks again,
Lisa
Your form questions apparently have default values that you don't want in your form letter. You can check for those defaults and replace them with something more suitable, such as a blank string.
...
// If website question was not answered, leave blank
var Website = e.values[6];
if (Website == 'website') Website = '';
...
This alternative uses the Ternary or Conditional Operation, and is more compact:
...
// If website question was not answered, leave blank
var Website = (e.values[6] == 'website') ? '' : e.values[6];
...