Google app script - callback confusion - google-apps-script

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.

Related

How to have One URL which sends to one-of-three Google Forms URLs?

I have a need to get equal populations in each of three surveys. The three surveys are identical except for one change - it contains different pictures.
I would like to distribute a single URL to my survey respondents.
I would like to count the number of previous responses I have, and add one.
I would like to redirect the session to one of three (Google Forms) URLs based upon the calculation
(Responses.Count + 1) MOD 3.
I think I need a Google Apps script to do this?
Here is some pseudocode:
var form0 = FormApp.openByUrl(
'htttps://docs.google.com/forms/d/e/2342f23f1mg/viewform'
);
var form1 = FormApp.openByUrl(
'htttps://docs.google.com/forms/d/e/23422333g/viewform'
);
var form2 = FormApp.openByUrl(
'htttps://docs.google.com/forms/d/e/2342wfeijqeovig/viewform'
);
var form0Responses = form0.getResponses();
var form1Responses = form1.getResponses();
var form2Responses = form2.getResponses();
var whichURL = (
form0Responses.length +
form1Responses.length +
form2Responses.length + 1
) % 3; // modulo three
// var goToForm = switch ( whichURL ) blah blah;
// redirect to goToForm;
// How do I redirect now?
Thanks!
Maybe there's a simpler solution possible but I don't think I know of it :)
The common link that you give out could be a link to a "proxy" page that doesn't contain anything but just redirects users to the correct page. Or it could be a link to the actual page with a necessary form embedded. Let's look at the options.
0) Publish your code as web app
In either case you'll need to have your code published as a web app. In GAS it's way simpler than it sounds, you'll find all the info here: https://developers.google.com/apps-script/guides/web
Make sure you set that Anyone, even anonymous can access the app and it always runs as you (if you choose User accessing the app, they'll have to go through authentication process which is not what you need here).
1) Redirect via GAS web app.
Your code in this case would look like so:
// I changed your function a bit so that it could be easier to work with
// in case the number of your forms changes later on
function getForm() {
var forms = [
{
// I'm using openById instead of openByUrl 'cause I've run into issues with
// the latter
form: FormApp.openById('1')
},
{
form: FormApp.openById('2')
},
{
form: FormApp.openById('3')
}
];
var whichURL = 0;
for (var i in forms) {
forms[i].responses = forms[i].form.getResponses().length;
whichURL += forms[i].responses;
}
whichURL++;
// we're returning the actual URL to which we should redirect the visitors
return forms[whichURL % forms.length].form.getPublishedUrl();
}
// doGet is Google's reserved name for functions that
// take care of http get requests to your web app
function doGet() {
// we're creating an html template from which getForm function is called
// as the template is evaluated, the returned result
// of the function is inserted into it
// window.open function is a client-side function
// that will open the URL passed to it as attribute
return HtmlService.createTemplate('<script>window.open("<?= getForm() ?>", "_top");</script>').evaluate();
}
So, after you've published your app, you'll get the link opening which the doGet function will run — and you're going to be redirected to your form.
The thing here is that the URL that you're getting this way is not rather beautiful, sth like https://script.google.com/macros/s/1234567890abcdefghijklmnopqrstuvwxyz/exec and it will also show a message at the top of the page "The app wasn't developed by Google" during those 1-2 seconds before redirect happens.
2) Embed your form into another webpage
The idea here is different: instead of giving your users a "proxy" link, you'll provide them with a page that'll ask a Google script for a correct form link and will display that form in the page in an iframe.
So, there are a couple of steps:
2.1) Change your doGet function (getForm will stay the same):
function doGet() {
return ContentService.createTextOutput(getForm());
}
In this case doGet will not return an html to render by browser but just a link to your form.
Sidenote: after changing the code you'll need to publish a new version of your code for the changes to take effect.
2.2) Create a Google site at sites.google.com
2.3) Insert an "Embed" block into your page, with the following code:
<script>
function reqListener(response) {
// change height and width as needed
document.body.insertAdjacentHTML('beforeend', '<iframe src="' + response.target.response + '" width="400" height="400"></iframe>');
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "INSERT-YOUR-SCRIPT-URL");
oReq.send();
</script>
What it does: javascript code sends an http request to your script, gets the form URL and passes it on into the callback function, reqListener which in turn inserts it into document body within an iframe element.
The good thing is that your URL which will be much more user-friendly (you could use this approach on your own site, too).
As a result, you'll have sth like this:

