How to partially change a file name in google apps script? - javascript

function autoFillGoogleDocFromForm(e) {
var timestamp = e.values[0];
var auditorFirmName = e.values[1];
var auditorAddressLine1 = e.values [2];
var auditorAddressLine2 = e.values[3];
var auditorAddressLine3 = e.values[4];
var auditorAddressLine4 = e.values [5];
var dateOfLetterIssue = e.values[6];
const template = "template";
var templateFile = DriveApp.getFileById("");
var templateFolder = DriveApp.getFolderById("");
var copy = templateFile.makeCopy(auditorFirmName + ${template}, templateFolder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText("{{Insert Auditor Firm name}}", auditorFirmName);
body.replaceText("{{Address Line 1}}", auditorAddressLine1);
body.replaceText("{{Address Line 2}}", auditorAddressLine2);
body.replaceText("{{Address Line 3}}", auditorAddressLine3);
body.replaceText("{{Address Line 4}}",auditorAddressLine4);
body.replaceText("{{Date}}",dateOfLetterIssue);
doc.saveAndClose();
}
Currently the line var copy = templateFile.makeCopy(auditorFirmName, templateFolder); is creating a copy of the original doc with the file name of the auditor firm as I have requested. But what I would like to do is create a file name with the auditor firm name and the wording template for example. Or a fixed piece of text that is not a variable. E.g currently the file will save as John Smith Auditors where I want it to save as John Smith Auditors Template. Where John Smith stays as a variable but the word Template would always remain fixed. Is this possible?

How about changing this line var copy = templateFile.makeCopy(auditorFirmName, templateFolder); to this var copy = templateFile.makeCopy(auditorFirmName + template, templateFolder); and add a const template="whatever words you want to add"; earlier in the file near the top. You could just add + "Template" if you like but typically your needs tend to change so the use of a variable may be useful but it's up to you. If I'm not understanding you question I apologize.

Related

If e.value = null or blank then leave blank

var timestamp = e.values[0];
var recipientName = e.values[1];
var firstLineOfAddress = e.values [2];
var secondLineOfAddress = e.values[3];
var thirdLineOfAddress = e.values[4];
var postcode = e.values [5];
var recipientEmail = e.values[6];
var todaysDate = e.values[7];
var invoicenNumber = e.values[8];
var dueDate = e.values[9];
var item1Description = e.values [10];
var item1Qty = e.values [11];
var item1UnitPrice = e.values [12];
var item1Amount = e.values[13];
var templateFile = DriveApp.getFileById("1VjJI3VUNSJDQuv8NsgSfSugIfi3c_ev4cGpbk5_LQ3I");
var templateFolder = DriveApp.getFolderById("1MsmTVhosVz0S4Nquz2qMr-SZtYZYyV9S");
var copy = templateFile.makeCopy(recipientName, templateFolder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText("{{RECIPIENT NAME}}", recipientName);
body.replaceText("{{FIRST LINE OF ADDRESS}}", firstLineOfAddress);
body.replaceText("{{SECOND LINE OF ADDRESS}}", secondLineOfAddress);
body.replaceText("{{THIRD LINE OF ADDRESS}}", thirdLineOfAddress);
body.replaceText("{{Postcode}}",postcode);
body.replaceText("{{EMAIL}}",recipientEmail);
body.replaceText("{{DATE}}",todaysDate);
body.replaceText("{{REF}}", invoicenNumber);
body.replaceText("{{DUEDATE}}", dueDate);
body.replaceText("{{desc1}}", item1Description);
body.replaceText("{{qty1}}", item1Qty);
body.replaceText("{{unitprice1}}", item1UnitPrice);
body.replaceText("{{amount1}}", item1Amount)
doc.saveAndClose();
}
Im still learning googleappscript/java so apologies for sounding dumb. Im using a form to produce a invoice however I would like the variable of e.values[10] to be able to be cleared from the doc it produces if left blank.
So if e.value is blank then it body.replace text should replace it with nothing. If e.value is filled in then body.replace text should fill in with the appropriate response.
Any ideas how I can do this?
Each submission in form always contains timestamp. So when a user leave a question in blank, the value of it in e.values is just empty. It will produce something like this: [3/4/2022 5:50:53, , , , , , , , , , , , ].
Empty values works in body.replaceText() and not produce error. Hence you don't need to change anything in your code.
In case you have null value in your e.values, which can be done by editing the content of e.values, just append a ||'' next to the replacement string.
Your code should look like this:
body.replaceText("{{RECIPIENT NAME}}", recipientName||'');
body.replaceText("{{FIRST LINE OF ADDRESS}}", firstLineOfAddress||'');
body.replaceText("{{SECOND LINE OF ADDRESS}}", secondLineOfAddress||'');
body.replaceText("{{THIRD LINE OF ADDRESS}}", thirdLineOfAddress||'');
body.replaceText("{{Postcode}}",postcode||'');
body.replaceText("{{EMAIL}}",recipientEmail||'');
body.replaceText("{{DATE}}",todaysDate||'');
body.replaceText("{{REF}}", invoicenNumber||'');
body.replaceText("{{DUEDATE}}", dueDate||'');
body.replaceText("{{desc1}}", item1Description||'');
body.replaceText("{{qty1}}", item1Qty||'');
body.replaceText("{{unitprice1}}", item1UnitPrice||'');
body.replaceText("{{amount1}}", item1Amount||'')

Converting a Google doc to PDF, then moving to another folder

I am working on script that will fill a Google doc template with cell values from a spreadsheet. A copy of the edited doc is created and converted into a PDF. I would then like for both the doc and the pdf to be moved to the specified folder. I am stuck on getting the pdf moved over to the folder. I created a function to move the docs, and it seems to work fine with the Google doc copy, but an error is being returned when the function runs for the pdf. The error seems to be coming from the moveFile function. I have also tried moving moveFile pdf call to fillLetter, but still get the same error. This is my first attempt at coding with Google script, so any advice would be greatly appreciated. Thank you!
function fillLetter() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];//Form Responses tab
var templateId = '1d-CKr_Xi27FrWsH6eWdUCWKyzrLjy3ivTjLkk_WyJ4s';//Test doc
//get candidates row number from user input
var ui = SpreadsheetApp.getUi();
var rowNum = ui.prompt("Please enter candidate row number");
//activates first column in selected row
var col = sheet.getRange("A"+ rowNum.getResponseText());
sheet.setActiveRange(col);
var candName = sheet.getActiveCell().getValue();
col = sheet.getRange("B"+ rowNum.getResponseText());
sheet.setActiveRange(col);
var location = sheet.getActiveCell().getValue();
//creates copy of template doc and renames
var lastName = candName.split(" ");
var filename = candName.substring(0,1) + lastName[lastName.length - 1] + ' - Offer Letter';
var newOffer = DriveApp.getFileById(templateId).makeCopy();
var offerId = newOffer.getId();
DriveApp.getFileById(offerId).setName(filename);
//gets body of template doc and replaces text
var doc = DocumentApp.openById(offerId);
var body = doc.getBody();
var todaysDate = Utilities.formatDate(new Date(), 'PST', 'MMMM dd, yyyy');
body.replaceText('{{Todays date}}', todaysDate);
body.replaceText('{{Candidate name}}', candName);
body.replaceText('{{Location}}', location);
doc.saveAndClose();
//Creates folder and moves newly created files
var folderName = DriveApp.createFolder(candName).getId();
convertPDF(offerId, folderName); // Line 52
moveFile(offerId, folderName);
}
function convertPDF(fileToCopy, folder) {
var docFolder = DriveApp.getFolderById(folder);
var copy = DriveApp.getFileById(fileToCopy);
//Add the PDF extension
var docblob = copy.getAs('application/pdf');
docblob.setName(copy.getName() + ".pdf");
var pdfFile = DriveApp.createFile(docblob);
var fileId = pdfFile.getId();
Logger.log("Offer PDF id - " + fileId);//for debug
moveFile(fileId, docFolder); // Line 66
}
function moveFile(fileId, folderId) {
var file = DriveApp.getFileById(fileId);
DriveApp.getFolderById(folderId).addFile(file); // Line 72: wh/ error is most likely occurring
}
Below is the error message from the Logger:
Error
Exception: Unexpected error while getting the method or property getFolderById on object DriveApp.
moveFile # testCode.gs:72
convertPDF # testCode.gs:66
fillLetter # testCode.gs:52
In the current stage, you can use moveTo method for moving the file on Google Drive. This has added on July 27, 2020. Ref In your script, when moveFile is modified, it becomes as follows.
Modified script:
function moveFile(fileId, folderId) {
var file = DriveApp.getFileById(fileId);
file.moveTo(DriveApp.getFolderById(folderId));
}
Reference:
moveTo(destination)
The methods of addFile, addFolder, removeFile and removeFolder have already been deprecated. Ref

