Insert hyperlink with variable into google docs using google scripts - google-apps-script

I have a google Form, and the responses populate a response google Sheet, which has a google Script function to generate a google Document using a template.
I am trying to get the address entered in the Form (stored in the response Sheet) to become a hyperlink in the generated Doc.
I have been using the body.replaceText() to replace all the fields I need in the Doc:
body.replaceText("{{Date}}", date);
and its working well, but the address field I would like to become a hyperlink.
I have been trying to do it this way:
body.replaceText("{{Location}}", =HYPERLINK("http://www.google.com/maps/place/'+location+'"));
But that does not become a usable hyperlink, resulting with this in the Doc (please note while it becomes a hyperlink on this page it does not become a hyperlink in Docs):
=HYPERLINK("http://www.google.com/maps/place/myplacenotyours")
I have also tried:
body.replaceText("{{Location}}", location = HYPERLINK("http://www.google.com/maps/place/"+location+));
But this throws up syntax errors.
I have this var:
var location = e.values[2];
So perhaps it better to use that to create another var as a hypertext?
I am now trying:
var loclink = 'Hyperlink("http://www.google.com/maps/place/'+location+'","'+location+'")';
but that doesnt do it either... I'm now starting to think that one can't insert a hyperlink using replace method?
Sorry for the noob question, but I can't figure this out. Can you help me find a solution and put a var into a hypertext link and put that into the Doc as a link?!
Cheers.

Something like this:
function insertLink() {
var pattern = '{{Location}}';
var url = 'https://stackoverflow.com/a/69143679/14265469';
var text = 'how to paste a link';
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var next = body.findText(pattern);
if (!next) return;
var start = next.getStartOffset();
body.replaceText(pattern, text);
body.editAsText().setLinkUrl(start, start+text.length-1, url);
}

Related

Google Apps Script to automatically open copied document after creating it?

We are using sheets for our mom & pop store as our invoice. However, my mother-in-law keeps saving over our invoice and we're always having to go back and delete the filled in sections. She cannot seem to remember the steps of making a copy and then opening that. I am using a script (button) to create a copy of the original and it is renamed as the customer name & date into a specific folder. However, once we do that, we still have to navigate to the folder and open the new document. Is there there a way to do this after I click the button on our original document to open of the copy that was made? Here is the script that I am using.
function saveAsSpreadsheet()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var range = sheet.getRange('Carolina Fireworks Order Form!C8');
sheet.setNamedRange('TestRange', range);
var TestRange = sheet.getRangeByName('Carolina Fireworks Order Form!C8').getValues();
Logger.log(TestRange);
var destFolder = DriveApp.getFolderById("1UdK90fEs3gkP4KZuUbmZbvvyVAW5ZMGw");
let name = SpreadsheetApp.getActiveSheet().getRange('C8').getValue();
const ds = Utilities.formatDate(new Date(),SpreadsheetApp.getActive().getSpreadsheetTimeZone(),"MM.dd.yy");
DriveApp.getFileById(sheet.getId()).makeCopy('TestRange', destFolder).setName(`${name}.${ds}`);
}
In your situation, how about the following modification?
From:
DriveApp.getFileById(sheet.getId()).makeCopy('TestRange', destFolder).setName(`${name}.${ds}`);
To:
const file = DriveApp.getFileById(sheet.getId()).makeCopy('TestRange', destFolder).setName(`${name}.${ds}`);
var js = `<script>window.open('${file.getUrl()}');google.script.host.close();</script>`;
var html = HtmlService.createHtmlOutput(js);
SpreadsheetApp.getUi().showModalDialog(html, 'Now loading.');
In this script, the URL is opened using Javascript on the dialog.
This is from this post
Note:
From MetaMan's comment
If you want this to work you will have to disable popup blocking
References:
showModalDialog(userInterface, title)
Window.open()

Google Sites "addListItem" fails with Google Form Prefilled URL