Using server handlers with modal dialogs

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

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

Using Cache from Server Handler

I am trying to save some user input from a Google App Script form on a spreadsheet to the private cache.
Here is a test script:
var cache = CacheService.getPrivateCache();
function onLoad() {
var sheet = SpreadsheetApp.getActiveSpreadsheet(),
entries = [{
name : "Show form",
functionName : "showForm"
}];
sheet.addMenu("Test Menu", entries);
}
function showForm() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(),
app = UiApp.createApplication(),
setButton = app.createButton("Set"),
setHandler = app.createServerClickHandler('setTest');
setButton.addClickHandler(setHandler);
app.add(setButton);
spreadsheet.show(app);
}
function setTest(event) {
cache.put("test", "test", 7200);
Browser.msgBox("Test was set: " + cache.get("test") + ". Use the getTest cell formula to test the cache.");
}
function getTest() {
var result = cache.get("test");
return result;
}
Once I click the menu button, a form appears and sets a cache value in a server handler. Then I try to get the value from the cache using =getTest() in a cell. I would expect the cache to return the value "test" but it seems to return null.
I started this issue here:
http://code.google.com/p/google-apps-script-issues/issues/detail?id=2039
And I also found another similar one:
http://code.google.com/p/google-apps-script-issues/issues/detail?id=1804
Trying to save some user input on a form into the cache and be able to access it from another function at a later time.
Any suggestions?
Custom functions have limited scope and then can only access a few select services. You read more about their limitations here.
With Cache its a bit tricky - caching is per "script scope". So when a Cache is accessed first from the Server handler script scope its running as a UiApp which has more privileges and that is different from the script scope that a custom function runs as. Therefore, the cache is not shared between those two scopes.
You can access cached items that you set in custom functions from other custom functions, but this cache can't cross these boundaries.
You could theoretically store this in ScripProperties but that can very clumsy and it would be misusing those capabilities and this is shared amongst all users.
ScriptProperties.setProperty("test", "test")
and
var result = ScriptProperties.getProperty("test");
If you can explain your usecase a bit more in depth, perhaps we can provide some alternative solutions.

e.parameter undefined

Q: why is e.parameter.wfId undefined (in the log) after running the script below (as a web-app)
I call script with this URL
https://script.google.com/a/macros/gappspro.com/exec?service=my-webapp-key
without a parameter (&wfId=somecharacters)
function doGet(e) {
var app = UiApp.createApplication().setTitle('Workflow Builder');
var mainGrid = app.createGrid(2,1).setId('FILE_doGet_mainGrid');
app.add(mainGrid);
var wfId = '1234567890' // FILE.doGet.randomString();
mainGrid.setWidget(1,0, app.createTextBox().setValue(wfId).setId('wfId').setName('wfId'));
var handler = app.createServerHandler('func');
handler.addCallbackElement(mainGrid);
Logger.log(e.parameter.wfId);
return app;
}
function func(e) {
return x;
}
I am trying to implement the workflow script from chapter 8 of james ferreira’s book Enterprise Application Essentials and in the add Docs section i ran into the problem that e.parameter.wfId in line “var wfRowArray = FILE.ssOps.getWfRowFromSS(e.parameter.wfId), “ is undefined when running the script. (on page 134 in the book, not the PDF).
In the example above i brought the code back to the essence of what is causing the error,...for me.
e.parameter.wfId is only available in your func(e) function, not in the doGet. the variable e represents the elements of the callBackElement catch by the handler function.
If I have understood your question correctly, this is behaving as expected.
You say "h-ttps://script.google.com/a/macros/gappspro.com/exec?service=my-webapp-key without a parameter (&wfId=somecharacters)"
So, I believe you are not passing any URL parameters to the script URL and therefore you get them as undefined.
If you call your script with the URL parameters, say
h-ttps://script.google.com/a/macros/gappspro.com/exec?service=my-webapp&wfId=somecharacters
then you can expect to see e.parameter.wfld