Using server handlers with modal dialogs - google-apps-script

I am displaying a User Interface over a sheet using showModalDialog passing in the app I just created. I also setup a button with a server handler. When server handler function is called I try to get the app again using "UiApp.getActiveApplication()" to hide some elements and show some different elements, however, the changes are not reflected. At the end of the method I tried to close the app, and show a new modal dialog, I tried to return the app, I tried to do nothing, and nothing seems to work.
I can't post my whole code since it is very long, so I made a very simple version that gets the point across. When I put some logging statements in testHandler() it proves that the code is running.
function test() {
var app = UiApp.createApplication().setHeight(700).setWidth(1500);
var label = app.createLabel("Hi").setId("label");
var label2 = app.createLabel("GoodBye").setId("label2").setVisible(false);
var button = app.createButton("Press Me").setId("button");
app.add(label);
app.add(label2);
app.add(button);
var testHandler = app.createServerHandler('testHandler');
testHandler.addCallbackElement(label);
testHandler.addCallbackElement(label2);
button.addClickHandler(testHandler);
SpreadsheetApp.getUi().showModalDialog(app, 'Test');
}
function testHandler() {
var app = UiApp.getActiveApplication();
app.getElementById('label').setVisible(false);
app.getElementById('label2').setVisible(true);
// Not sure what to do now
}
Thank you in advance for your help

return app; //where you are not sure what do do

Related

Google Apps Script Lockservice Not Working

