How to select some default nodes in Google Org Chart - orgchart

I am new to Google Org Chart.
Having a tough time selecting some default nodes in my chart by code.
Like in this case I want "jordan" to be selected automatically.
Note: Node selection is dynamic
Thanks in advance.

At last done by myself.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Group');
data.addColumn('string', 'Parent');
data.addColumn('string', 'ToolTip');
var response = [
['Mark', '', 'Mark'],
['John', 'Mark', 'John'],
['Mary', 'Mark', 'Mary'],
['Jordan', 'Mary', 'Jordan'],
['Eli', 'Mary', 'Eli'],
['Ivan', 'Mary', 'Ivan'],
['Sarah', 'John', 'Sarah'],
['Mike', 'John', 'Mike']
];
data.addRows(response);
var chart = new google.visualization.OrgChart(document.getElementById('grouporgdiv'));
chart.draw(data, {allowHtml:true});
var selectedArray = new Array();
var counter = 0;
var commaSeperatedDefaultValues = "Jordan";
var defaultValuesArray = commaSeperatedDefaultValues.split(",");
for(i=0;i<response.length;i++) {
chart.setSelection([{row: i}]);
var temp = chart.getSelection()[0];
var a = defaultValuesArray.indexOf(data.getValue(temp.row, 2));
if(a != -1)
selectedArray[counter++] = temp;
}
chart.setSelection(selectedArray);

Related

Is there any way to be more efficient when taking values from a spreasheet if they contain certain value?

I´m new at this and I´m trying to copy and paste certain rows (every row that contains the value "Buenos días" in the column C) from spreadsheet 1 (CSV) into spreadsheet 2 (buenosDias). It takes too much time to the script to totally run and I cannot find a way to be more efficient.Is there any way to be more efficient? This is the code I have come up with:
function buenosDias() {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1ur1Y7KoPONxPiFBMdGR4UfJW4GfyLy4MDxTEk30mg8w/edit#gid=0"); var sheets = ss.getSheets();
var buenosDias = ss.getSheetByName("Buenos días"); var range = buenosDias.getDataRange().getValues(); var CSV = ss.getSheetByName("CSV");
var lastRowA = CSV.getLastRow(); var CSVA = CSV.getRange(1, 1, lastRowA).getValues();
var lastRowB = CSV.getLastRow(); var CSVB = CSV.getRange(1, 2, lastRowB).getValues();
var lastRowC = CSV.getLastRow(); var CSVC = CSV.getRange(1, 3, lastRowC).getValues();
var lastRowD = CSV.getLastRow(); var CSVD = CSV.getRange(1, 4, lastRowD).getValues();
var lastRowE = CSV.getLastRow(); var CSVE = CSV.getRange(1, 5, lastRowE).getValues();
var lastRowF = CSV.getLastRow(); var CSVF = CSV.getRange(1, 6, lastRowF).getValues();
var lastRowG = CSV.getLastRow(); var CSVG = CSV.getRange(1, 7, lastRowG).getValues();
var lastRowH = CSV.getLastRow(); var CSVH = CSV.getRange(1, 8, lastRowH).getValues();
var lastRowI = CSV.getLastRow(); var CSVI = CSV.getRange(1, 9, lastRowI).getValues();
var lastRowJ = CSV.getLastRow(); var CSVJ = CSV.getRange(1, 10, lastRowJ).getValues();
var lastRowK = CSV.getLastRow(); var CSVK = CSV.getRange(1, 11, lastRowK).getValues();
var lastRowL = CSV.getLastRow(); var CSVL = CSV.getRange(1, 12, lastRowL).getValues();
var lastRowM = CSV.getLastRow(); var CSVM = CSV.getRange(1, 13, lastRowM).getValues();
for (var i = 1;i < CSVA.length; i++) {
var lastRow0 = buenosDias.getLastRow();
var RowToComplete = lastRow0;
if (CSVC[i] == "Buenos días") {
buenosDias.getRange(RowToComplete+1, 1).setValue(CSVA[i]).setHorizontalAlignment("center");
buenosDias.getRange(RowToComplete+1, 2).setValue(CSVF[i]).setNumberFormat("0").setHorizontalAlignment("center");
buenosDias.getRange(RowToComplete+1, 3).setValue(CSVH[i]).setNumberFormat("0").setHorizontalAlignment("center");
buenosDias.getRange(RowToComplete+1, 4).setValue(CSVH[i]/CSVF[i]).setNumberFormat("00.00%").setHorizontalAlignment("center");
buenosDias.getRange(RowToComplete+1, 5).setValue(CSVJ[i]).setNumberFormat("0").setHorizontalAlignment("center");
buenosDias.getRange(RowToComplete+1, 6).setValue(CSVJ[i]/CSVF[i]).setNumberFormat("00.00%").setHorizontalAlignment("center");
}
} }
Thanks!
Try using the method appendRow so you don't need to get the last Row of the Sheet, as it will add the values at the end of the Sheet.
Also, I made a single for loop to iterate over the Column C, looking for the string "Buenos dias". If it coincides, then appends that row to the CSV Sheet. Don't forget to change the numberofColumns to the actual number of Columns you want to copy from each row from Column A.
From the setHorizontalAlignment loop you made at the end I guess you want to center all the data of the CSV Sheet. It's easier to set it for all the Data Range instead of looping over all the rows.
function buenosDias() {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1ur1Y7KoPONxPiFBMdGR4UfJW4GfyLy4MDxTEk30mg8w/edit#gid=0");
var buenosDias = ss.getSheetByName("Buenos días");
var CSV = ss.getSheetByName("CSV");
var range = CSV.getRange("C1:C").getValues(); //Range goes from C1 to the last C with values
for (var i = 0; i < range.length; i++){
if (range[i][0] == "Buenos días"){
CSV.appendRow(buenosDias.getRange((i+1), 1, numberofColumns).getValues());
}
}
CSV.getDataRange().setHorizontalAlignment('center');
}

