Saving files to a specified folder - google-apps-script

I have a script that uses data from a form and key values to fill out a document and convert the document to a pdf. Now I am having trouble getting that pdf to save to a specified folder in my google drive.
function myfunction(e) {
var docTemplate = "1pKwW-RcjaVV8xmm00hWDx1u2QxzQwaSjPJwVY2ux2nI";
var docName = "Form";
var full_name = "Form";
var targetFolderId = "Work Order Forms";
function onFormSubmit(e) {
var Assign_To_1 = e.value[2];
var Assign_To_2 = e.value[3];
var Timestamp = e.values[0];
var Date_Of_Request = e.value[1];
var Requested_By = e.value[7];
var Principal_Approval = e.value[5];
var Urgency = e.value[4];
var Building_Room_Number = e.value[10];
var Description_of_Work_To_Be_Done = e.value[6];
var Parts_Needed = e.value[8];
var Parts_In_Stock = e.value[9];
var Invoice_Number = e.value[10];
var Completed_Signature = e.value[22];
var Incomplete_Signature = e.value[23];
var On_Hold_Signature = e.value[24];
var Estimated_Hours = e.value[14];
var Number_Of_Employees_To_Complete = e.value[18];
var Budget = e.value[11];
var Follow_Up = e.value[16];
var Overtime = e.value[15];
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+full_name)
.getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('KeyAssignedTo1',Assign_To_1);
copyBody.replaceText('KeyAssignedTo2',Assign_To_2);
copyBody.replaceText('KeyTimestamp',Timestamp);
copyBody.replaceText('KeyDateOfRequest',Date_Of_Request);
copyBody.replaceText('KeyRequestedBy',Requested_By);
copyBody.replaceText('KeyPrincipalApproval',Principal_Approval);
copyBody.replaceText('KeyUrgency',Urgency);
copyBody.replaceText('KeyBuildingRoomNumber',Building_Room_Number);
copyBody.replaceText('KeyDescriptionofWorkToBeDone',Description_of_Work_To_Be_Done);
copyBody.replaceText('KeyPartsNeeded', Parts_Needed);
copyBody.replaceText('KeyPartsInStock', Parts_In_Stock);
copyBody.replaceText('KeyInvoiceNumber', Invoice_Number);
copyBody.replaceText('KeyCompletedSignature', Completed_Signature);
copyBody.replaceText('KeyIncompleteSignature', Incomplete_Signature);
copyBody.replaceText('KeyOnHoldSignature', On_Hold_Signature);
copyBody.replaceText('KeyEstimatedHours', Estimated_Hours);
copyBody.replaceText('KeyNumberOfEmployeesToComplete', Number_Of_Employees_To_Complete);
copyBody.replaceText('KeyBudget', Budget);
copyBody.replaceText('KeyFoolowUp', Follow_Up);
copyBody.replaceText('KeyOvertime', Overtime);
copyDoc.saveAndClose();
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
var doc = DocsList.getFileById(copyId);
function moveFileToFolder(fileId, targetFolderId) {
var targetFolder = DocsList.getFolderById(targetFolderId);
var file = DocsList.getFileById(fileId);
file.addToFolder(targetFolder);
}}}
Here is my code so far. Everything is working except the saving in a specified folder part. Please help I am very new to this.

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

We're sorry, a server error occurred. Please wait a bit and try again. (line 63, file "Code")