I am calling a sidebar in a Google Sheets bound script. I am trying to prevent multiple users from opening the sidebar at a time. The code below is how I am attempting to achieve this:
function loadM1DocsSideBar() {
var lock = LockService.getScriptLock();
lock.tryLock(0);
if (!lock.hasLock()) {
SpreadsheetApp.getUi().alert("WARNING! Function currently in use by another user. Please try again later.");
return;
}
Logger.log(lock);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Metadata");
var dataRange = sh.getRange("metadataRecord").clearContent();
var form = HtmlService.createHtmlOutputFromFile('M1DocsConfiguratorSidebar').setTitle('Verification Project Library Creator');
SpreadsheetApp.getUi().showSidebar(form);
lock.releaseLock();
}
During testing both first and second users can launch the sidebar at the same time. Can anyone enlighten me where I am going wrong.
Issue:
The script becomes inaccessible only during the brief time the first execution hasn't finished. After that, other users can execute this, even if the sidebar is opened by user #1: the script has already ended execution. The fact that a certain user has the sidebar opened is not registered by your script.
Workaround:
A possible workaround would be using Properties Service to set and retrieve information about whether the sidebar is open, instead of using LockService. The idea would be the following:
When your main function starts, check whether there's a script property SIDEBAR_OPEN equal to true (see getProperty). If that's the case, show your alert and stop the execution. This would be parallel to your current tryLock and hasLock sections.
If the script property is not present, or not equal to true, that means no-one else has opened the sidebar. Your script can now open the sidebar, and set the script property SIDEBAR_OPEN to true (see setProperty.
On your sidebar, have a button that will close the sidebar, and which will as well call a function (setClosedSidebar in the sample below) that will set SIDEBAR_OPEN to false.
Code sample:
function loadM1DocsSideBar() {
var sidebarOpen = isSidebarOpen();
if (sidebarOpen) {
SpreadsheetApp.getUi().alert("WARNING! Function currently in use by another user. Please try again later.");
return;
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Metadata");
var dataRange = sh.getRange("metadataRecord").clearContent();
var form = HtmlService.createHtmlOutputFromFile('M1DocsConfiguratorSidebar').setTitle('Verification Project Library Creator');
setOpenedSidebar();
SpreadsheetApp.getUi().showSidebar(form);
}
function setOpenedSidebar() {
var props = PropertiesService.getScriptProperties();
props.setProperty("SIDEBAR_OPEN", "true");
}
function setClosedSidebar() { // Call me when closing the sidebar
var props = PropertiesService.getScriptProperties();
props.setProperty("SIDEBAR_OPEN", "false");
}
function isSidebarOpen() {
var props = PropertiesService.getScriptProperties();
return JSON.parse(props.getProperty("SIDEBAR_OPEN"));
}
Note:
As a downside to this workaround, this will only work if the sidebar is closed through the button, not by clicking the closing icon nor by refreshing the tab. You should probably set a timeout anyway via Utilities.sleep, so that the sidebar becomes accessible to other users after some time. Be careful with this.
Alternatively, you could use Utilities.sleep to keep the script running for some time after displaying the sidebar, so that other users cannot open the sidebar right after the first user did that.

Multiple Page UI using UiService

I would like to use Google Apps Script UiService to produce a multiple page user interface.
Here's what I've got so far:
function doGet(e)
{
var app=UiApp.createApplication();
var nameLabel=app.createLabel('Name:');
var button=app.createButton("next");//my button on clicking,trying to divert to other UI
var handler=app.createServerHandler("myclick");
button.addClickHandler(handler);
app.add(namelabel);
app.add(button);
return app;
}
function myClick(){
//on clicking the button it should call the other ui or other html page
is there any method for that.}
How can I do this?
You should look at How To Allow Users to Review Answers before Submiting Form?, which has an example that does this.
The idea is to create your UiApp with multiple Panels, then show or hide them in response to user actions, using setVisible(). (If you were using the HtmlService, you would enclose your "pages" in different <div>s, and change their display attributes. See toggle show/hide div with button?.)
The Best Practices also describes use of client-side handlers for responsiveness, so let's try that.
/**
* Very simple multiple page UiApp.
*
* This function defines two panels, which appear to the end user
* as separate web pages. Visibility of each panel is set to
* control what the user sees.
*/
function doGet() {
var app = UiApp.createApplication();
var page1 = app.createFlowPanel().setId('page1');
var page2 = app.createFlowPanel().setId('page2');
// Content for Page 1
page1.add(app.createLabel('Page 1'));
var page1Button = app.createButton('Next Page');
page1.add(page1Button);
// Create client handler to "change pages" in browser
var gotoPage2 = app.createClientHandler()
.forTargets(page1).setVisible(false)
.forTargets(page2).setVisible(true);
page1Button.addClickHandler(gotoPage2);
// Content for Page 2
page2.add(app.createLabel('Page 2'));
var page2Button = app.createButton('Previous Page');
page2.add(page2Button);
// Create client handler to "change pages" in browser
var gotoPage1 = app.createClientHandler()
.forTargets(page1).setVisible(true)
.forTargets(page2).setVisible(false);
page2Button.addClickHandler(gotoPage1);
app.add(page1);
app.add(page2);
// Set initial visibility
page1.setVisible(true);
page2.setVisible(false);
return app;
}
That works for changing the view of the UI. To extend this for general purposes, you would likely want to add server-side handlers to the same buttons to perform work, and update the contents of the panels as things progress.
Here is working code
that demonstrates a multiple page form, i.e. it does the initial doGet() and then lets you advance back and forth doing multiple doPost()'s. All this is done in a single getForm() function called by both the standard doGet() and the doPost() functions.
// Muliple page form using Google Apps Script
function doGet(eventInfo) {return GUI(eventInfo)};
function doPost(eventInfo) {return GUI(eventInfo)};
function GUI (eventInfo) {
var n = (eventInfo.parameter.state == void(0) ? 0 : parseInt(eventInfo.parameter.state));
var ui = ((n == 0)? UiApp.createApplication() : UiApp.getActiveApplication());
var Form;
switch(n){
case 0: {
Form = getForm(eventInfo,n); // Use identical forms for demo purpose only
} break;
case 1: {
Form = getForm(eventInfo,n); // In reality, each form would differ but...
} break;
default: {
Form = getForm(eventInfo,n) // each form must abide by (implement) the hidden state variable
} break;
}
return ui.add(Form);
};
function getForm(eventInfo,n) {
var ui = UiApp.getActiveApplication();
// Increment the ID stored in a hidden text-box
var state = ui.createTextBox().setId('state').setName('state').setValue(1+n).setVisible(true).setEnabled(false);
var H1 = ui.createHTML("<H1>Form "+n+"</H1>");
var H2 = ui.createHTML(
"<h2>"+(eventInfo.parameter.formId==void(0)?"":"Created by submission of form "+eventInfo.parameter.formId)+"</h2>");
// Add three submit buttons to go forward, backward and to validate the form
var Next = ui.createSubmitButton("Next").setEnabled(true).setVisible(true);
var Back = ui.createSubmitButton("Back").setEnabled(n>1).setVisible(true);
var Validate = ui.createSubmitButton("Validate").setEnabled(n>0).setVisible(true);
var Buttons = ui.createHorizontalPanel().add(Back).add(Validate).add(Next);
var Body = ui.createVerticalPanel().add(H1).add(H2).add(state).add(Buttons).add(getParameters(eventInfo));
var Form = ui.createFormPanel().setId((n>0?'doPost[':'doGet[')+n+']').add(Body);
// Add client handlers using setText() to adjust state prior to form submission
// NB: Use of the .setValue(val) and .setValue(val,bool) methods give runtime errors!
var onClickValidateHandler = ui.createClientHandler().forTargets(state).setText(''+(parseInt(n)));
var onClickBackHandler = ui.createClientHandler().forTargets(state).setText(''+(parseInt(n)-1));
Validate.addClickHandler(onClickValidateHandler);
Back.addClickHandler(onClickBackHandler);
// Add a client handler executed prior to form submission
var onFormSubmit = ui.createClientHandler()
.forTargets(state).setEnabled(true) // Enable so value gets included in post parameters
.forTargets(Body).setStyleAttribute("backgroundColor","#EEE");
Form.addSubmitHandler(onFormSubmit);
return Form;
}
function getParameters(eventInfo) {
var ui = UiApp.getActiveApplication();
var panel = ui.createVerticalPanel().add(ui.createLabel("Parameters: "));
for( p in eventInfo.parameter)
panel.add(ui.createLabel(" - " + p + " = " + eventInfo.parameter[p]));
return panel;
}
The code uses a single "hidden" state (here visualized in a TextBox) and multiple SubmitButton's to allow the user to advance forward and backward through the form sequence, as well as to validate the contents of the form. The two extra SubmitButton's are "rewired" using ClientHandler's that simply modify the hidden state prior to form submission.
Notes
Note the use of the .setText(value) method in the client handler's. Using the Chrome browser I get weird runtime errors if I switch to either of the TextBox's .setValue(value) or .setValue(value, fireEvents) methods.
I tried (unsuccessfully) to implement this logic using a Script Property instead of the hidden TextBox. Instead of client handlers, this requires using server handlers. The behavior is erratic, suggesting to me that the asynchronous server-side events are occurring after the form submission event.
You could load different UI's on reading the parameters in your app.
The doGet(e) passes the parameters in the app's url. This way you could call your app with for example: ?myapp=1 (url parameter).
in your doGet you could read that parameter with: e.parameter.myapp
This way you could load different applications depending on the parameters that where passed.
You could just change your button with a link (to your own app, with different url parameters).
You could also do it with buttons and handlers but the above way has my preference.
If you want to use a button<>handler just change you main (first panel) and each time add a completely new panel to your app object. This way you would start from scratch (i.e. create a new application).

Google app script - callback confusion

I'm confused about the behavior of the following code sample.
Why can't I access statusLabelU in the callback via the app object ?
It is available in the argument
BTW, what is the type of the argument variable e in the callback ?
function doGet() {
var app = UiApp.createApplication();
var button = app.createButton('Enter Symbol');
app.add(button);
var symbolText = app.createTextBox().setName('symbolText').setId('symbolText');
app.add(symbolText);
var labelU = app.createLabel('Unknown symbol U')
.setId('statusLabelU');
var labelK = app.createLabel('Unknown symbol K')
.setId('statusLabelK');
app.add(labelU);
app.add(labelK);
var handler = app.createServerHandler('myClickHandler');
handler.addCallbackElement(symbolText);
button.addClickHandler(handler);
return app;
}
function myClickHandler(e) {
var app = UiApp.getActiveApplication();
var symU = app.getElementById('symbolText');
var symK = e.parameter.symbolText;
var financeU = FinanceApp.getStockInfo(symU);
var financeK = FinanceApp.getStockInfo(symK);
var label = app.getElementById('statusLabelU');
label.setText(financeU.name);
var label = app.getElementById('statusLabelK');
label.setText(financeK.name);
app.close();
return app;
}
If you run
labelU.setName('labelU');
handler.addCallbackElement(labelU);
you will be be able to access the value of the label in the callback like so:
var value = e.parameter.labelU;
The argument 'e' (or 'eventInfo') contains information about how the callback was triggered. There is some general information about user ID, x/y position of cursor, and also the source element that triggered the callback. Apart from that, values from widgets that are explicitly added to the handler will be accessible as parameters. You can always check out the content by doing a
Logger.log(e);
and check out the log from the coding environment (cmd/ctrl + return).
Actually you can access statusLabelU in the callback via the app object. What you cannot do (at least I dont know any way) to access the contents of a TextBox except than passing it as a parameter to your event-handler via addCallbackElement (you can also pass a container to addCallbackElement, then all elements in this container are passed to your event-handler). So what happens in your example:
var symU = app.getElementById('symbolText');
returns a kind of Proxy of your TextBox, which returns, when converted to a string 'Generic'.
FinanceApp.getStockInfo('Generic');
then in turn returns undefined, which is then set as Text of your label statusLabelU.
Yeah it took me a while to understand what was going on. The way I finally understood it is this:
The server processes stuff, then serves up UI to the client. Every time the client does something, like click a button, he submits this stuff to the server, but the server has no recollection of what it did before, so all those variables you made prior to serving the UI to the client, it no longer knows.
Thus if you want the server to remember those values it created from before serving the client, then you need to embed them along with the UI sent to the client so that when he does something, the data gets sent back to the server.
That embedded crap is considered a hidden callback element, something the user doesn't interact with, and is solely there to pass it back to the server during the next processing action. The 'normal' callback elements are data the server doesn't know yet, such as form elements (names, addresses, etc). It will need to know this information once the user hits the submit button to process it, so that's why it's called callback info.

google apps script - web app doesn't seem to do anything . .

I'm a Java developer but I did a small site for a non-profit group using Google Sites. I have a form I'd like to be somewhat dynamic and Google Apps Script seemed to be a viable option. As frequently happens when one is learning a new technology, I copied and pasted the code below from a tutorial/documentation. I then published it, and inserted the script widget into a page on the site and saved the page. When I reload the page, the "place holder" for the widget is there, but nothing happens - no buttons, no panel, nothing. Same results when I run it from the script editor. I'm sure I'm missing something obvious, but I haven't been able to get the UI to render at all. A little direction would be greatly appreciated.
thanks in advance!
function doGet(e) {
Logger.log("Executing the doGet() method . . .");
var app = UiApp.createApplication();
var aPanelRoot = app.createVerticalPanel();
var button = app.createButton('Click Me');
aPanelRoot.add(button);
var label = app.createLabel('The button was clicked.');
label.setId('statusLabel');
aPanelRoot.add(label);
var handler = app.createServerHandler('myClickHandler');
handler.addCallbackElement(label);
button.addClickHandler(handler);
aPanelRoot.setVisible(true);
return app;
}
function myClickHandler(e) {
var app = UiApp.getActiveApplication();
var label = app.getElementById('statusLabel');
label.setVisible(true);
//app.close();
return app;
}
It seems that you simply forgot to add aPanelRoot to the app in the doGet() function
app.add(aPanelRoot)
also : by default all widgets are visibles so you can remove all the setVisible(true) statements as they are only necessary if you set them to false somewhere else...
And if I may add a last comment, it's generally a good idea to choose the parent widget as callbackElement so you don't risk to forget to add elements when you begin to have lots of them (all children are automatically included in the parent) .

Improve my script run time

Is there anyway to improve my script run time? I have a script that creates 2 listboxes: Listbox1 items is all my google site pages, listbox2 items is the sub-pages of listbox1 page. The script runs fine but sometimes it takes between 2 and 5 seconds to get all of the listbox2 items.
You can try my script here.
And here is my script:
function doGet()
{
var app = UiApp.createApplication();
//GUI with 2 listbox
//Listbox1: onclick > lbox1onclick(e), onchange > lbox1onchange(e)
app.add(app.loadComponent("MyUrlParser"));
var lbox1 = app.getElementById('ListBox1');
lbox1.addItem(' ');
var lbox1_Item = SitesApp.getSite('phichdaica').getChildByName('manga').getChildren();
for(var i = lbox1_Item.length-1; i >= 0; i--)
{
lbox1.addItem(lbox1_Item[i].getTitle());
}
return app;
}
function lbox1onclick(e)
{
var app = UiApp.getActiveApplication();
var lbox2 = app.getElementById('ListBox2');
lbox2.clear();
return app;
}
function lbox1onchange(e)
{
var app = UiApp.getActiveApplication();
// var value = e.parameter.lbox1;
var lbox1value = e.parameter.ListBox1;
var lbox2 = app.getElementById('ListBox2');
var lbox2_Item = SitesApp.getSite('phichdaica').getChildByName('manga').getChildByName(lbox1value).getChildren();
for(var i=lbox2_Item.length-1; i >= 0; i--)
{
lbox2.addItem(lbox2_Item[i].getTitle());
}
return app;
}
I don't think it will speed up the process but you could use just one handler function to do that : on change listBox1, clear listBox 2 and re-populate it immediately. What is taking some time is the call to site's content so the difference might not be significative but the 'logic' of your script would be improved ;-)
Looking at your page, I see that listBox 2 is never cleared... is that a temporary issue ? Did you change something recently ?
Also, what is supposed to happen when something is selected in listBox2 ?
EDIT : following your comment, if you want to improve user experience concerning the 'responsiveness' of your UI the best way is to use client handlers to trigger the visibility of a 'wait message' for example(something like "Updating the list"). I usually use an animated gif that I made visible with a client handler and that is made invisible again when the server handler returns (ie I set it invisible in the server handler function).
here is a working example, just try to change the date in the upper right corner.