Apps Script that reads email of user and returns information from spreadsheet

I'm trying to make a script to put on my google site for my students so that they can look up their login details for mymaths from home. I have a spreadsheet with all their emails which match up to their login details but when they access the page I want the to be able to just see their row. I am using Session.getActiveUser().getEmail() for this and all of my code is below but it is not working!
Any help would be greatly appreciated.
var userID = Session.getActiveUser().getEmail();
var userLogin;
var userPass;
var userName;
var text;
//Function to lookup login and password from email and add to variables
function lookup() {
var spreadsheetKey = '1UftMLEgJPof3533X1Dp2IRqLIJa-70y8m-xnbyfj8ZA';
var sheet = SpreadsheetApp.openById(spreadsheetKey);
var end = SpreadsheetApp.getActiveSheet().getLastRow();
var range = sheet.getRange(1, 0, end, 4);
var values = range.getValues();
for (i = 0; i < values.length; ++i) {
if (values[i][0] == userID) {
text = 'Here are your login details for MyMaths. Now get on with your homework!'
userName = string(values[i][1]);
userLogin = string(values[i][2]);
userPass = string(values[i][3]);
}
else {
text = 'Sorry, but there is an error. You will need to check in your book or ask your teacher for your MyMaths login details.'
}
}
}
//Function to create Userinterface on site page
function doGet() {
var app = UiApp.createApplication();
var panel = app.createAbsolutePanel();
var label = app.createLabel(text);
var table = app.createGrid(2,3);
table.setText(0, 0, 'Name');
table.setText(0, 1, 'Login');
table.setText(0, 2, 'Password');
table.setText(1, 0, userName);
table.setText(1, 1, userLogin);
table.setText(1, 2, userPass);
panel.add(label);
panel.add(table);
app.add(panel);
return app;
}
The way you implemented this is not going to work. You defined a number of variables as "global" so that each function could use it but although this is true, the functions won't be able to modify them..., in other words : they cannot assign a value to these variables.
I would suggest to build this in a completely different way : a main doGet that would call a lookup function, this latter returning the appropriate values (as an array or an object).
The code goes like this, I didn't test it because I didn't have data to do so but it should work as expected.
btw, think about using some styles to make it look nicer :-) see this post from Anees Hameed showing a smart way to do it.
//Function to create Userinterface on site page
function doGet() {
var userID = Session.getEffectiveUser().getEmail();
var result = lookup(userID);
var app = UiApp.createApplication();
var panel = app.createAbsolutePanel();
var label = app.createLabel(result.text);
var table = app.createGrid(2,3);
table.setText(0, 0, 'Name');
table.setText(0, 1, 'Login');
table.setText(0, 2, 'Password');
table.setText(1, 0, result.userName);
table.setText(1, 1, result.userLogin);
table.setText(1, 2, result.userPass);
panel.add(label);
panel.add(table);
app.add(panel);
return app;
}
function lookup(userID) {
var result = {};
var spreadsheetKey = '1UftMLEgJPof3533X1Dp2IRqLIJa-70y8m-xnbyfj8ZA';
var sheet = SpreadsheetApp.openById(spreadsheetKey);
var end = SpreadsheetApp.getActiveSheet().getLastRow();
var range = sheet.getRange(1, 0, end, 4);
var values = range.getValues();
for (i = 0; i < values.length; ++i) {
if (values[i][0] == userID) {
result['text'] = 'Here are your login details for MyMaths. Now get on with your homework!'
result['userName'] = string(values[i][1]);
result['userLogin'] = string(values[i][2]);
result['userPass'] = string(values[i][3]);
}
else {
result['text'] = 'Sorry, but there is an error. You will need to check in your book or ask your teacher for your MyMaths login details.'
result['userName'] = '-';
result['userLogin'] = '-';
result['userPass'] = '-';
}
}
return result;
}