I am working up a solution which returns a link to a prefilled Google Form, to be located on a classic Google Sites List Page. I have all the code in place, everything works, aside from the last vital part: programmatically, via Google Apps Script, adding the Google Form prefilled url as a new listitem on a Google Sites List Page. I am doing the prefilling using variables from a spreadsheet (the Responses from the google form). The url/anchor code looks perfectly formed in the Log. Here is the code:
//fetch all spreadsheet row entries to variables
var keyname = candname;
var keytimestamp = ActiveSheet.getRange("A"+ActiveRow).getValue();
var keytimestamp = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
var keyinc01 = ActiveSheet.getRange("B"+ActiveRow).getValue();
var keyinc02 = ActiveSheet.getRange("C"+ActiveRow).getValue();
var keyinc03 = ActiveSheet.getRange("D"+ActiveRow).getValue();
var keybrok01 = ActiveSheet.getRange("E"+ActiveRow).getValue();
var keybrok02 = ActiveSheet.getRange("F"+ActiveRow).getValue();
var keybrok03 = ActiveSheet.getRange("G"+ActiveRow).getValue();
var keyacc01 = ActiveSheet.getRange("H"+ActiveRow).getValue();
var keyacc02 = ActiveSheet.getRange("I"+ActiveRow).getValue();
var keyacc03 = ActiveSheet.getRange("J"+ActiveRow).getValue();
//var prefillurl = "https://www.google.co.uk"; //test other url
var prefillurl = 'https://docs.google.com/a/xxxxxxxx.org/forms/d/e/1FAIpQLSfOT0CVpSyGrlZmKKIRVCqbg11rAa9ANyYL8u9QwIWjqWfITg/viewform?entry.1894338678='+keyinc01+'&entry.1429410229='+keyinc02+'&entry.868549131='+keyinc03+'&entry.1083479546='+keybrok01+'&entry.1385475363='+keybrok02+'&entry.137722395='+keybrok03+'&entry.1074722805='+keyacc01+'&entry.1093081320='+keyacc02+'&entry.409101030='+keyacc03;
var listpageurl = "Google Form Link";
Logger.log(listpageurl);
var site = SitesApp.getSiteByUrl("https://sites.google.com/a/xxxxxxxx.org/xxxxxxxx");
var page = site.getChildByName("/home/candidates/"+candwebname);
page.addListItem([ keytimestamp, ssname, listpageurl ]);
As you can see I have tested the anchor tag syntax with the commented "https://www.google.co.uk", which works, and the prefilled url pasted into a browser also works correctly (grabbed from the Log). Also the listpage will accept the url via manual direct entry.However I always get the error about the anchor tag not being properly formed when I run the code. I have also tested with and without the https:// in the url, just in case. I have either missed something fundemental, have left out some additional quotes or double quotes, or have found a bug?
I have found a workaround, which was to enable UrlShortener, but would prefer to be able to use the prefilled url directly ( I will have a lot of these to do!) to speed things up, and make the code more transferrable.
Can anyone spot the issue here?

Google App Script- Docs/images in tables?

I have searched and searched for the syntax to place an image in a table cell with Google App Script in a Google Doc (not Sheet). This is what I am trying to do:
var resp01 = UrlFetchApp.fetch("http://www.example.com/image01.png");
var resp02 = UrlFetchApp.fetch("http://www.example.com/image02.png");
var cells = [[resp01.getBlob()], [resp02.getBlob()]];
copyBody.appendTable(cells);
This yields simply the word "Blob" in my table.
I can do this all day long with a paragraph:
Body.getChild(x).asParagraph().appendInlineImage(resp01.getBlob());
But for some reason, the "parallel" syntax in a table won't cut it? Does anyone know what I am missing?
Thank You
You need to call TableCell's insertImage() method and provide the child index and the blob source of the image as parameters.
Hope that helps!
Thank You for the input KRR.
I was able to get my project where I wanted it to go, part of which involved inserting images in a table in a Google Doc using Google App Script. After much reading, I settled on the syntax that follows. I hope this helps anyone else trying to learn:
function createDoc() {
var doc = DocumentApp.create('Sample Document');
var body = doc.getBody();
var resp01 = UrlFetchApp.fetch("http://www.cincinnati-oh.gov/cityofcincinnati/assets/Image/Logos/cityofcincinnati.png");
var rowsData = [["City of Cincinnati IMAGE:", ""]];
table = body.insertTable(1, rowsData);
var row = table.getRow(0);
var cell = row.getCell(1);
cell.appendImage(resp01.getBlob());
}

Making links from script in google spreadsheet

I want to make some links in my spreadsheet. I can make a string that looks like this. I looked around, though I did only find methods to link links that are already in the spreadsheet.
var linkBattlenet = "http://eu.battle.net/wow/en/character/"+toonrealm+"/"+toon.name+"/advanced"
var showLink = "battle.net link"+toon.name //this is what shall be seen in the spreadsheet.
I tried
var showLink = "battle.net link"+toon.name
var linkBattlenet = showLink.link("http://eu.battle.net/wow/en/character/"+toonrealm+"/"+toon.name+"/advanced")
Here i got the problem that it printed a string into the spreadsheet cell, that looks like this:
"%Character name%" .
(I am returnig the value in an array)
Instead of using showLink.link(), you can directly assign the string value to the cell.
Tried this code below:
function makeLink(){
var name = "john";
var showLink = ""http://eu.battle.net/wow/en/character/+name+"/advanced"";
var mainsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Main');
mainsheet.getActiveCell().setValue(showLink);
}
If you don't want to see the complete url in the cell, you can also try this line instead:
var showLink = '=HYPERLINK("http://eu.battle.net/wow/en/character/'+name+'/advanced","clickhere")';
Hope that helps!

How to (from a Google Spreadsheet) get the ID of a linked form

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. :)