Thank you in advance for helping.
I am trying to convert the most recent submitted data from Google Form/Google sheets to a "template" Google doc. Basically, when a user submit a form, it will convert the data from Google Sheet and create a new Google Doc.
Side note: Im not really a coder.. I found the base script online and tried to modified it accordingly. I would greatly appreciate a step by step if possible?
AGAIN, THANK YOU SO MUCH
function createDocument() {
var headers = Sheets.Spreadsheets.Values.get('SHEET-ID', 'A1:AU1');
var tactics = Sheets.Spreadsheets.Values.get('SHEET-ID', 'A2:AU2');
var templateId = 'DOCTEMPLATE-ID';
for(var i = 0; i < tactics.values.length; i++){
var Fclient = tactics.values[i][0];
var Lclient = tactics.values[i][1];
var birthday = tactics.values[i][2];
var profession = tactics.values[i][3];
var email = tactics.values[i][4];
var phone = tactics.values[i][5];
var whatsapp = tactics.values[i][6];
var preferredcontact = tactics.values[i][7];
var UScitizen = tactics.values[i][8];
var Ocitizen = tactics.values[i][9];
var Tsapre = tactics.values[i][10];
var Pairplane = tactics.values[i][11];
var Photelamen = tactics.values[i][12];
var FFlyer = tactics.values[i][13];
var hotelloy = tactics.values[i][14];
var vistedcountries = tactics.values[i][15];
var smoke = tactics.values[i][16];
var allergies = tactics.values[i][17];
var Othermed = tactics.values[i][18];
var addANOTHER = tactics.values[i][19];
var emergencyname = tactics.values[i][20];
var emergencyphone = tactics.values[i][21];
var emergencyrelation = tactics.values[i][22];
var emergencyname2 = tactics.values[i][23];
var emergencyphone2 = tactics.values[i][24];
var emergencyrelation2 = tactics.values[i][25];
var comptravelmag = tactics.values[i][26];
var secondaryFname = tactics.values[i][27];
var secondaryLname = tactics.values[i][28];
var secondarybirthday = tactics.values[i][29];
var secondaryprofession = tactics.values[i][30];
var secondaryemail = tactics.values[i][31];
var secondaryphone = tactics.values[i][32];
var secondarywhatsapp = tactics.values[i][33];
var secondarypreferredcontact = tactics.values[i][34];
var secondaryUScitizen = tactics.values[i][35];
var secondaryOcitizen = tactics.values[i][36];
var secondaryTsapre = tactics.values[i][37];
var secondaryPairplane = tactics.values[i][38];
var secondaryPhotelamen = tactics.values[i][39];
var secondaryFFlyer = tactics.values[i][40];
var secondaryhotelloy = tactics.values[i][41];
var secondaryvistedcountries = tactics.values[i][42];
var secondarysmoke = tactics.values[i][43];
var secondaryallergies = tactics.values[i][44];
var secondaryOthermed = tactics.values[i][45];
var timestamp = tactics.values[i][46];
//Make a copy of the template file
var documentId = DriveApp.getFileById(templateId).makeCopy().getId();
//Rename the copied file
DriveApp.getFileById(documentId).setName('Basic Information: ' + Lclient + 'test');
//Get the document body as a variable.
var body = DocumentApp.openById(documentId).getBody(); **ERROR HERE**
//Insert the supplier name
body.replaceText('{{Fcilent}}', Fclient);
body.replaceText('{{Lcilent}}', Lclient);
body.replaceText('{{birthday}}', birthday);
body.replaceText('{{profession}}', profession);
body.replaceText('{{email}}', email);
body.replaceText('{{phone}}', phone);
body.replaceText('{{whatsapp}}', whatsapp);
body.replaceText('{{preferredcontact}}', preferredcontact);
body.replaceText('{{UScitizen}}', UScitizen);
body.replaceText('{{Ocitizen}}', Ocitizen);
body.replaceText('{{Tsapre}}', Tsapre);
body.replaceText('{{Pairplane}}', Pairplane);
body.replaceText('{{Photelamen}}', Photelamen);
body.replaceText('{{FFlyer}}', FFlyer);
body.replaceText('{{hotelloy}}', hotelloy);
body.replaceText('{{vistedcountries}}', vistedcountries);
body.replaceText('{{smoke}}', smoke);
body.replaceText('{{allergies}}', allergies);
body.replaceText('{{Othermed}}', Othermed);
body.replaceText('{{addANOTHER}}', addANOTHER);
body.replaceText('{{emergencyname}}', emergencyname);
body.replaceText('{{emergencyphone}}', emergencyphone);
body.replaceText('{{emergencyrelation}}', emergencyrelation);
body.replaceText('{{emergencyname2}}', emergencyname2);
body.replaceText('{{emergencyphone2}}', emergencyphone2);
body.replaceText('{{emergencyrelation2}}', emergencyrelation2);
body.replaceText('{{comptravelmag}}', comptravelmag);
body.replaceText('{{secondaryFname}}', secondaryFname);
body.replaceText('{{secondaryLname}}', secondaryLname);
body.replaceText('{{secondarybirthday}}', secondarybirthday);
body.replaceText('{{secondaryprofession}}', secondaryprofession);
body.replaceText('{{secondaryemail}}', secondaryemail);
body.replaceText('{{secondaryphone}}', secondaryphone);
body.replaceText('{{secondarywhatsapp}}', secondarywhatsapp);
body.replaceText('{{secondarypreferredcontact}}', secondarypreferredcontact);
body.replaceText('{{secondaryUScitizen}}', secondaryUScitizen);
body.replaceText('{{secondaryOcitizen}}', secondaryOcitizen);
body.replaceText('{{secondaryTsapre}}', secondaryTsapre);
body.replaceText('{{secondaryPairplane}}', secondaryPairplane);
body.replaceText('{{secondaryPhotelamen}}', secondaryPhotelamen);
body.replaceText('{{secondaryFFlyer}}', secondaryFFlyer);
body.replaceText('{{secondaryhotelloy}}', secondaryhotelloy);
body.replaceText('{{secondaryvistedcountries}}', secondaryvistedcountries);
body.replaceText('{{secondarysmoke}}', secondarysmoke);
body.replaceText('{{secondaryallergies}}', secondaryallergies);
body.replaceText('{{secondaryOthermed}}', secondaryOthermed);
body.replaceText('{{timestamp}}', timestamp);
//Append tactics
parseTactics(headers.values[0], tactics.values[i], body);
}
}
function parseTactics(headers, tactics, body){
for(var i = 1; i < tactics.length; i++){
{tactics[i] != '' &&
body.appendListItem(headers[i] + ' | ' + tactics[i] + ' OTHER').setGlyphType(DocumentApp.GlyphType.BULLET);
}
}
}
Error: "We're sorry, a server error occurred. Please wait a bit and try again. (line 63, file "Code")"
I expected the script to generate a new google doc from the data sheet as it is being submitted on google form.
I think your pretty close. Here's an example I did.
First, I created a function to generate some data for myself.
function testData() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
sh.clearContents();
var rg=sh.getRange(1,1,10,10);
var vA=rg.getValues();
for(var i=0;i<vA.length;i++) {
for(var j=0;j<vA[i].length;j++) {
vA[i][j]=Utilities.formatString('row: %s - col: %s',i+1,j+1);
}
}
rg.setValues(vA);
}
The above function creates a sheet that looks like this:
The Template File Looks like this:
And after running this code:
function createDoc(){
var spreadsheetId='spreadsheet Id';
var templateId='template Id';
var data=Sheets.Spreadsheets.Values.get(spreadsheetId,'Sheet177!A1:J2');//range include sheet name
var docId=DriveApp.getFileById(templateId).makeCopy('Test').getId();
var body=DocumentApp.openById(docId).getBody();
for(var i=0;i<data.values.length;i++) {
for(var j=0;j<data.values[i].length;j++) {
var s=Utilities.formatString('{{col%s-%s}}',i+1,j+1);
body.replaceText(s,data.values[i][j]);
}
}
}
There appears in the same folder another file named test that looks like this:
I must say that sure is a simple way to get data.
I'm kind of wondering if perhaps you simply didn't authenticate the program in the script editor.

