I'm teaching a class and for my class I keep all of my student's marks on a google spreadsheet. On my website I would like to present information to students on an individual basis. I've created an app where it presents them with a password text box. They type in their password and then it retrieves information from the spreadsheet that is unique to them and presents it to them in a label. I've been trying to hack this all together, but it's just not working properly and I'm getting an error that I cannot diagnose. If I print out the information using Browser.msgBox() it outputs the info, but otherwise it generates an error. Why is this happening and what is the fix? Here's the code:
var pointsSheet = SpreadsheetApp.openById('1o8_f063j1jYZjFEnI_P7uAztpnEAvQ6mc3Z1_Owa69Y');
//creates and shows an app with a label and password text box
function doGet() {
var app = UiApp.createApplication().setTitle('Incomplete Challenges');
var mygrid = app.createGrid(1, 2);
mygrid.setWidget(0, 0, app.createLabel('Password:'));
mygrid.setWidget(0, 1, app.createPasswordTextBox().setName("text"));
var mybutton = app.createButton('Submit');
var submitHandler = app.createServerClickHandler('getResults');
submitHandler.addCallbackElement(mygrid);
mybutton.addClickHandler(submitHandler);
var mypanel = app.createVerticalPanel();
mypanel.add(mygrid);
mypanel.add(mybutton);
app.add(mypanel);
SpreadsheetApp.getActiveSpreadsheet().show(app);
//return app; //UNCOMMENT WHEN DEPLOYING APP
}
//obtains data based on password entered by user and outputs their info
function getResults(eventInfo) {
var app = UiApp.createApplication().setTitle('Incomplete Challenges');
var password = eventInfo.parameter.text;
var passwordCheckRange = pointsSheet.getRange("B34:C34").getValues();
if (passwordCheckRange == null) {
Browser.msgBox("Error: Range is null");
return app;
}
var name;
for(var i = 0; i < passwordCheckRange.length; i++) {
if(passwordCheckRange[i][1] == password) {
name = passwordCheckRange[i][0];
break;
}
}
var studentRecordRange = pointsSheet.getRange("B3:AY29").getValues();
var headingRange = pointsSheet.getRange("B1:AY2").getValues();
if (studentRecordRange == null) {
Browser.msgBox("Error: Range is null");
return app;
}
var requestedRecord;
for(var i = 0; i < studentRecordRange.length; i++) {
if(studentRecordRange[i][0] == name)
requestedRecord = studentRecordRange[i];
}
var stringRecord = "";
for(var i = headingRange[1].length-1; i >= 7; i--) {
if (requestedRecord[i] == "")
stringRecord += headingRange[1][i] + ": " + headingRange[0][i] + "XP" + "\\n";
}
var mygrid = app.createGrid(2, 1);
mygrid.setWidget(0, 0, app.createLabel('INCOMPLETE CHALLENGES'));
mygrid.setWidget(1, 0, app.createLabel(stringRecord));
var mypanel = app.createVerticalPanel();
mypanel.add(mygrid);
app.add(mypanel);
//Browser.msgBox(stringRecord);
return app;
}
The error that I experience is: Error encountered: An unexpected error occurred.
As you can see it's very helpful.
Line 28 it should be getActiveApplication() and not createApplication().
You cant create an application on another application. :)
Also I think line 63 it should be "<br>"; instead "\n"; along with line 68 it should be createHTML instead of createLabel
I also think that you have apply few styling css so that your app looks good. check on .setStyleAttributes in UiApp.
There are a few errors in this code, the first one -that generates the error you get - is (as mentioned in the other answer) the UiApp.createApplication() in the handler function.
You can't create an UiApp instance in a handler function, you should instead get the active instance and eventually add elements to it (using UiApp.getActiveApplication()).
You can't neither change the title of this instance. Btw, it doesn't make sense since this title will not appear as a "title" when you will be deploying this app as a webapp. It will simply show up at the top of your browser window (as a page title) as your app will occupy the whole screen and not a modal popup anymore. So if you want a title to appear in your Ui, simply add it as an HTML widget where you can choose the font size and weight (and any other CSS styles).
The other error is in the password check, you are using Browser.msgBox("Error: Range is null"); but Browser class won't work in UiApp. You should only use UiApp elements, not spreadSheetApp elements.
And, as a more general comment, I suggest you test your app directly using the .dev url (last saved version) of the app (after saving a beta version and having deployed it) so that you are in the "real" use condition and have a pertinent pov on the result.
Related
I have built a tool in google scripts that is currently set up as a bound script to a google docs file. The goal of the tool is to pull in templates from other created docs files from a custom form input. The code works as is as a bound script, but I am trying to port that code over to create an Add-on for users within my organization. The issue right now is that when trying to insert the template elements into the header or footer of the clean test documents, the code throws an error when attempting to append the elements to the saying Cannot call method "appendParagraph" of null.
I have tried appending as a header and footer with DocumentApp.getActiveDocument().getHeader().appendParagraph. This method works when I am using the script as a bound script and it works as expected. When I try to append the paragraph (or other element) to the body instead of the header or footer while testing as an Add-on the elements are appended without issue. The only time I am getting this error is when I try to append the elements to either the header or footer.
function examplefunction_( docLink, locPaste ) {
var srcBody = DocumentApp.openById( docLink )
.getBody();
var srcNumChild = srcBody.getNumChildren();
var activeBody = DocumentApp.getActiveDocument()
.getBody();
var activeHead = DocumentApp.getActiveDocument()
.getHeader();
var activeFoot = DocumentApp.getActiveDocument()
.getFooter();
var a =0;
if ( locPaste == 'Body') {
var activeLoc = activeBody;
}
else if (locPaste == 'Header') {
var activeLoc = activeHead;
}
else if (locPaste == 'Footer') {
var activeLoc = activeFoot;
}
for (var i = 0; i<srcNumChild; i++) {
if (srcBody.getChild(i).getType() == DocumentApp.ElementType.PARAGRAPH) {
var srcText = srcBody.getChild(i).copy();
activeLoc.appendParagraph(srcText);
}
else if (srcBody.getChild(i).getType() == DocumentApp.ElementType.TABLE) {
var srcTable = srcBody.getTables();
var copiedTable = srcTable[a].copy()
a = a + 1;
activeLoc.appendTable(copiedTable);
}
else if (srcBody.getChild(i).getType() == DocumentApp.ElementType.LIST_ITEM) {
var srcList = srcBody.getChild(i).getText();
var listAtt = srcBody.getChild(i).getAttributes();
var nestLvl = srcBody.getChild(i).getNestingLevel();
activeLoc.appendListItem(srcList).setAttributes(listAtt).setNestingLevel(nestLvl);
}
else {
Logger.log("Could not get element: " + i);
}
}
}
I expected the elements to be appended to the headers and footers from the template without error like when run as a bounded script. The actual result while being run kills the process with error "Cannot call method appendParagraph of null." at the line: activeLoc.appendParagraph(srcText);
You cannot append a paragraph to a header or footer, if your document does not have a header or a footer.
Add to the beginning of your function:
if(!DocumentApp.getActiveDocument().getHeader()){
DocumentApp.openById(docLink).addHeader();
}
Same for the footer.
I have the following code which creates a simple app to allow the user to enter two values and click a button:
function start() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
app.setTitle("Appraisals Analysis");
app.setHeight(100);
app.setWidth(500);
var grid = app.createGrid(3, 2);
grid.setId("grid");
grid.setCellSpacing(2);
grid.setCellPadding(2);
var uafLabel = app.createLabel("Unprocessed apparaisals folder name: ");
uafLabel.setStyleAttributes({"font-weight": "bold"});
var uafTextBox = app.createTextBox();
uafTextBox.setName('uafTextBox').setId('uafTextBox');
uafTextBox.setText('Unprocessed Appraisals');
grid.setWidget(0, 0, uafLabel);
grid.setWidget(0, 1, uafTextBox);
var pafLabel = app.createLabel("Processed apparaisals folder name: ");
pafLabel.setStyleAttributes({"font-weight": "bold"});
var pafTextBox = app.createTextBox();
pafTextBox.setName('pafTextBox').setId('pafTextBox');
pafTextBox.setText('Processed Appraisals');
grid.setWidget(1, 0, pafLabel);
grid.setWidget(1, 1, pafTextBox);
var button = app.createButton('Submit').setId("submitButton");
grid.setWidget(2, 0, button);
var mypanel = app.createVerticalPanel();
mypanel.add(grid);
app.add(mypanel);
var clickHandler = app.createServerClickHandler("parseFiles");
button.addClickHandler(clickHandler);
clickHandler.addCallbackElement(grid);
ss.show(app);
}
I then have the parseFiles function which can take up to 2 minutes to do its job as follow
function parseFiles(e) {
var app = UiApp.getActiveApplication();
var processedFolder = DocsList.getFolder(e.parameter.pafTextBox);
var workingFolder = DocsList.getFolder(e.parameter.uafTextBox);
var appraisals = workingFolder.find('Performance Appraisal');
app.getElementById("submitButton").setText("Parsing Files...");
for (var i in appraisals) {
var doc = DocumentApp.openById(appraisals[i].getId());
parseDocument(doc, getEmpName(doc.getName()));
}
return app;
}
My problem is that when I click the button, the work gets done, but the button text stays as "Submit" instead of changing to "Parsing Files...". Once the work is over, then the button changes.
Any idea what I may be doing wrong?
Regards
Crouz
You got nothing wrong, just the concept. Think like this: all Apps Script code you write runs on a google server (server-side), but the interface is (obviously) shown on your computer (client-side). The Apps Script "environment" has a client-side script (that we do not have access or control of) that receives the information on how to build the interface you defined in your code (server-side).
So, everything you do in your code gets updated at once, in a bundle, after your function finishes. And that's why we need to return app, so that our UiApp definition gets sent/returned to the client-side that have triggered the script.
For very simple situations, like disabling or setting the text on a button or label, there's a clientHandler that can perform basic operations on directly the client-side without requiring a network trip to the server-side to run your custom code. Since these operations are done on the client-side they're done "instantly". Note that this is not for generic code, but only predefined operations. clientHandlers are really meant just for simple stuff. It's difficult (if not impossible) to do complex operations.
Here's my suggestion using a clientHandler:
function start() {
//your current code...
clickHandler.addCallbackElement(grid);
var clientHandler = app.createClientHandler().forEventSource().setText('Parsing Files...').setEnabled(false);
button.addClickHandler(clientHandler);
ss.show(app);
}
function parseFiles(e) {
//...
app.getElementById("submitButton").setText("Submit again").setEnabled(true);
//...
return app;
}
Note that you can add multiple handlers, client or server, to a button (or any other widget that accept handlers) and all of them will run concurrently.
Also, it's very important to notice that we're talking about UiApp here, when using HtmlService the approach is significantly different.
Method UiInstance.getElementById(ID) always returns GenericWidget object, even if ID does not exist.
Is there some way how to find out that returned object does not exist in my app, or check whether UI contains object with given ID?
Solution for UI created with GUI builder:
function getSafeElement(app, txtID) {
var elem = app.getElementById(txtID);
var bExists = elem != null && Object.keys(elem).length < 100;
return bExists ? elem : null;
}
It returns null if ID does not exist. I didn't test all widgets for keys length boundary, so be careful and test it with your GUI.
EDIT: This solution works only within doGet() function. It does not work in server handlers, so in this case use it in combination with #corey-g answer.
This will only work in the same execution that you created the widget in, and not in a subsequent event handler where you retrieve the widget, because in that case everything is a GenericWidget whether or not it exists.
You can see for yourself that the solution fails:
function doGet() {
var app = UiApp.createApplication();
app.add(app.createButton().setId("control").addClickHandler(
app.createServerHandler("clicked")));
app.add(app.createLabel(exists(app)));
return app;
}
function clicked() {
var app = UiApp.getActiveApplication();
app.add(app.createLabel(exists(app)));
return app;
}
function exists(app) {
var control = app.getElementById("control");
return control != null && Object.keys(control).length < 100;
}
The app will first print 'true', but on the click handler it will print 'false' for the same widget.
This is by design; a GenericWidget is a "pointer" of sorts to a widget in the browser. We don't keep track of what widgets you have created, to reduce data transfer and latency between the browser and your script (otherwise we'd have to send up a long list of what widgets exist on every event handler). You are supposed to keep track of what you've created and only "ask" for widgets that you already know exist (and that you already know the "real" type of).
If you really want to keep track of what widgets exist, you have two main options. The first is to log entries into ScriptDb as you create widgets, and then look them up afterwards. Something like this:
function doGet() {
var app = UiApp.createApplication();
var db = ScriptDb.getMyDb();
// You'd need to clear out old entries here... ignoring that for now
app.add(app.createButton().setId('foo')
.addClickHandler(app.createServerHandler("clicked")));
db.save({id: 'foo', type: 'button'});
app.add(app.createButton().setId('bar'));
db.save({id: 'bar', type: 'button'});
return app
}
Then in a handler you can look up what's there:
function clicked() {
var db = ScriptDb.getMyDb();
var widgets = db.query({}); // all widgets
var button = db.query({type: 'button'}); // all buttons
var foo = db.query({id: 'foo'}); // widget with id foo
}
Alternatively, you can do this purely in UiApp by making use of tags
function doGet() {
var app = UiApp.createApplication();
var root = app.createFlowPanel(); // need a root panel
// tag just needs to exist; value is irrelevant.
var button1 = app.createButton().setId('button1').setTag("");
var button2 = app.createButton().setId('button2').setTag("");
// Add root as a callback element to any server handler
// that needs to know if widgets exist
button1.addClickHandler(app.createServerHandler("clicked")
.addCallbackElement(root));
root.add(button1).add(button2);
app.add(root);
return app;
}
function clicked(e) {
throw "\n" +
"button1 " + (e.parameter["button1_tag"] === "") + "\n" +
"button2 " + (e.parameter["button2_tag"] === "") + "\n" +
"button3 " + (e.parameter["button3_tag"] === "");
}
This will throw:
button1 true
button2 true
button3 false
because buttons 1 and 2 exist but 3 doesn't. You can get fancier by storing the type in the tag, but this suffices to check for widget existence. It works because all children of the root get added as callback elements, and the tags for all callback elements are sent up with the handler. Note that this is as expensive as it sounds and for an app with a huge amount of widgets could potentially impact performance, although it's probably ok in many cases especially if you only add the root as a callback element to handlers that actually need to verify the existence of arbitrary widgets.
My initial solution is wrong, because it returns false exist controls.
A solution, based on Corey's answer, is to add the setTag("") method and here is ready to use code. It is suitable for event handlers only, because uses tags.
function doGet() {
var app = UiApp.createApplication();
var btn01 = app.createButton("control01").setId("control01").setTag("");
var btn02 = app.createButton("control02").setId("control02").setTag("");
var handler = app.createServerHandler("clicked");
handler.addCallbackElement(btn01);
handler.addCallbackElement(btn02);
btn01.addClickHandler(handler);
btn02.addClickHandler(handler);
app.add(btn01);
app.add(btn02);
return app;
}
function clicked(e) {
var app = UiApp.getActiveApplication();
app.add(app.createLabel("control01 - " + controlExists(e, "control01")));
app.add(app.createLabel("control02 - " + controlExists(e, "control02")));
app.add(app.createLabel("fake - " + controlExists(e, "fake")));
return app;
}
function controlExists(e, controlName) {
return e.parameter[controlName + "_tag"] != null;
}
Can anyone confirm that HTML widgets accept ClickHandlers on the Server side ? I can't get my below code to work.
I create a serverHandler (and for good measure I have even added a useless callback element). Subsequently, I add it to a HTML.addClickHander (for good measure I have even added it to .addMouseUpHandler as well). The function is NOT executed.
var mouseclick = app.createServerHandler("handleTrainingClick_").addCallbackElement(lstFilter);
var params = [ "fromOrg", "trainingTitle", "dueDate", "medical", "status" ];
var resultSet = blSelectActiveTrainings_();
while (resultSet.hasNext()) {
var training = resultSet.next();
var html = TRAINING_ROW;
for (var pI in params) {
html = html.replace("$"+params[pI], training[params[pI]]);
}
pnlList.add(app.createHTML(html).setId(training.id).addClickHandler(mouseclick).addMouseUpHandler(mouseclick)
.addMouseMoveHandler(mousemove).addMouseOutHandler(mouseout).addMouseOverHandler(mouseover));
}
function handleTrainingClick_(e) {
Logger.log(e.source);
var app = UiApp.getActiveApplication();
return app;
}
HTML widgets server side handlers work just fine. It was an incorrect reference in my code. Thanks all.
I have created two user interfaces. How can I close the first one and activate the next? Is it possible to have two UI under Google apps script?
I have try something like:
var app = UiApp.getActiveApplication();
app.add(app.loadComponent("APPGui"));
var panel1 = app.getElementById("LoginPanel1");
panel1.setVisible(false);
return app;
The easiest way is probably to design both panels in the same GUI builder, one over each other in 2 separate panels, the 'login panel' being above the other it will mask the other one when active. As you set it 'invisible', you'll see the one underneath.
Depending on your use case the login panel might hide all or only a part of your main panel.
The GUI builder has all the necessary tools to decide which is in front or backwards.
Here's and example of three dialogs shown one after the other, maintaining state/data between them via the CacheService object.
(You could use UserProperties, ScriptProperties or even a Hidden Field as an alternative, each has their own scope though...)
Hopefully this makes sense without explaining what each dialog in the UI Builder contains.
function showDialog1(){
var app = UiApp.createApplication();
app.add( app.loadComponent("Dialog1") );
SpreadsheetApp.getActiveSpreadsheet().show(app);
}
function onDialog1OKButton(e){
CacheService.getPrivateCache().put("n1", e.parameter.n1);
var app = UiApp.getActiveApplication();
var d2 = app.loadComponent("Dialog2");
app.add(d2);
SpreadsheetApp.getActiveSpreadsheet().show(app);
}
function onDialog2OKButton(e){
var c = CacheService.getPrivateCache();
c.put("n2", e.parameter.n2);
var app = UiApp.getActiveApplication();
app.add(app.loadComponent("DialogResult"));
var n1 = c.get("n1");
var n2 = c.get("n2");
var l = app.getElementById("Label2");
l.setText( "" + n1 + " + " + n2 + " = " + (parseInt(n1) + parseInt(n2)) );
SpreadsheetApp.getActiveSpreadsheet().show(app);
}
I prefer to build multiple GUI. With this code you can jump between them.
function doGet() {
var app = UiApp.createApplication();
var base0 =app.createAbsolutePanel().setId('GUI_base0').setHeight('630px').setWidth('1125px');
app.createAbsolutePanel().setId('GUI_base1'); // create all abs_panells but not use
// you need to create all abspanels if you want to jump between them
app.createAbsolutePanel().setId('GUI_base2'); // create here all the absolute panels (1 for every GUI)
// app.createAbsolutePanel() ... GUI3, GUI4 ...
var component0 = app.loadComponent("GUI_password"); // load first GUI (his name is "password"
/// this is an example of code for the 1st GUI ////////////////////
/// I can check if the user can see the second GUI
var label_ID = app.getElementById('LB_ID');
var user = Session.getActiveUser().getEmail();
if ( user == 'XXX#yyyy.com' ) {
label_ID.setText(user).setTag(user); // only show if ....
}
////////////////////////////////////////////////////////////////////
base0.add(component0); // GUI_password over absolute panel
app.add(base0);
// handler Button1 // we can show a button only if the password is correct or is a valid user or ...
app.getElementById('BT_jump').addClickHandler(app.createServerHandler('NOW_gui1'));
return app;
};
function NOW_gui1(e) {
var app = UiApp.getActiveApplication();
var base0 = app.getElementById("GUI_base0").setVisible(false); // hide 1st abs_panel created with code
var base2 = app.getElementById("GUI_base2").setVisible(false); // hide 3rd abs_panel created with code
/// hide all others abs_panel
var base1 = app.createAbsolutePanel().setId('GUI_base1').setHeight('630px').setWidth('1125px'); // maybe get by ID ??, but this work
var component1 = app.loadComponent("GUI_1"); // load the second GUI
base1.add(component1); // load GUI_1 over 2n absolute panel
app.add(base1);
// HERE THE CODE OF THE GUI_1
// handler Button2
app.getElementById('BT_jump_1_to_2').addClickHandler(app.createServerHandler('NOW_gui2'));
return app;
};