Javascript split string between multiple spans

I have scoured Google looking for an answer but I cant seem to find one.
I need to split the following string into separate variables
the string is stored as a variable
:-
var location = autocomplete.getPlace();
var address = location['formatted_address'];
Output:-
<span class="street-address">Street address</span>, <span class="locality">Town</span>, <span class="region">County</span> <span class="postal-code">Post Code</span>, <span class="country-name">Country</span>
eg.
var street = "Street address";
var town = "Town";
var county = "County";
var postc = "Post Code";
var country = "Country";
So I need to get the contents between
<span class="street-address"></span>
<span class="locality"></span>
etc...
Sometime there are extra spans sometimes less.
I have looked at some javascript but it only gets the content between:-
<span class="locality"> and the very last </span>
Any help in the right direction would be greatly
Are you using plain javascript? or jQuery?
in javascript you can get the text inside an element via:
var1 = document.getElementByClass("street-address").innerText
or in jQuery:
var streetAddress = $('.street-address').text();
var city= $('.city').text();
If you're using jQuery:
var 1 = $('span.street-address').text();
var 2 = $('span.locality').text();
var 3 = $('span.region').text();
var 4 = $('span.postal-code').text();
var 5 = $('span.country-name').text();
It should be that simple, unless I am missing something in the question.
Can you use jQuery? Check this out https://jsfiddle.net/zsxar4r4/
var address = [];
$('span').each(function(idx, span) {
address.push($(span).html());
})
console.log(address);
You can use the getElementsByClassName() method, which will return an array-like object.
https://developer.mozilla.org/en/docs/Web/API/Document/getElementsByClassName
var addressData = document.getElementsByClassName('address');
//And than do something with the object. You can access it like an array:
console.log(addressData[2].innerHTML);