How to fix the issue mail merge issue

I am trying to create an approval flow using sheet mail merge with approval buttons in the mail . Mail could generate when the user submits the HTML form.
Below script is not working I have attached the script with sample sheet.
I am not able to identify the exact issue, please help me to fix or identify
Sample Sheet
var REQUESTS_STATE_COLUMN = 32;
var STATE_APPROVERS_EMAILED = "EMAILED_Response Pending";
var STATE_APPROVED = "Approved";
var STATE_DENIED = "Rejected";
function sendEmail(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:AH2");
var data = dataRange.getValues();
for (i in data) {
var rowData = data[i];
var email = e.namedValues["Email Address"];
var emailAddress = rowData[30];
var submiterEmail = rowData[1];
var ProjectName = rowData[2];
var SrDesign = "Sr. Design Architect Services";
var PerHourRate = rowData[6];
var NumberOfHours = rowData[7];
var TotalRate = rowData[8];
var Contact = "Contact Centre Expert";
var PerHourRate2 = rowData[10];
var NumberOfHours2 = rowData[11];
var NTotalRate2 = rowData[12];
var NJrDesign = "Jr. Design Architect";
var PerHourRate3 = rowData[14];
var NumberOfHours3 = rowData[15];
var TotalRate3 = rowData[16];
var Outsourced = "Outsourced Technical Support Resource";
var PerHourRate4 = rowData[18];
var NumberOfHours4 = rowData[19];
var TotalRate4 = rowData[20];
var Supplier = "Supplier Management";
var PerHourRate5 = rowData[22];
var NumberOfHours5 = rowData[23];
var TotalRate5 = rowData[24];
var Project = "Project Management & Execution";
var PerHourRate6 = rowData[26];
var NumberOfHours6 = rowData[27];
var TotalRate6 = rowData[28];
var UserAccount = rowData[28];
var GrandTotalRate = rowData[29];
var seq = e.values[1];
var url = ScriptApp.getService().getUrl();
var sheet = SpreadsheetApp.openById('1i5x0oqpCDgOZO2Nbly4SpNkWpLbTXJhT6pPOfQ7NuEc').getSheetByName("Sheet1");
var cellval = range.getCell(row,1).getValue();
var options = '?approval=%APPROVE%&reply=%EMAIL%'
.replace("%EMAIL%",e.namedValues["User Email Address"])
var approve = url+options.replace("%APPROVE%","Approved")+'&row='+data+'&cellval='+cellval;
var reject = url+options.replace("%APPROVE%","Rejected")+'&row='+data+'&cellval='+cellval;
var subject = 'Technology Charges for '+ProjectName+'';
var html = '<p style="font-family:Verdana; fontsize=9px">Hello Recipient,<br/><br/><br/><br/>Referance No: '+cellval+'<br/><a href='+ approve +'> <b>approve </b></a><a href='+ reject +'> <b>Reject</b></a><br/>'
MailApp.sendEmail({
to: emailAddress,
subject: subject,
htmlBody: html,
});
//Add a state in the form spreadsheet with APPROVERS_EMAILED state
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
sheet.getRange(lastRow, REQUESTS_STATE_COLUMN+1).setValue(STATE_APPROVERS_EMAILED);
}
}
function doGet(e){
var answer = (e.parameter.approval === 'Approved') ? 'Yes -Approved!' : 'No-Rejected ';
var cellval = e.parameter.cellval;
var email = e.parameter.reply;
var sheet = SpreadsheetApp.openById("1i5x0oqpCDgOZO2Nbly4SpNkWpLbTXJhT6pPOfQ7NuEc").getSheetByName("Sheet1");
var data = sheet.getDataRange().getValues();
var headers = data[0];
var approvalCol = headers.indexOf("Approval") + 1;
if (0 === approvalCol) throw new Error ("Must add Approval column.");
// Record approval or rejection in spreadsheet
var row = ArrayLib.indexOf(data, 0, cellval);
if (row < 0) throw new Error ("Request not available."); // Throw error if request was not found
sheet.getRange(row+1, approvalCol).setValue(e.parameter.approval);
// Display response to approver
var app = UiApp.createApplication();
app.add(app.createHTML('<h2>Thank you..! Your response has been recorded'+' saying: '+ answer + '</h2>'))
return app
}
The getCell requires integer value for row and column but instead you are passing the entire row (rowData). You need to replace the line 45 to the below line.
var cellval = dataRange.getCell(i+1, 1).getValue()

