So I have an app script gadget embedded in a google site. What the app script does is get objects from scriptdb and display it on the screen. There also is an add button clicking on which you get a form to enter information and add objects. What I am trying to do is that after an object is saved, I repopulate the object and display them so the newly created object can be seen without manually refreshing the page.
I have a function called update() that is called after an object is saved and this function takes care of the "auto refresh".
In the save() function, I call the update function with this syntax, update(). Here is the submit() function
function SaveAssignment(e){
var db = ScriptDb.getMyDb();
var app = UiApp.getActiveApplication();
var name = e.parameter.assignmentname;
var date = e.parameter.assignmentdate.toString();
var desc = e.parameter.assignmentdesc;
var category = e.parameter.assignmentcategory;
var totalscore = e.parameter.assignmenttotalscore;
var site = SitesApp.getActiveSite();
var assignment = { name: name,
date: date,
description: desc,
url: pageUrl + '?name='+name+'&date='+date+'&description='+desc+'&id='+sheetId,
sheetid: sheetId,
totalScore: totalscore,
Category: category
};
db.save(assignment);
update();
}
and here is my update() method
function update(){
var app = UiApp.createApplication();
var oldGrid = app.getElementById('grid');
app.remove(oldGrid);
var handler = app.createServerHandler('AddAssignment');
var addAssignmentButton = app.createButton('Add Assignment', handler);
var assignments = db.query({});
var i = 1;
var j = 1;
var grid;
if(assignments.getSize() < 1){
grid = app.createGrid(3, 5).setId('grid');
}
else{
grid = app.createGrid(assignments.getSize() + assignments.getSize() + assignments.getSize(), 5).setId('grid');
}
handler.addCallbackElement(grid);
grid.setWidget(0, 2, addAssignmentButton);
while(assignments.hasNext()){
var assignment = assignments.next();
var name = assignment.name;
var date = assignment.date;
var description = assignment.description;
var nameLabel = app.createLabel('Assignment ' + i + ' : ' + name).setVisible(true);
var dateLabel = app.createLabel('Date: ' + date).setVisible(true);
var idLabel = app.createLabel(assignment.getId()).setVisible(false);
var deletebutton = app.createButton('Delete Assignment');
var handler = app.createServerHandler('deleteAssignment');
handler.addCallbackElement(idLabel);
deletebutton.addClickHandler(handler);
grid.setWidget(j, 0, nameLabel);
j = j + 1;
grid.setWidget(j, 0, dateLabel);
grid.setWidget(j, 1, deletebutton);
grid.setWidget(j, 3, idLabel);
i++;
j = j + 2;
}
app.add(grid);
return app;
I made some little test on your code. you need to do some little changes:
You need to change "var app = UiApp.createApplication();" for "var app = UiApp.getActiveApplication()" (already saw that in comment).
You didn't declared "db" your script will systematically be in error if you don't correct that.
Bellow your code where the update function actually update the grid:
function doGet(){
var app = UiApp.createApplication();
var grid = app.createGrid(3, 3).setId("grid").setWidget(1, 2, app.createLabel("test"));
grid.addClickHandler(app.createServerHandler("update"));
app.add(grid);
return(app);
}
function update(){
var app = UiApp.getActiveApplication(); // getActiveApplication
var oldGrid = app.getElementById('grid');
app.remove(oldGrid);
var handler = app.createServerHandler('AddAssignment');
var addAssignmentButton = app.createButton('Add Assignment', handler);
var db = ScriptDb.getMyDb();
var assignments = db.query({}); // YOU DIDNT DECLARED db
var i = 1;
var j = 1;
var grid;
if(assignments.getSize() < 1){
grid = app.createGrid(3, 5).setId('grid');
}
else{
grid = app.createGrid(assignments.getSize() + assignments.getSize() + assignments.getSize(), 5).setId('grid'); // assignments.getSize()*3
}
handler.addCallbackElement(grid);
grid.setWidget(0, 2, addAssignmentButton);
while(assignments.hasNext()){
var assignment = assignments.next();
var name = assignment.name;
var date = assignment.date;
var description = assignment.description;
var nameLabel = app.createLabel('Assignment ' + i + ' : ' + name).setVisible(true);
var dateLabel = app.createLabel('Date: ' + date).setVisible(true);
var idLabel = app.createLabel(assignment.getId()).setVisible(false);
var deletebutton = app.createButton('Delete Assignment');
var handler = app.createServerHandler('deleteAssignment');
handler.addCallbackElement(idLabel);
deletebutton.addClickHandler(handler);
grid.setWidget(j, 0, nameLabel);
j = j + 1;
grid.setWidget(j, 0, dateLabel);
grid.setWidget(j, 1, deletebutton);
grid.setWidget(j, 3, idLabel);
i++;
j = j + 2;
}
app.add(grid);
return app;
}
Related
I have read through the official documentation that states, you are not allowed to use services that require authorization such as SpreadsheetApp.openById within a custom function.
I am using a script to call a spreadsheet in its functions and it's doing that fluently. My custom function is not using the service SpreadsheetApp.openById, but still tells me that I do not have the permission. I just want to know whether it is possible to run the custom function or not, even though I am not calling a spreadsheet in the function itself?
Updated:
My custom function build's a reference id for a particular quotation.
I've also tried using https://www.googleapis.com/auth/spreadsheets in oauthScopes in the json file, didn't work.
This is the function calling openById:
var ss1 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var dukeid = "1WGbEo1Xr99HwHY_4ZaeTRIgCOuNcjVfqCzZx4dcQX4I"
var duke = SpreadsheetApp.openById(dukeid);
var totalstockd = duke.getSheetByName("Total Stock").getRange(2,3,2500,7).getValues();
var avmid = "1a6bm2O_iljHZUoF2BhYeyxUT13tB06-JJCYeYCZZ10Q"
var avm = SpreadsheetApp.openById(avmid);
var totalstocka = avm.getSheetByName("Total Stock").getRange(2,3,1000,7).getValues();
function when(e){
var activeCell = e.range;
var val = activeCell.getValue();
var r = activeCell.getRow();
var c = activeCell.getColumn();
var ssName = activeCell.getSheet().getName();
if (ssName=="General Information" && (r==3 || r==6) && c==3){
var rescell = ss1.getRange(r,6);
var unitcell = ss1.getRange(r,7);
rescell.clearContent();
if(val[0]=="A"){
var result = sumalt(val,totalstocka,unitcell);
rescell.setValue(result);
}
else {
var result = sumalt(val,totalstockd,unitcell);
rescell.setValue(result);
}
}
else{
console.log("No Edit");
}
}
And this is my custom function:
function QREF(Company,ID){
var td=new Date().valueOf();
var year = new Date().getFullYear();
var hd=new Date(year, 0, 0).valueOf();
var year2 = year - 2000
var sec=1000;
var min=60*sec;
var hour=60*min;
var day=24*hour;
var diff=td-hd;
var julian=Math.floor(diff/day);
Logger.log(year2);
string = Company + ID + "-"+ "" + julian + "/" + year2 + "-";
return string;
}
Modification points:
When I saw your script, I noticed that SpreadsheetApp.openById is used as the global. By this, when your custom function is run, SpreadsheetApp.openById is run. So, such error occurs. I think that this is the reason of your issue.
When you want to use both script in your Google Apps Script, how about the following modification?
Modified script:
function when(e) {
// These scripts are included in a function.
var ss1 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var dukeid = "1WGbEo1Xr99HwHY_4ZaeTRIgCOuNcjVfqCzZx4dcQX4I"
var duke = SpreadsheetApp.openById(dukeid);
var totalstockd = duke.getSheetByName("Total Stock").getRange(2, 3, 2500, 7).getValues();
var avmid = "1a6bm2O_iljHZUoF2BhYeyxUT13tB06-JJCYeYCZZ10Q"
var avm = SpreadsheetApp.openById(avmid);
var totalstocka = avm.getSheetByName("Total Stock").getRange(2, 3, 1000, 7).getValues();
var activeCell = e.range;
var val = activeCell.getValue();
var r = activeCell.getRow();
var c = activeCell.getColumn();
var ssName = activeCell.getSheet().getName();
if (ssName == "General Information" && (r == 3 || r == 6) && c == 3) {
var rescell = ss1.getRange(r, 6);
var unitcell = ss1.getRange(r, 7);
rescell.clearContent();
if (val[0] == "A") {
var result = sumalt(val, totalstocka, unitcell);
rescell.setValue(result);
} else {
var result = sumalt(val, totalstockd, unitcell);
rescell.setValue(result);
}
} else {
console.log("No Edit");
}
}
function QREF(Company, ID) {
var td = new Date().valueOf();
var year = new Date().getFullYear();
var hd = new Date(year, 0, 0).valueOf();
var year2 = year - 2000
var sec = 1000;
var min = 60 * sec;
var hour = 60 * min;
var day = 24 * hour;
var diff = td - hd;
var julian = Math.floor(diff / day);
Logger.log(year2);
string = Company + ID + "-" + "" + julian + "/" + year2 + "-";
return string;
}
By this modification, when QREF() is run as the custom function, SpreadsheetApp.openById is not run. By this, such error can be removed.
Note:
If you are using the following script at other function, please be careful this. In that case, please include the script to the function. Or, please include the following script as new function, and call the function from other function.
var ss1 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var dukeid = "1WGbEo1Xr99HwHY_4ZaeTRIgCOuNcjVfqCzZx4dcQX4I"
var duke = SpreadsheetApp.openById(dukeid);
var totalstockd = duke.getSheetByName("Total Stock").getRange(2, 3, 2500, 7).getValues();
var avmid = "1a6bm2O_iljHZUoF2BhYeyxUT13tB06-JJCYeYCZZ10Q"
var avm = SpreadsheetApp.openById(avmid);
var totalstocka = avm.getSheetByName("Total Stock").getRange(2, 3, 1000, 7).getValues();
After getting interested in a code proposed on Github to get WooCommerce orders in Google Sheets: https://github.com/mithunmanohar/woocommerce-orders-google-sheets-integration
I integrated this code in a sheet with its script but this code has a defect: when updating the status of an order the script adds an extra line instead of changing the status of the line corresponding to the order.
We get a duplicate as you can see here :
Same ID but statut different
You can find the complete code of the script here: https://github.com/mithunmanohar/woocommerce-orders-google-sheets-integration/blob/master/wc-gc-integration.gs
// Updated code to v2 Woocommerce API
function start_syncv2() {
var sheet_name = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
fetch_orders(sheet_name)
}
function fetch_orders(sheet_name) {
var ck = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name).getRange("B4").getValue();
var cs = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name).getRange("B5").getValue();
var website = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name).getRange("B3").getValue();
var manualDate = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name).getRange("B6").getValue(); // Set your order start date in spreadsheet in cell B6
var m = new Date(manualDate).toISOString();
var surl = website + "/wp-json/wc/v2/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&after=" + m + "&per_page=100";
var url = surl
//Logger.log(url)
var options =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
Logger.log(result.getResponseCode())
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
//Logger.log(params);
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
var consumption = {};
var arrayLength = params.length;
for (var i = 0; i < arrayLength; i++) {
var a, c, d;
var container = [];
a = container.push(params[i]["billing"]["first_name"]);
a = container.push(params[i]["billing"]["last_name"]);
a = container.push(params[i]["billing"]["address_1"]+ " "+ params[i]["billing"]["postcode"]+ " "+ params[i]["billing"]["city"]);
a = container.push(params[i]["shipping"]["first_name"] + " "+ params[i]["shipping"]["last_name"]+" "+ params[i]["shipping"]["address_2"]+" "+ params[i]["shipping"]["address_1"]+" "+params[i]["shipping"]["postcode"]+" "+params[i]["shipping"]["city"]+" "+params[i]["shipping"]["state"]+" "+params[i]["shipping"]["country"]);
a = container.push(params[i]["billing"]["phone"]);
a = container.push(params[i]["billing"]["email"]);
a = container.push(params[i]["customer_note"]);
a = container.push(params[i]["payment_method_title"]);
c = params[i]["line_items"].length;
var items = "";
var total_line_items_quantity = 0;
for (var k = 0; k < c; k++) {
var item, item_f, qty, meta;
item = params[i]["line_items"][k]["name"];
qty = params[i]["line_items"][k]["quantity"];
item_f = qty + " x " + item;
items = items + item_f + ",\n";
total_line_items_quantity += qty;
}
a = container.push(items);
a = container.push(total_line_items_quantity); // Quantity
a = container.push(params[i]["total"]); //Price
a = container.push(params[i]["discount_total"]); // Discount
d = params[i]["refunds"].length;
var refundItems = "";
var refundValue = 0.0;
for (var r = 0; r < d; r++) {
var item, item_f, value;
item = params[i]["refunds"][r]["reason"];
value = params[i]["refunds"][r]["total"];
refundValue += parseFloat(value);
item_f = value +" - "+ item;
refundItems += item_f + ",\n";
}
a = container.push(refundValue); //Refunded value from order
a = container.push(parseFloat(container[10]) + refundValue); // Total minus refund
a = container.push(refundItems); //Refunded items from order
a = container.push(params[i]["id"]);
a = container.push(params[i]["date_created"]);
a = container.push(params[i]["date_modified"]);
a = container.push(params[i]["status"]);
a = container.push(params[i]["order_key"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
temp.appendRow(container);
Logger.log(params[i]);
removeDuplicates(sheet_name);
}
}
function removeDuplicates(sheet_name) {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName(sheet_name);
var data = sheet.getDataRange().getValues();
var newData = new Array();
for (i in data) {
var row = data[i];
/* TODO feature enhancement in de-duplication
var date_modified =row[row.length-2];
var order_key = row[row.length];
var existingDataSearchParam = order_key + "/" + date_modified;
*/
var duplicate = false;
for (j in newData) {
var rowNewData = newData[j];
var new_date_modified =rowNewData[rowNewData.length-2];
var new_order_key = rowNewData[rowNewData.length];
//var newDataSearchParam = new_order_key + "/" + new_date_modified; // TODO feature enhancement in de-duplication
if(row.join() == newData[j].join()) {
duplicate = true;
}
// TODO feature enhancement in de-duplication
/*if (existingDataSearchParam == newDataSearchParam){
duplicate = true;
}*/
}
if (!duplicate) {
newData.push(row);
}
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
I am new to google script. I have a datasource that I need to display in a table and allow user to select a row and select open button. the event handler of the open button should be able to find out the row number so that I will be able to send a request with the name user chosen.
I thought of adding a check box and on the click event, simply read the name of the checkbox which has the row number.
Please let me know how to do this. thanks
var panel = app.createVerticalPanel();
var scroll = app.createScrollPanel().setPixelSize(500, 300);
scroll.add(panel);
var flexTable = app.createFlexTable().setStyleAttribute('border', '1px solid black')
.setStyleAttribute('borderCollapse','collapse')
.setBorderWidth(1);
flexTable.setText(0, 1, 'Application Name')
flexTable.setRowStyleAttribute(0,'color', 'blue')
flexTable.setText(0, 2, 'Owner')
flexTable.setText(0, 3, 'Date')
var handler = app.createServerClickHandler('clickTable');
var counter = 1;
for (var i in queryResult.records) {
var chkBox = app.createCheckBox().setName('chk' + counter).setId('chk');
var owner = queryResult.records[i]["Owner"]["Name"];
var AppName = queryResult.records[i]["Name"];
var ModifiedDate = queryResult.records[i]["LastModifiedDate"]
var UniqId = queryResult.records[i]["Apttus_XApps__UniqueId__c"]
flexTable.setWidget(counter, 0 , chkBox)
flexTable.setText(counter, 1, AppName.toString());
flexTable.setText(counter, 2, owner.toString());
flexTable.setText(counter, 3, ModifiedDate.toString());
counter ++;
}
panel.add(app.createButton('Open', handler));
panel.add(flexTable);
app.add(scroll);
You have only created server handler, but no callback elements are attached to it. Please have a look at this page
So your code will be like.
var handler = app.createServerClickHandler('clickTable');
handler.addCallbackElement(panel)
Next: at your server function clickTable
function clickTable(e)
{
for (var i in e.parameter) {
Logger.log('parameter ' + i+1 + ' is ' + e.parameter[i]);
}
//try logging all the values that are passed and use it accordingly,
}
Here is an example of an implementation I suggested in comments above using radioButtons.
User can only submit if one option has been selected
test online here
code :
function doGet(){
var app = UiApp.createApplication();
var panel = app.createVerticalPanel().setStyleAttributes({'padding':'15px'});
var handler = app.createServerClickHandler('clickTable').addCallbackElement(panel);
var btn = app.createButton('Open', handler).setEnabled(false);
panel.add(btn);
var scroll = app.createScrollPanel().setPixelSize(500, 400);
scroll.add(panel);
var flexTable = app.createFlexTable().setStyleAttribute('border', '1px solid black')
.setStyleAttributes({'borderCollapse':'collapse'})
.setBorderWidth(1).setCellPadding(2);
flexTable.setText(0, 1, 'Application Name')
flexTable.setRowStyleAttribute(0,'color', 'blue')
flexTable.setText(0, 2, 'Owner')
flexTable.setText(0, 3, 'Date')
var radioValue = app.createTextBox().setName('radioValue').setVisible(false);// set it to visible if you want to see what happens in tests
panel.add(radioValue);
var counter = 1;
for (var i =0;i<10;i++) {
var name = counter;
var radio = app.createRadioButton('radioBtn','select');
var CliHandler = app.createClientHandler().forTargets(radioValue).setText(name).forTargets(btn).setEnabled(true);
radio.addClickHandler(CliHandler);
// var owner = queryResult.records[i]["Owner"]["Name"];
// var AppName = queryResult.records[i]["Name"];
// var ModifiedDate = queryResult.records[i]["LastModifiedDate"]
// var UniqId = queryResult.records[i]["Apttus_XApps__UniqueId__c"]
// temp var definitions for test
var owner = 'test';
var AppName = 'test';
var ModifiedDate = 'test';
var UniqId = 'test';
// delete in production code
flexTable.setWidget(counter, 0 , radio)
flexTable.setText(counter, 1, AppName.toString());
flexTable.setText(counter, 2, owner.toString());
flexTable.setText(counter, 3, ModifiedDate.toString());
counter ++;
}
panel.add(flexTable);
app.add(scroll);
return app;
}
function clickTable(e){
var app = UiApp.getActiveApplication();
app.add(app.createLabel('you have selected item nr '+e.parameter.radioValue));
return app
}
Is there any way to add an app script that I created to a StackPanel? or do I have to create the StackPanel integrated with the existing app script code?
function doGet() {
var app = UiApp.createApplication();
//Create stack panel
var stackPanel = app.createStackPanel().setSize('100%', '100%');
//add widgets to each stack panel, and name the stack panel
stackPanel.add(, 'Instructions: Scheduling the Lab');
stackPanel.add(, 'Lab Calendar');
stackPanel.add(, 'Lab Request Form');
//Add the panel to the application
app.add(stackPanel);
return app;
}
You can in a way but there can be only one Uinstance in a webapp so instead of returning app in each function that builds a stackPanel you'll have to return a widget that will be added to each stackPanel. The functions can be in different script files but must be part of the same project.
Your app will need a few modifications : see the code below (look also at the end of the formBuild function that has changed a bit ;-).
function doGet() {
var app = UiApp.createApplication().setTitle('DHS: Kurzweil Calendar');
//Create stack panel
var stackPanel = app.createStackPanel().setSize('100%', '100%');
var form = formBuild(app);
var p1 = app.createVerticalPanel().setId('Panel1').add(form);
var cal = calendar(app);
var p2 = app.createVerticalPanel().setId('Panel2').add(cal);
var ins = instruction(app);
var p3 = app.createVerticalPanel().setId('Panel3').add(ins);
//add widgets to each stack panel, and name the stack panel
stackPanel.add(p1, 'Instructions: Scheduling the Lab');
stackPanel.add(p2, 'Lab Calendar');
stackPanel.add(p3, 'Lab Request Form');
//Add the panel to the application
app.add(stackPanel);
return app;
}
function instruction(app){
var lab = app.createLabel('label').setPixelSize(100,100);
return lab
}
function calendar(app){
return app.createLabel('label').setPixelSize(100,100);
}
function formBuild(app) {
//Create a panel which holds all the form elelemnts
var vrtMainPanel = app.createVerticalPanel().setId('vrtMainPanel');
//Create Spreadsheet Source
var spSheet = SpreadsheetApp.openById('0AnqSFd3iikE3dEtBQndOYVNEbFVWcDlyQmFoaUV3a1E');
var spTeacherList = spSheet.getSheetByName('TeacherList');
var spSubjectList = spSheet.getSheetByName('SubjectList');
var spPeriodList = spSheet.getSheetByName('PeriodList');
var spCountList = spSheet.getSheetByName('CountList');
//Create the form elements
var hdlTeacherName = app.createServerHandler('getTeacherName').addCallbackElement(vrtMainPanel);
var lbxTeacherName = app.createListBox().setId('lbxTeacherName').setName('lbxTeacherName').addChangeHandler(hdlTeacherName);
var lstTeacherNames = spTeacherList.getRange(1,1,spTeacherList.getLastRow(),1).getValues();
lstTeacherNames.sort();
for (var l = 0; l < lstTeacherNames.length; l++) {
lbxTeacherName.addItem(lstTeacherNames[l],l);
}
var lblTeacherName = app.createLabel('Teacher Name:');
var txtTeacherName = app.createTextBox().setName('txtTeacherName').setId('txtTeacherName').setVisible(false);
var vldTeacherName = app.createLabel().setId('vldTeacherName').setVisible(false);
var lblExt = app.createLabel('Ext:');
var txtExt = app.createTextBox().setName('txtExt').setId('txtExt');
var vldExt = app.createLabel().setId('vldExt').setVisible(false);
//Set DateBox to Tomorrow's Date
var tomorrow =new Date(new Date(new Date().setHours(0,0,0,0)).setDate(new Date().getDate() + 1));// set hours, min, sec & milliSec to 0 and day=day+1
Logger.log(tomorrow);
var lblDate = app.createLabel('Date of Test:');
var boxDate = app.createDateBox().setId('boxDate').setName('boxDate').setFormat(UiApp.DateTimeFormat.DATE_SHORT).setValue(tomorrow);
var vldDate = app.createLabel().setId('vldDate').setVisible(false);
var lbxSubject = app.createListBox().setId('lbxSubject').setName('lbxSubject');
var vldSubject = app.createLabel().setId('vldSubject').setVisible(false);
var lstSubjects = spSubjectList.getRange(1,1,spSubjectList.getLastRow(),1).getValues();
lstSubjects.sort();
for (var l = 0; l < lstSubjects.length; l++) {
lbxSubject.addItem(lstSubjects[l]);
}
var lbxPeriod = app.createListBox().setId('lbxPeriod').setName('lbxPeriod');
var vldPeriod = app.createLabel().setId('vldPeriod').setVisible(false);
var lstPeriods = spPeriodList.getRange(1,1,spPeriodList.getLastRow(),1).getValues();
lstPeriods.sort();
for (var l = 0; l < lstPeriods.length; l++) {
lbxPeriod.addItem(lstPeriods[l]);
}
var lblStudentNum = app.createLabel('Number of Students:');
var vldStudentNum = app.createLabel().setId('vldStudentNum').setVisible(false);
var lbxStudentNum = app.createListBox().setId('lbxStudentNum').setName('lbxStudentNum');
var lstStudentNums = spCountList.getRange(1,1,spCountList.getLastRow(),1).getValues();
lstStudentNums.sort();
for (var l = 0; l < lstStudentNums.length; l++) {
lbxStudentNum.addItem(lstStudentNums[l]);
}
var txtSourceGrp = app.createTextBox().setName('txtSourceGrp').setVisible(false);
var txtTypeGrp = app.createTextBox().setName('txtTypeGrp').setVisible(false);
var vldSourceGrp = app.createLabel().setId('vldSourceGrp').setVisible(false);
var vldTypeGrp = app.createLabel().setId('vldTypeGrp').setVisible(false);
var txtElementsID = app.createTextBox().setName('txtElementsID').setText('Elements Test ID').setVisible(false);
var txtQuiaLink = app.createTextBox().setName('txtQuiaLink').setText('Quia Test Link').setVisible(false);
var txtQuiaPass = app.createTextBox().setName('txtQuiaPass').setText('Quia Test Passphrase').setVisible(false);
//Create Source Radio Button Group
var radHCopy = app.createRadioButton('group1', 'Hard-Copy').setFormValue('Hard-Copy').addClickHandler(app.createClientHandler().forTargets(txtSourceGrp).setText('Hard-Copy'));
var radECopy = app.createRadioButton('group1', 'Electronic-Copy').setFormValue('Electronic-Copy').addClickHandler(app.createClientHandler().forTargets(txtSourceGrp).setText('Electronic-Copy'));
//Create Type Radio Button Group
var radTExam = app.createRadioButton('group2', 'Teacher-Made Exam').setFormValue('Teacher-Made Exam').addClickHandler(app.createClientHandler().forTargets(txtTypeGrp).setText('Teacher-Made Exam'));
var radEExam = app.createRadioButton('group2', 'Elements Exam').setFormValue('Elements Exam').addClickHandler(app.createClientHandler().forTargets(txtTypeGrp).setText('Elements Exam'));
var radQExam = app.createRadioButton('group2', 'Quia Exam').setFormValue('Quia Exam').addClickHandler(app.createClientHandler().forTargets(txtTypeGrp).setText('Quia Exam'));
var btnCreate = app.createButton('Create Event');
//Client Handlers for textBoxes
var showTxtElementHandler = app.createClientHandler().forTargets(txtElementsID).setVisible(true);
var hideTxtElementHandler = app.createClientHandler().forTargets(txtElementsID).setVisible(false);
var vldElementsID = app.createLabel().setId('vldElementsID').setVisible(false);
radEExam.addClickHandler(showTxtElementHandler);
radTExam.addClickHandler(hideTxtElementHandler);
radQExam.addClickHandler(hideTxtElementHandler);
var showTxtQuiaLinkHandler = app.createClientHandler().forTargets(txtQuiaLink).setVisible(true);
var hideTxtQuiaLinkHandler = app.createClientHandler().forTargets(txtQuiaLink).setVisible(false);
var vldQuia = app.createLabel().setId('vldQuia').setVisible(false);
radQExam.addClickHandler(showTxtQuiaLinkHandler);
radTExam.addClickHandler(hideTxtQuiaLinkHandler);
radEExam.addClickHandler(hideTxtQuiaLinkHandler);
var showTxtQuiaPassHandler = app.createClientHandler().forTargets(txtQuiaPass).setVisible(true);
var hideTxtQuiaPassHandler = app.createClientHandler().forTargets(txtQuiaPass).setVisible(false);
radQExam.addClickHandler(showTxtQuiaPassHandler);
radTExam.addClickHandler(hideTxtQuiaPassHandler);
radEExam.addClickHandler(hideTxtQuiaPassHandler);
//Create validation handler
var valSubmit = app.createServerClickHandler('valSubmit');
valSubmit.addCallbackElement(vrtMainPanel);
//Add this handler to the button
btnCreate.addClickHandler(valSubmit);
//Add all the elemnts to the panel
var formGrid = app.createGrid(18,3).setCellPadding(3);
vrtMainPanel.add(formGrid);
formGrid
.setWidget(0,0,vldTeacherName)
.setWidget(0,1,vldExt)
.setWidget(1,0,lbxTeacherName)
.setWidget(1,1,txtExt)
.setWidget(1,2,txtTeacherName)
.setWidget(2,0,vldPeriod)
.setWidget(2,1,vldSubject)
.setWidget(3,0,lbxPeriod)
.setWidget(3,1,lbxSubject)
.setWidget(4,1,vldDate)
.setWidget(5,0,lblDate)
.setWidget(5,1,boxDate)
.setWidget(1,1,vldStudentNum)
.setWidget(7,0,lblStudentNum)
.setWidget(7,1,lbxStudentNum)
.setWidget(8,0,vldSourceGrp)
.setWidget(9,0,radHCopy)
.setWidget(9,1,radECopy)
.setWidget(10,0,vldTypeGrp)
.setWidget(11,0,radTExam)
.setWidget(11,1,vldElementsID)
.setWidget(12,0,radEExam)
.setWidget(12,1,txtElementsID)
.setWidget(13,0,radQExam)
.setWidget(13,1,vldQuia)
.setWidget(14,1,txtQuiaLink)
.setWidget(15,1,txtQuiaPass)
.setWidget(16,0,txtSourceGrp)
.setWidget(16,1,txtTypeGrp)
.setWidget(17,0,btnCreate)
//Add this panel to the application
return(vrtMainPanel);
}
function getTeacherName(e){
var spSheet = SpreadsheetApp.openById('0AnqSFd3iikE3dEtBQndOYVNEbFVWcDlyQmFoaUV3a1E');
var spTeacherList = spSheet.getSheetByName('TeacherList');
var lstTeacherNames = spTeacherList.getRange(1,1,spTeacherList.getLastRow(),2).getValues();
var app = UiApp.getActiveApplication();
var txtTeacherName = app.getElementById('txtTeacherName');
var txtExt = app.getElementById('txtExt');
txtTeacherName.setText(lstTeacherNames[e.parameter.lbxTeacherName][0]);// sets Teacher's Name
txtExt.setText(lstTeacherNames[Number(e.parameter.lbxTeacherName)][1]);// sets Ext
return app;
}
function valSubmit(e) {
var flag = 0;
var app = UiApp.getActiveApplication();
var Teacher = e.parameter.txtTeacherName;
var Ext = e.parameter.txtExt;
var Subject = e.parameter.lbxSubject;
var Period = e.parameter.lbxPeriod;
var Date = e.parameter.boxDate;
var StudentNum = e.parameter.lbxStudentNum;
var Source = e.parameter.txtSourceGrp;
var Type = e.parameter.txtTypeGrp;
var ElementsID = e.parameter.txtElementsID;
var QuiaLink = e.parameter.txtQuiaLink;
var QuiaPass = e.parameter.txtQuiaPass;
if (Teacher == '' || Teacher == '-- Select Teacher --') {
app.getElementById('vldTeacherName').setText('* Select Teacher').setStyleAttribute("color", "#F00").setVisible(true);
flag = 1;
}
if (Ext == '') {
app.getElementById('vldExt').setText('* Select Teacher Again').setStyleAttribute("color", "#F00").setVisible(true);
flag = 1;
}
if (Subject == '' || Subject == '-- Select Subject --') {
app.getElementById('vldSubject').setText('* Select Subject').setStyleAttribute("color", "#F00").setVisible(true);
flag = 1;
}
if (Period == '' || Period == '-- Select Period --') {
app.getElementById('vldPeriod').setText('* Select Period').setStyleAttribute("color", "#F00").setVisible(true);
flag = 1;
}
if (Date == '' || Date == Utilities.formatDate(Date, 'EST', 'yyyy-mm-dd')) {
app.getElementById('vldDate').setText('* Date must be entered as yyyy-mm-dd').setStyleAttribute("color", "#F00").setVisible(true);
flag = 1;
}
if (StudentNum == '' || StudentNum == '-- Select # --') {
app.getElementById('vldStudentNum').setText('* Select Student #').setStyleAttribute("color", "#F00").setVisible(true);
flag = 1;
}
if (Source == '' || Source == false) {
app.getElementById('vldSourceGrp').setText('* Select either Hard Copy or Electronic Copy').setStyleAttribute("color", "#F00").setVisible(true);
flag = 1;
}
if (Type == '' || Type == false) {
app.getElementById('vldTypeGrp').setText('* Select either Teacher-Made Exam, Elements Exam, or Quia Exam').setStyleAttribute("color", "#F00").setVisible(true);
flag = 1;
}
if (ElementsID == '' && Type == 'Elements Exam') {
app.getElementById('vldElementsID').setText('* Enter Elements ID').setStyleAttribute("color", "#F00").setVisible(true);
flag = 1;
}
if (QuiaLink == '' || QuiaPass == '' && Type == 'Quia Exam') {
app.getElementById('vldQuia').setText('* Enter Quia Link and/or Passphrase').setStyleAttribute("color", "#F00").setVisible(true);
flag = 1;
}
if (flag == 0) {
//Create handler which will execute 'createEvents(e)' on clicking the button
var evtHandler = app.createServerClickHandler('createEvents');
var vrtMainPanel = app.getElementById(vrtMainPanel)
evtHandler.addCallbackElement(vrtMainPanel);
}
}
function createEvents(e){
//Get the active application
var app = UiApp.getActiveApplication();
try{
//Get the entries
var ssTeacher = e.parameter.txtTeacherName;
var ssExt = e.parameter.txtExt;
var ssSubject = e.parameter.lbxSubject;
var ssPeriod = e.parameter.lbxPeriod;
var ssStudentNum = e.parameter.lbxStudentNum;
var ssSource = e.parameter.txtSourceGrp;
var ssType = e.parameter.txtTypeGrp;
var ssElementsID = e.parameter.txtElementsID;
var ssQuiaLink = e.parameter.txtQuiaLink;
var ssQuiaPass = e.parameter.txtQuiaPass;
var eventDate = e.parameter.boxDate;
var eventCalSubject = ssPeriod + ": " + ssTeacher + " (" + ssStudentNum + ")";
var eventCalDetails = "Extension: " + ssExt + "\n" +
"Subject: " + ssSubject + "\n\n" +
"Source: " + ssSource + "\n" +
"Type: " + ssType + "\n" +
"Elements ID: " + ssElementsID + "\n" +
"Quia Test Link: " + ssQuiaLink + "\n" +
"Quia Passphrase: " + ssQuiaPass;
//Get the calendar
var cal = CalendarApp.getCalendarById('davie.k12.nc.us_d2mv2eb8aspuant1vb5j6r3sis#group.calendar.google.com');//Change the calendar id
//Create the events
var newID = cal.createAllDayEvent(eventCalSubject, eventDate, {description:eventCalDetails}).getId();
//Log the entries in a spreadsheet
var sheet = SpreadsheetApp.openById('0AnqSFd3iikE3dEtBQndOYVNEbFVWcDlyQmFoaUV3a1E').getActiveSheet();//Change the spreadhseet key to yours
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 13).setValues([[new Date(),eventDate,ssTeacher,ssExt,ssSubject,ssPeriod,ssSource,ssType,ssElementsID,ssQuiaLink,ssQuiaPass,ssStudentNum,newID]]);
return app;
//Show the confirmation message
app.add(app.createLabel('Kurzweil Calendar Event created successfully...'));
//Make the form panel invisible
app.getElementById('vertMainPanel').setVisible(false);
return app;
}
//If an error occurs, show it on the panel
catch(e){
app.add(app.createLabel('Error occured: '+ e));
return app;
}
}
I want to be able to clear the whole array of images with the click of a button and reload the array with updated values. I cannot get this to work by clearing the vertPanel. Can this be done by somehow resetting all the data? Any help would be appreciated.
var maxImgs = 6; // Number of images in grid
var colUrl = 0; // Column containing URL
var colName = 2; // Column containing Name
var colAttr = 1; // Column containing Attributes
function doGet(e) {
var app = UiApp.createApplication().setTitle('Not Here');
var abspanel = app.createAbsolutePanel().setStyleAttribute('padding','25px');
var grid = app.createGrid(8, 8);
var titleLabel = app.createLabel('Not Here');
titleLabel.setStyleAttribute('margin-left','85px');
titleLabel.setStyleAttribute("font-size", "135%");
titleLabel.setStyleAttribute("font-weight", "bold");
var insertlabel = app.createLabel('Which Schedule? (Insert Document Key)');
var inserttxtbox = app.createTextBox().setId('txtbox').setName('ttbox').setMaxLength(44);
var loadbtn = app.createButton('Load Pictures').setId('loadbtn');
var resetbtn = app.createButton('Refresh').setId('rbtn').setVisible(false);
var daylabel = app.createLabel('Select Day');
var mon = "P - Mon"
var tues = "P - Tues"
var wed = "P - Wed"
var thurs = "P - Thurs"
var fri = "P - Fri"
var dayListBox = app.createListBox().setWidth('140px').setId('day').setName('sday')
dayListBox.addItem(mon);
dayListBox.addItem(tues);
dayListBox.addItem(wed);
dayListBox.addItem(thurs);
dayListBox.addItem(fri);
// Borrowed from https://sites.google.com/site/scriptsexamples/learn-by-example/uiapp-examples- code-snippets/progress-indicators
var spinner = app.createImage('https://dl.dropboxusercontent.com/u/211279/loading3T.gif')
.setVisible(false)
.setId('spinner');
// Client handler for loadbtn will start spinner when button clicked
// Server handler will stop spinner when done loading pictures
var loadSpinner = app.createClientHandler()
.forTargets(spinner)
.setVisible(true);
loadbtn.addClickHandler(loadSpinner);
var loadhandler = app.createServerHandler('loadPics');
loadhandler.addCallbackElement(abspanel);
loadbtn.addClickHandler(loadhandler);
grid
.setWidget(1, 0, insertlabel)
.setWidget(1, 1, inserttxtbox)
.setWidget(2, 0, daylabel)
.setWidget(2, 1, dayListBox)
.setWidget(3, 1, loadbtn)
.setWidget(3, 2, resetbtn)
.setWidget(2, 2, spinner)
.setCellSpacing(5);
for (var img = 0, row = 5; img < maxImgs; img++) {
var image = app.createImage().setPixelSize(350, 350).setId('image' + img);
var imageName = app.createLabel('name').setId('name'+img);
var imageAttr = app.createLabel('attr').setId('attr'+img);
var vertPan = app.createVerticalPanel().add(imageName).add(imageAttr).add(image).setStyleAttributes({'padding':'15px','borderStyle':'solid','border-radius':'15px','background':'silver'}).setVisible(false).setId('vertPanel'+img);
grid.setWidget(row + Math.floor(img / 4), 1 + (img % 4), vertPan)
}
abspanel.add(titleLabel);
abspanel.add(grid);
app.add(abspanel);
return app;
}
function loadPics(e) {
var app = UiApp.getActiveApplication();
var ss = SpreadsheetApp.openById(e.parameter.ttbox);
var list = ss.getSheetByName(e.parameter.sday);
var data = list.getRange("A121:C230").getValues().splice(1); // Get whole spreadsheet, without headers
for (var row = 0, img = 0; row < data.length && img < maxImgs; row++) {
var rowData = data[row];
if (rowData[0] != '') {
var image = app.getElementById('image' + img);
var imageName = app.getElementById('name'+img);
var imageAttr = app.getElementById('attr'+img);
var vertPan = app.getElementById('vertPanel'+img).setVisible(true);
image.setUrl(rowData[colUrl])
.setTitle(rowData[colName].toString() === '' ? 'image'+img : rowData[colName]);
imageName.setText(rowData[colName]).setStyleAttribute("font-size", "150%");
imageAttr.setText(rowData[colAttr]);
img++;
}
}
// Done loading, hide spinner
app.getElementById('spinner').setVisible(false);
return app;
}
Better define another grid and add it to abspanel, In the handler function, call the image grid by ID and then use method clear(); to clear the grid. And then reconstruct it for new images.
I hope you get it what I am trying to say.
in doGet() function use
var imgGrid = app.createGrid(1,1).setId('imgGrid');
abspanel.add(imgGrid);
in your handler function use
var imgGrid = app.getElementById('imgGrid').clear();
imgGrid.resize(row, column);
//Now manipulate this grid to show new images