I have this google app script which should
show file upload dialog
store file in google drive
write the url of the file into the current cell
All goes well except step 3, where the cell updated is always cell A1 in the first sheet. But the cursor is on sheet #3 on another cell.
function onOpen(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var menuEntries = [];
menuEntries.push({name: "File...", functionName: "doGet"});
ss.addMenu("Attach ...", menuEntries);
}
function doGet(e) {
var app = UiApp.createApplication().setTitle("Attach file to sheet");
var form = app.createFormPanel().setId('frm').setEncoding('multipart/form-data');
var formContent = app.createVerticalPanel();
form.add(formContent);
formContent.add(app.createFileUpload().setName('thefile'));
formContent.add(app.createSubmitButton('Submit'));
app.add(form);
SpreadsheetApp.getActiveSpreadsheet().show(app);
return app;
}
function doPost(e) {
var fileBlob = e.parameter.thefile;
var doc = DocsList.getFolderById('0B0uw1JCogWHuc29FWFJMWmc3Z1k').createFile(fileBlob);
var app = UiApp.getActiveApplication();
var label = app.createLabel('file uploaded successfully');
var value = '=hyperlink("' + doc.getUrl() + '","' + doc.getName() + '")'
app.add(label);
app.close();
SpreadsheetApp.getActiveSheet().getActiveCell().setValue(value);
return app;
}
I tried SpreadsheetApp.getActiveSheet().getActiveCell().setValue(value); outside of the doPost() function and this works when called in a normal context. What am I missing here?
judging from this answer, it is not possible to get the current spreadsheet/cell from the doPost function, the way I got it working is to get it in the doGet function via hidden fields and pass it via the form. Full blown working example here.
Related
So I have multiple google forms (around 20 forms), that I need to do 2 things to them:
1- These 20 forms are placed in a folder in my google drive. I need to add more like an "Access code" where users will have to insert in order to continue the solving the quiz.
The way I did that was to add a "short answer" question to "section 1" of the quiz asking "Enter your Access Code", add "response validation", "Regular expression" and "Pattern". Also making this a "required question". This should look something like the below picture
Example of google form
So is it possible to have a scriptto add this question to all 20 forms
2- The "access code" in these google forms will have to be updated frequently, so I don' want to be updating the "Pattern" manually for each form, is t possible to have a google script to edit the value of the pattern for each form
Thanks in advance guys :)
I managed to solve this issue that I was having, through looking for different codes and here are the codes that I used.
N.B. The codes might not be very clean as I was copying them from other parts/projects, but they have worked for me
1- Update the 20 forms with adding the access code question, I figured it was not possible to add a question at a certain position in the google form, however I can add a question at the end of the form and then move this item to the position I want:
function AddAccesscodeQ() {
var filess = DriveApp.getFolderById("Drive id>").getFiles();
while (filess.hasNext()) {
var file = filess.next();
var form = FormApp.openById(file.getId());
var sectionIndex= 0; // Please set the index you want to insert.
//I added a "sample item" to be moved and edited later
var newItemQ = form.addTextItem().setTitle("New sample item").getIndex(); // New sample item
// I added a Pagebreak that also should be moved after the questions "Enter Your Access Code"
var newItemPB = form.addPageBreakItem().getIndex();
var items = form.getItems(FormApp.ItemType.PAGE_BREAK);
var sections = [0];
for (var i = 0; i < items.length; i++) {
// I pushed the items in the google form twice downwards, to be able to move the "sample item" and "Page break" to the top of the form
sections.push(items[i].getIndex());
sections.push(items[i].getIndex());
}
var insertIndex = sections[sectionIndex + 1] || null;
if (insertIndex) {
// Here I moved the 2 new items to the desired positions
form.moveItem(newItemQ, 0);
form.moveItem(newItemPB, 1);
}
// Here I am going to edit the "Sample Question" to be as desired
var itemss = form.getItems();
var itemID = itemss[0].getId();
var itemse = form.getItemById(itemID).asTextItem()
.setTitle('Enter Your Access Code').setRequired(true);
//Create validation rule
var validation = FormApp.createTextValidation()
.setHelpText('Invalid Code')
.requireTextMatchesPattern("<Access Code>")
.build();
itemse.setValidation(validation);
}
}
2- The second problem was that I later might need to change this access code to a new one for the 20 forms
function UpdateAccessCode() {
var filesPhCH = DriveApp.getFolderById("<Drive ID>").getFiles();
while (filesPhCH.hasNext()) {
var file = filesPhCH.next();
var form = FormApp.openById(file.getId());
var items = form.getItems();
//Loop through the items and list them
for (var i = 0;i<items.length;i++){
var item = items[i];
var itemID = item.getId();
var itemtitle = item.getTitle();
var itemindex = item.getIndex();
// I found no need to continue the for loop since the items that need modification are at the top of the form
if (itemindex == 0){
break;
}
}
//Select the question you want to update
var itemse = form.getItemById(itemID).asTextItem()
.setTitle('Enter Your Access Code');
//Create validation rule
var validation = FormApp.createTextValidation()
//.setTitle('Enter Your Access Code');
.setHelpText('Invalid Code')
.requireTextMatchesPattern("<Enter the new Access Code>")
.build();
itemse.setValidation(validation);
}
}
I hope this might help someone as it has saved a lot of time for me ;)
I create an object that returns textBox(), which could change their properties depending on the user's actions. However, once I put the function doChange(e) inside the object as a method like this:
function textBoxExt() {
...
this.doChange = function(e) {...}
...
}
my code returns an error: Cannot find a function doChange()...
I tried different ways to declare a function as a method in my object, but none of them worked. Please tell me, how do I modify the code below to move doChange(e) inside the object as a method. It is possible for functions that calls by handlers?
var style = {
modified: {color: 'black', backgroundColor: 'yellow', },
};
function textBoxExt() {
var app = UiApp.getActiveApplication();
var changeHandler = app.createServerHandler('doChange');
var box = app.createTextBox();
box.addValueChangeHandler(changeHandler);
this.init = function(id) {
return box.setId(id);
}
}
var doChange = function(e){
var app = UiApp.getActiveApplication();
app.getElementById(e.parameter.source).setStyleAttributes(style.modified);
return app;
}
function doGet() {
var app = UiApp.createApplication();
app.add(new textBoxExt().init('box1').setText('text1'));
return app;
}
You cant do this with gas. Handlers are passed as text. Besides objects only exist during the current handler so it cant possibly be attached to an object from a previous server call.
I'm trying to add an autocomplete feature in my Google Spreadsheet using this Google Apps Script suggest box library from Romain Vialard and James Ferreira's book:
function doGet() {
// Get a list of all my Contacts
var contacts = ContactsApp.getContacts();
var list = [];
for(var i = 0; i < contacts.length; i++){
var emails = contacts[i].getEmails();
if(emails[0] != undefined){
list.push(emails[0].getAddress());
}
}
var app = UiApp.createApplication();
var suggestBox = SuggestBoxCreator.createSuggestBox(app, 'contactPicker', 200, list);
app.add(suggestBox);
return app;
}
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "my_sheet_name" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 1) {
doGet();
}
}
}
But when I start editing the column 1 of "my_sheet_name" nothing hapens (if I replace doGet() for other function, this other function runs Ok). I've already installed the Suggest Box library. So, why the doGet() function doesn't work?
small confusion here...
The doGet() ..... return app; structure that you are using here is for standalone webapps that need to be deployed and run with their own url in a browser window.
What you are trying to do is to show a Ui in a popup window in a spreadsheet, the mechanism is different : see example below and have a look at the documentation here.
function doGet_or_any_other_name_preferably_something_more_specific() {
var contacts = ContactsApp.getContacts();
var list = [];
for(var i = 0; i < contacts.length; i++){
var emails = contacts[i].getEmails();
if(emails[0] != undefined){
list.push(emails[0].getAddress());
}
}
var app = UiApp.createApplication();
var suggestBox = SuggestBoxCreator.createSuggestBox(app, 'contactPicker', 200, list);
app.add(suggestBox);
SpreadsheetApp.getActive().show(app);
}
Note that this code will allow the Ui to show up but that's about all.... no data will be written in the spreadsheet since you didn't implement any handler to handle the data return. For details about that step read the aforementioned documentation and the examples shown on Romain's website.
EDIT following your comment : tested with this exact code (copied/pasted) and working, see capture below.
I found a script online that takes the current sheet, copies it to a temporary new spreadsheet, converts it to PDF and emails it. I was able to get it working but trying to set it up so that it only sends a certain range. Tried to play with it a bit but I am not a good coder by any stretch. Alternatively I'd be interested also in figuring out how to get it to fit to 1 page PDF in landscape, convert without gridlines (my online research shows this ins't possible?) or even send as XLS.
// Simple function to send Weekly Status Sheets to contacts listed on the "Contacts" sheet in the MPD.
// Load a menu item called "Project Admin" with a submenu item called "Send Status"
// Running this, sends the currently open sheet, as a PDF attachment
function onOpen() {
var submenu = [{name:"Send Status", functionName:"exportSomeSheets"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Project Admin', submenu);
}
function exportSomeSheets() {
// Set the Active Spreadsheet so we don't forget
var originalSpreadsheet = SpreadsheetApp.getActive();
// Set the message to attach to the email.
var message = "Please see attached"; // Could make it a pop-up perhaps, but out of wine today
// Get Project Name from Cell A1
var projectname = originalSpreadsheet.getRange("A1:A1").getValues();
// Get Reporting Period from Cell B3
var period = originalSpreadsheet.getRange("B3:B3").getValues();
// Construct the Subject Line
var subject = projectname + " - Weekly Status Sheet - " + period;
// Get contact details from "Contacts" sheet and construct To: Header
// Would be nice to include "Name" as well, to make contacts look prettier, one day.
var contacts = originalSpreadsheet.getSheetByName("Contacts");
var numRows = contacts.getLastRow();
var emailTo = contacts.getRange(2, 2, numRows, 1).getValues();
// Google scripts can't export just one Sheet from a Spreadsheet
// So we have this disgusting hack
// Create a new Spreadsheet and copy the current sheet into it.
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var projectname = SpreadsheetApp.getActiveSpreadsheet();
sheet = originalSpreadsheet.getActiveSheet();
sheet.copyTo(newSpreadsheet);
// Find and delete the default "Sheet 1", after the copy to avoid triggering an apocalypse
newSpreadsheet.getSheetByName('Sheet1').activate();
newSpreadsheet.deleteActiveSheet();
// Make zee PDF, currently called "Weekly status.pdf"
// When I'm smart, filename will include a date and project name
var pdf = DocsList.getFileById(newSpreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:'Weekly Status.pdf',content:pdf, mimeType:'application/pdf'};
// Send the freshly constructed email
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
// Delete the wasted sheet we created, so our Drive stays tidy.
DocsList.getFileById(newSpreadsheet.getId()).setTrashed(true);
}
To send a single sheet you may hide all other before sending.
var sheet_to_send = 'Sheet1';
//-----------------------------
var as = SpreadsheetApp.getActiveSpreadsheet();
var sheets = as.getSheets();
for(var i in sheets){
if (sheets[i].getName()!=sheet_to_send){
sheets[i].hideSheet();
}
}
MailApp.sendEmail(email_to, email_subject, email_body, {attachments: SpreadsheetApp.getActiveSpreadsheet()});
for(var i in sheets){
if (sheets[i].getName()!=sheet_to_send){
sheets[i].showSheet();
}
}
If you have more sheets to send, you would filter them with a javascript object:
var sheets_to_send = {'Sheet1':1, 'Sheet3': 1};
...
// replace
if (sheets[i].getName()!=sheet_to_send)
// by
if (!(sheets[i].getName() in sheet_to_send))
I am using this code to automatically send a google spreadsheet with email in pdf format. it works fine, but I need to customize the pdf by removing the grid lines and set display A4 . Is there a way ? thanks
Simple function to send Weekly Status Sheets to contacts listed on the "Contacts" sheet in the MPD.
// Load a menu item called "Project Admin" with a submenu item called "Send Status"
// Running this, sends the currently open sheet, as a PDF attachment
function onOpen() {
var submenu = [{name:"Invia", functionName:"exportSomeSheets"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Invia PDF', submenu);
}
function exportSomeSheets() {
// Set the Active Spreadsheet so we don't forget
var originalSpreadsheet = SpreadsheetApp.getActive();
// Set the message to attach to the email.
var message = "Messaggio email";
// Get Project Name from Cell A1
var projectname = originalSpreadsheet.getRange("A1:A1").getValues();
// Get Reporting Period from Cell A2
var period = originalSpreadsheet.getRange("A2:A2").getValues();
// Construct the Subject Line
var subject = projectname;
// Get contact details from "Contacts" sheet and construct To: Header
// Would be nice to include "Name" as well, to make contacts look prettier, one day.
var emailTo = originalSpreadsheet.getRange("A3:A3").getValues();
// Create a new Spreadsheet and copy the current sheet into it.
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var projectname = SpreadsheetApp.getActiveSpreadsheet();
sheet = originalSpreadsheet.getActiveSheet();
sheet.copyTo(newSpreadsheet);
var aliases = GmailApp.getAliases()
Logger.log(aliases);
Logger.log(aliases[2]); //returns the alias located at position 0 of the aliases array
// Make zee PDF, currently called "Weekly status.pdf"
// When I'm smart, filename will include a date and project name
var pdf = DocsList.getFileById(originalSpreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:'Nome_allegato',content:pdf, mimeType:'application/pdf'};
// Send the freshly constructed email
GmailApp.sendEmail(emailTo, subject, message, {'from': aliases[2], attachments:[attach]});
// Delete the wasted sheet we created, so our Drive stays tidy.
DocsList.getFileById(newSpreadsheet.getId()).setTrashed(true);
}
In order to split a spreadsheet up, you must first copy the parts into a temporary sheet and then copy that sheet into a new spreadsheet.
Here is my code to replace yours from 'Create spreadsheet...' to where you delete Sheet1 of the new spreadsheet.
//variables firstRow & lastRow define the part of the sheet to copy
//create new spreadsheet
var newSpreadsheet = SpreadsheetApp.create('Spreadsheet to export');
//create temporary sheet to copy to new spreadsheet
var tempSheet = originalSpreadsheet.insertSheet();
//if header copy it
if (sheet.getFrozenRows() > 0)
{
dataSheet.getRange( 1, 1, sheet.getFrozenRows() ).copyTo( tempSheet.getRange(1,1) );
}
//copy relevant data to temporary sheet
dataSheet.getRange( firstRow, 1, lastRow - firstRow + 1 ).copyTo(tempSheet.getRange( sheet.getFrozenRows() + 1, 1 ));
//copy temp sheet to new spreadsheet
tempSheet.copyTo( newSpreadsheet );
//delete Sheet1 in new spreadsheet
newSpreadsheet.getSheetByName('Sheet1').activate();
newSpreadsheet.deleteActiveSheet();
//delete temp sheet
originalSpreadsheet.setActiveSheet(tempSheet);
originalSpreadsheet.deleteActiveSheet();
On my Google Site I've inserted an Apps Script Gadget (by pasting the URL of an Apps Script that I published as a service). This Apps Script allows the user to enter a value (their 'Blow Number') and view the corresponding data (based on API calls to my Google Fusion tables).
Right now, the script returns 3 hyperlinks:
Click here for a table of Blow Number 1
Click here for a chart of Blow Number 1
Click here for a map of Blow Number 1
This is because my script function getblowdetails has 3 app.createAnchor variables. Instead of having the script return 3 hyperlinks (that the user has to click on and view the resulting URL in a new window), I would like for the script to automatically invoke the 3 URLs and display the table, chart, and map in panels on the same page.
So the user would enter their Blow Number and press enter. They would then view the table, chart, and map directly below the text box on the same web page.
Please see the Code that I've included below and advise...Thanks for the help- I'm an apps-script novice so a thorough and understand-able response is greatly appreciated!
Code
Note: I've removed the URLs from the createAnchor variables because I'm only allowed to include 2 links in the post, but you can see them by going to www.OnSiteBAC.com/ViewMyBlows and entering Blow Number = 1...then click on the hyperlinks.
function doGet() {
var app = UiApp.createApplication();
// Create input boxes, buttons, labels, and links
var textBoxA = app.createTextBox().setId('textBoxA').setName('textBoxA').setFocus(true);
var buttonA = app.createButton('Get Blow Details').setEnabled(false);
var label = app.createLabel('Please enter your Blow Number here');
var link = app.createAnchor('where can I find my Blow Number?', 'http://www.onsitebac.com');
// Create a handler to call the getblowdetails function.
// A validation is added to this handler so that it will only invoke 'getblowdetails' if textBoxA contains a number
var handler = app.createServerClickHandler('getblowdetails').validateNumber(textBoxA).addCallbackElement(textBoxA);
// Create a handler to enable the button if all input is legal
var onValidInput = app.createClientHandler().validateNumber(textBoxA).forTargets(buttonA).setEnabled(true).forTargets(label, link).setVisible(false);
// Create a handler to mark invalid input in textBoxA and disable the button
var onInvalidInput1 = app.createClientHandler().validateNotNumber(textBoxA).forTargets(buttonA).setEnabled(false).forTargets(textBoxA).setStyleAttribute("color", "red").forTargets(label, link).setVisible(true);
// Create a handler to mark the input in textBoxA as valid
var onValidInput1 = app.createClientHandler().validateNumber(textBoxA).forTargets(textBoxA).setStyleAttribute("color", "black");
// only fire ServerHandler for onKeyUp if it passes validation
var textBoxHandler = app.createServerHandler('textBoxHandlerFunction');
// Add all the handlers to be called when the user types in the text boxes
textBoxHandler.addCallbackElement(textBoxA);
textBoxA.addKeyUpHandler(onInvalidInput1);
textBoxA.addKeyUpHandler(onValidInput1);
textBoxA.addKeyUpHandler(onValidInput);
textBoxA.addKeyUpHandler(textBoxHandler);
buttonA.addClickHandler(handler);
app.add(textBoxA);
app.add(buttonA);
app.add(label);
app.add(link);
return app;
}
function textBoxHandlerFunction(e) {
var app = UiApp.getActiveApplication();
if (e.parameter.keyCode == 13)
{
app = getblowdetails(e);
}
return app;
}
function getblowdetails(e) {
var app = UiApp.getActiveApplication();
var panel2 = app.createVerticalPanel();
var link2 = app.createAnchor ().setStyleAttribute("color", "green");
var panel3 = app.createVerticalPanel();
var link3 = app.createAnchor ();
var panel4 = app.createVerticalPanel();
var link4 = app.createAnchor ();
panel3.add(link3);
app.add(panel3);
panel4.add(link4);
app.add(panel4);
return app;
}
I don't think you'll be able to actually download the result and show it. So, there's no easy solution.
But you can build that table and chart on Apps Script easily (assuming you can already fetch the info from tables using its API).
The last issue is the map. On Apps Script you can only create static maps, meaning, an image. You can add custom markers and polygons, set the zoom, etc. But in the end it's a photo. The user will not be able to drag it around or use the map as an embedded google map as one would expect.