select a row from a flextable in google script

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
}

Load a table from Google Storage to BigQuery using Google App Scripts

I believe this is setting up the job configuration correctly, but I am having trouble figuring out how to get the the job to run. Has anyone had success using Apps Script to load a table to BigQuery?
function testLoad(){
var fields = [
{'name': 'FirstName', 'type':'STRING'},
{'name': 'LastName', 'type':'STRING'}
];
var schema = BigQuery.newTableSchema()
schema.setFields(fields)
var tableReference = BigQuery.newTableReference()
tableReference.setProjectId(PROJECT_ID);
tableReference.setDatasetId('Test_Dataset');
tableReference.setTableId('TestTable1');
var load = BigQuery.newJobConfigurationLoad();
load.setDestinationTable(tableReference);
load.setSkipLeadingRows(1);
load.setSourceUris([SOURCE]);
load.setSourceFormat('CSV');
load.setSchema(schema)
var configuration = BigQuery.newJobConfiguration();
configuration.setLoad(load);
var newJob = BigQuery.newJob();
newJob.setConfiguration(configuration);
var insert = BigQuery.Jobs.insert(newJob)
Logger.log(insert.getId());
}
Finally got back to this issue. The missing piece was needing to include the project id to the insert job as well as the table reference.
I also included a bit to poll for the job status and return when the job is done.
function testLoad(){
Logger.log(exampleLoad_());
}
function exampleLoad_(){
try{
var fields = [
{'name': 'FirstName', 'type':'STRING'},
{'name': 'LastName', 'type':'STRING'}
];
var schema = BigQuery.newTableSchema();
schema.setFields(fields);
var tableReference = BigQuery.newTableReference();
tableReference.setProjectId(PROJECT_ID);
tableReference.setDatasetId('Test_Dataset');
tableReference.setTableId('TestTable1');
var load = BigQuery.newJobConfigurationLoad();
load.setDestinationTable(tableReference);
load.setSkipLeadingRows('1');
load.setSourceUris([SOURCE]);
load.setSourceFormat('CSV');
load.setSchema(schema);
load.setAllowJaggedRows(false);
var configuration = BigQuery.newJobConfiguration();
configuration.setLoad(load);
var newJob = BigQuery.newJob();
newJob.setConfiguration(configuration);
var job = BigQuery.Jobs.insert(newJob, {projectId:PROJECT_ID});
var jobId = job.getJobReference().getJobId();
var status = job.getStatus();
while (status.getState() != 'DONE'){
if(status.getState() == 'PENDING'){
Utilities.sleep(100);
}
if (status.getErrorResult() == true){
return status.getErrors();
}
status = BigQuery.Jobs.get(PROJECT_ID, jobId).getStatus();
}
}catch(err){
return err;
}
return status.getState();
}

How to load geodata from google sheet (columns) instead

My current data is hardcoded:
var geoData = new google.visualization.DataTable();
geoData.addColumn('string', 'City');
geoData.addColumn('string', 'Name');
geoData.addColumn('boolean', 'Yes/no');
var geoView = new google.visualization.DataView(geoData);
geoView.setColumns([0, 1]);
var query = new google.visualization.Query('http://spreadsheets.google.com/...')