copyDoc.saveAndClose(); Missing ) after argument list Google Sheet Script

I do not not know coding - I'm trying to run the script below and recieve the error Missing ) after argument list on line 79 copyDoc.saveAndClose();
Blockquote
Here is the url for the doc:
https://docs.google.com/document/d/1FcbVBHmCcDfjcaKXSU5UeaOD30h1d5yTyQp_s28VPzc/edit?usp=sharing
here is the script. Please advise. Sincere Thanks.
function myFunction() {
// rsaez#shsd.org
// Travel Request
// Get template from Google Docs and name it
var docTemplate = "1FcbVBHmCcDfjcaKXSU5UeaOD30h1d5yTyQp_s28VPzc";
// *** replace with your template ID ***
var docName = "Travel_Request";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email_address = "rsaez#shsd.org, rsaez#shsd.org";
var Building = e.values[5];
var Request = e.values[6];
var Total_Days = e.values[7];
var Substitute_Needed = e.values[8];
var Staff_Member_Type = e.values[9];
var Coverage_Type = e.values[10];
var Time_of_Day = e.values[11];
var Coverage = e.values[12];
var Request_Type = e.values[13];
var Destination = e.values[14];
var Purpose = e.values[15];
var City = e.values[16];
var State = e.values[17];
var Purpose_is_related_to = e.values[18];
var Registration = e.values[19];
var Lodging = e.values[20];
var Lodging_Cost = e.values[21];
var Lodging_Total = e.values[22];
var Meals = e.values[23];
var Meals_Cost = e.values[24];
var Meals_Total = e.values[25];
var Mileage = e.values[26];
var Other = e.values[27];
var Travel_Cost = e.values[28];
var Miscellanous = e.values[29];
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+full_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('keyDate',
copyBody.replaceText('keyName',
copyBody.replaceText('keyPosition',
copyBody.replaceText('keyBuilding',
copyBody.replaceText('keyRequest',
copyBody.replaceText('keyDayT',
copyBody.replaceText('keySubstitute',
copyBody.replaceText('keyStaff',
copyBody.replaceText('keyDay',
copyBody.replaceText('keyTime',
copyBody.replaceText('keyCoverage',
copyBody.replaceText('keyRequest',
copyBody.replaceText('keyDest',
copyBody.replaceText('keyPurpose',
copyBody.replaceText('keyCity',
copyBody.replaceText('keySt',
copyBody.replaceText('keyPurpRelated',
copyBody.replaceText('keyRT',
copyBody.replaceText('keyLND',
copyBody.replaceText('keyLCP',
copyBody.replaceText('keyLT',
copyBody.replaceText('keyMND',
copyBody.replaceText('keyMCP',
copyBody.replaceText('keyMT',
copyBody.replaceText('keyMLT',
copyBody.replaceText('keyOT',
copyBody.replaceText('keyTotalBOE',
copyBody.replaceText('keyMisc',
// Save and close the temporary document
copyDoc.saveAndClose();
// copyDoc.saveAndClose() (options.cand_email);
// Convert temporary document to PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf"
}
Your last line,
var pdf = DocsList.getFileById(copyId).getAs("application/pdf"
seems to be missing a ')' at the end. Perhaps that is the Missing ) after argument list.
The saveAndClose() method is automatically invoked at the end of script execution, for each open Document. Maybe it'll help: DocsList is deprecated since 2013, see https://developers.google.com/apps-script/sunset. You should use DriveApp instead.
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' for '+full_name)
.getId();
var pdf = DriveApp.getFileById(copyId).getAs('application/pdf');

Copy/paste values and formats while asking for name

I am trying to copy over all of the values and formats to a different spreadsheet, week by week, creating a new sheet within the workbook each time. This is for archival purposes. I have pieced together the following:
function ArchiveByWeek(){
var source = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('CRS Stats By Week')
var buildVersion = Browser.inputBox("What is the Weekend Ending Date?");
var sValues = source.getDataRange().getValues();
var sBG = source.getDataRange().getBackgrounds();
var sFC = source.getDataRange().getFontColors();
var sFF = source.getDataRange().getFontFamilies();
var sFL = source.getDataRange().getFontLines();
var sFFa = source.getDataRange().getFontFamilies();
var sFSz = source.getDataRange().getFontSizes();
var sFSt = source.getDataRange().getFontStyles();
var sFW = source.getDataRange().getFontWeights();
var sHA = source.getDataRange().getHorizontalAlignments();
var sVA = source.getDataRange().getVerticalAlignments();
var sNF = source.getDataRange().getNumberFormats();
var sWR = source.getDataRange().getWraps();
var destination = SpreadsheetApp.openById('1WVfJGDbdOewO2H-aMhQiek7sCOolK6xH7cSbfZ8KQgY');
var destinationSheet = destination.insertSheet(buildVersion, 1);
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues)
.setBackgrounds(sBG)
.setFontColors(sFC)
.setFontFamilies(sFF)
.setFontLines(sFL)
.setFontFamilies(sFFa)
.setFontSizes(sFSz)
.setFontStyles(sFSt)
.setFontWeights(sFW)
.setHorizontalAlignments(sHA)
.setVerticalAlignments(sVA)
.setNumberFormats(sNF)
.setWraps(sWR);
}
This seems to work fine, only some cells are not copied. For some reason, it is only cells that are summing other cells. Can't figure out why.
I found the following script, which worked perfectly, only I was unable to find a way to give each new sheet a unique name:
function copySheetValues(){
var source = SpreadsheetApp.getActiveSheet();
var sourcename = source.getSheetName();
var sValues = source.getDataRange().getValues();
var sBG = source.getDataRange().getBackgrounds();
var sFC = source.getDataRange().getFontColors();
var sFF = source.getDataRange().getFontFamilies();
var sFL = source.getDataRange().getFontLines();
var sFFa = source.getDataRange().getFontFamilies();
var sFSz = source.getDataRange().getFontSizes();
var sFSt = source.getDataRange().getFontStyles();
var sFW = source.getDataRange().getFontWeights();
var sHA = source.getDataRange().getHorizontalAlignments();
var sVA = source.getDataRange().getVerticalAlignments();
var sNF = source.getDataRange().getNumberFormats();
var sWR = source.getDataRange().getWraps();
var destination = SpreadsheetApp.openById('15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ');
var destinationSheet = destination.insertSheet(sourcename, 0);
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues)
.setBackgrounds(sBG)
.setFontColors(sFC)
.setFontFamilies(sFF)
.setFontLines(sFL)
.setFontFamilies(sFFa)
.setFontSizes(sFSz)
.setFontStyles(sFSt)
.setFontWeights(sFW)
.setHorizontalAlignments(sHA)
.setVerticalAlignments(sVA)
.setNumberFormats(sNF)
.setWraps(sWR);
}
I was actually able to come up with a solution that I was satisfied with. This was able to paste all of the values, and formats exactly as they were on the sheet when viewing. It asks for a name of the new sheet, which was my intention:
function Archive() {
var source = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SHEET NAME')
var sValues = source.getDataRange()
.getValues();
var weekEnding = Browser.inputBox("What is the Weekend Ending Date?");
var destination = SpreadsheetApp.openById('SHEET ID');
var copy = source.copyTo(destination)
.setName(weekEnding)
copy.getRange(1, 1, sValues.length, sValues[0].length)
.setValues(sValues); // overwrite all formulas that the copyTo preserved

Value e is not defined

I am trying to have a form fill out a doc using key values and then save the form for printing later in a folder in my drive. However the script keeps giving me the error "e" is not defined. I have no idea why.
>function myfunction(e) {
var docTemplate = "1pKwW-RcjaVV8xmm00hWDx1u2QxzQwaSjPJwVY2ux2nI";
var docName = "Form";
var full_name = "Form";
function onFormSubmit(e) {}
var Assign_To_1 = e.value[2];
var Assign_To_2 = e.value[3];
var Timestamp = e.values[0];
var Date_Of_Request = e.value[1];
var Requested_By = e.value[7];
var Principal_Approval = e.value[5];
var Urgency = e.value[4];
var Building_Room_Number = e.value[10];
var Description_of_Work_To_Be_Done = e.value[6];
var Parts_Needed = e.value[8];
var Parts_In_Stock = e.value[9];
var Invoice_Number = e.value[10];
var Completed_Signature = e.value[22];
var Incomplete_Signature = e.value[23];
var On_Hold_Signature = e.value[24];
var Estimated_Hours = e.value[14];
var Number_Of_Employees_To_Complete = e.value[18];
var Budget = e.value[11];
var Follow_Up = e.value[16];
var Overtime = e.value[15];
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+full_name)
.getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('KeyAssignedTo1',Assign_To_1);
copyBody.replaceText('KeyAssignedTo2',Assign_To_2);
copyBody.replaceText('KeyTimestamp',Timestamp);
copyBody.replaceText('KeyDateOfRequest',Date_Of_Request);
copyBody.replaceText('KeyRequestedBy',Requested_By);
copyBody.replaceText('KeyPrincipalApproval',Principal_Approval);
copyBody.replaceText('KeyUrgency',Urgency);
copyBody.replaceText('KeyBuildingRoomNumber',Building_Room_Number);
copyBody.replaceText('KeyDescriptionofWorkToBeDone',Description_of_Work_To_Be_Done);
copyBody.replaceText('KeyPartsNeeded', Parts_Needed);
copyBody.replaceText('KeyPartsInStock', Parts_In_Stock);
copyBody.replaceText('KeyInvoiceNumber', Invoice_Number);
copyBody.replaceText('KeyCompletedSignature', Completed_Signature);
copyBody.replaceText('KeyIncompleteSignature', Incomplete_Signature);
copyBody.replaceText('KeyOnHoldSignature', On_Hold_Signature);
copyBody.replaceText('KeyEstimatedHours', Estimated_Hours);
copyBody.replaceText('KeyNumberOfEmployeesToComplete', Number_Of_Employees_To_Complete);
copyBody.replaceText('KeyBudget', Budget);
copyBody.replaceText('KeyFoolowUp', Follow_Up);
copyBody.replaceText('KeyOvertime', Overtime);
copyDoc.saveAndClose();
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
var doc = DocsList.getFileById(copyId);
var folders = doc.getParents();
var newFolder=DocsList.getFolder(WorkOrderForms);
doc.addToFolder(WorkOrderForms);
var docParentFolder=folders[0];
doc.removeFromFolder(docParentFolder);
}
Please Help!
A few issues already solved in comments but I didn't see the biggest one at first : your main function is actually onFormSubmit but it is "hidden" in a myFunction function ...
please rewrite it like below and setup your trigger to run onFormSubmit as the main function now has a different name...
var docTemplate = "1pKwW-RcjaVV8xmm00hWDx1u2QxzQwaSjPJwVY2ux2nI";
var docName = "Form";
var full_name = "Form"; // you can keep these declarations as global variables
function onFormSubmit(e) { // this is the real function starting point
var Assign_To_1 = e.value[2];
var Assign_To_2 = e.value[3];
var Timestamp = e.values[0];
var Date_Of_Request = e.value[1];
var Requested_By = e.value[7];
var Principal_Approval = e.value[5];
var Urgency = e.value[4];
var Building_Room_Number = e.value[10];
var Description_of_Work_To_Be_Done = e.value[6];
var Parts_Needed = e.value[8];
var Parts_In_Stock = e.value[9];
var Invoice_Number = e.value[10];
var Completed_Signature = e.value[22];
var Incomplete_Signature = e.value[23];
var On_Hold_Signature = e.value[24];
var Estimated_Hours = e.value[14];
var Number_Of_Employees_To_Complete = e.value[18];
var Budget = e.value[11];
var Follow_Up = e.value[16];
var Overtime = e.value[15];
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+full_name)
.getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('KeyAssignedTo1',Assign_To_1);
copyBody.replaceText('KeyAssignedTo2',Assign_To_2);
copyBody.replaceText('KeyTimestamp',Timestamp);
copyBody.replaceText('KeyDateOfRequest',Date_Of_Request);
copyBody.replaceText('KeyRequestedBy',Requested_By);
copyBody.replaceText('KeyPrincipalApproval',Principal_Approval);
copyBody.replaceText('KeyUrgency',Urgency);
copyBody.replaceText('KeyBuildingRoomNumber',Building_Room_Number);
copyBody.replaceText('KeyDescriptionofWorkToBeDone',Description_of_Work_To_Be_Done);
copyBody.replaceText('KeyPartsNeeded', Parts_Needed);
copyBody.replaceText('KeyPartsInStock', Parts_In_Stock);
copyBody.replaceText('KeyInvoiceNumber', Invoice_Number);
copyBody.replaceText('KeyCompletedSignature', Completed_Signature);
copyBody.replaceText('KeyIncompleteSignature', Incomplete_Signature);
copyBody.replaceText('KeyOnHoldSignature', On_Hold_Signature);
copyBody.replaceText('KeyEstimatedHours', Estimated_Hours);
copyBody.replaceText('KeyNumberOfEmployeesToComplete', Number_Of_Employees_To_Complete);
copyBody.replaceText('KeyBudget', Budget);
copyBody.replaceText('KeyFoolowUp', Follow_Up);
copyBody.replaceText('KeyOvertime', Overtime);
copyDoc.saveAndClose();
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
var doc = DocsList.getFileById(copyId);
var folders = doc.getParents();
var newFolder=DocsList.getFolder(WorkOrderForms);
doc.addToFolder(WorkOrderForms);
var docParentFolder=folders[0];
doc.removeFromFolder(docParentFolder);
}