From .txt data give values to inputs

I'm trying to fill some inputs when you load a page, using the data I have from a .txt file. This file has a list of numbers
1
2
3
Something like this. So I wanted to read this lines and put them in their corresponding input. Suggestions on how to do this??
I tried with this code, but maybe I have a mistake that I don't know about, I'm starting with javascript.
function loadvalues()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("E://Steelplanner/Demand_Routing/Pruebas/OrderBalancing_Masivos/ModificaFechaTope/DueDate/Datosactuales.txt", true);
var Ia5 = document.getElementById("Ia5sem");
var text = s.ReadLine();
Ia5.value = text;
Try using file.ReadLine() until document not completely read using while loop with AtEndOfStream of file variable.
Here is example you can refer: ReadLine Method
Don't forget to replace TextFile path to your own text file path
My text file contains same data as in your example
<script type="text/javascript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
//specify the local path to Open and always add escape character else throw error for bad file name
var file = fso.OpenTextFile("C:\\Users\\MY_USER\\Desktop\\txtfile.txt", 1);
var Ia5 = document.getElementById("Ia5sem");
while (!file.AtEndOfStream) {
var r = file.ReadLine();
Ia5.innerHTML = Ia5.innerHTML + ("<br />" + r);
}
file.Close();
</script>
<p id="Ia5sem">HI</p>
So, I don't know why, but I just changed the name of the variables and made a slight change in the .OpenTextFile line and it worked.
function loadvalues()
{
var file = new ActiveXObject("Scripting.FileSystemObject");
var text = file.OpenTextFile("E:\\Steelplanner\\Demand_Routing\\Pruebas\\OrderBalancing_Masivos\\ModificaFechaTope\\DueDate\\Datosactuales.txt", 1,false);
var Ia5s = document.getElementById("Ia5sem");
Ia5s.value = text.ReadLine();
var Ia4s = document.getElementById("Ia4sem");
Ia4s.value = text.ReadLine();
text.close();
}
Anyways, I'm gonna check the FileReader() for future references and the script #Sarjan gave, maybe I can improve it, but I have other things to finish. Thanks for everything.

Having trouble converting user input into a graphic bar

The code seems to work fine when inputting numbers 1-9 but anything above doesn't work, what could be the issue? Here is the code:
var varkString = prompt('Enter your VARK scores - [visual|aural|read|kinesthetic]','9|3|11|10');
var subStrings = varkString.split('|');
var visual = varkString[0];
var aural = varkString[1];
var read = varkString[2];
var kinesthetic = varkString[3];
var varkBar = 30*visual
document.writeln('<img src="bar_blue.png" width='+varkBar+' height="25"/>');{
}
Edit: Solved
You are parsing first character when you are getting visual, second on aural and third on read.
I belive that you want to use subStrings
var visual = subStrings[0];
var aural = subStrings[1];
var read = subStrings[2];
when you are slpiting the string varkString the array will automatically constructed and assigned to subStrings.so use it like this:
var subStrings = varkString.split('|');
var visual = subStrings[0];
var aural = subStrings[1];
var read = subStrings[2];
var kinesthetic = subStrings[3];

Categories