Error when adding contacts from Google Spreadsheets to Google Contacts - google-sheets

I tried making a script on Google Spreadsheets to add new contacts based on a spreadsheet and add them to the "adicionar marcador" group, it ended up like this::
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getSheetByName('Planilha de cadastro')
var headerRows = 1;
var MaxRow = sheet.getLastRow();
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
data.splice(0, headerRows);
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Contatos')
.addItem('Adicionar Contatos', 'addContact')
.addToUi();
}
function addContact() {
for (var i = 0; i < data.length; i++) {
var row = data[i];
var firstName = row[1];
var lastName = row[2];
var email = row[3];
var phone = row[4];
var job = row[5];
var address2 = row[6];
var Age = row [7];
var obs = row [8];
var group = row[10];
contact = ContactsApp.createContact(firstName, lastName, email);
contact.addPhone(ContactsApp.Field.MOBILE_PHONE, phone);
contact.setNotes(obs)
contact.addCompany('', job)
contact.addCustomField("Idade", Age);
contact.addCustomField("Endereço", address2)
var group = ContactsApp.getContactGroup("System Group: My Contacts");
group.addContact(contact);
var group = ContactsApp.getContactGroup('Adicionar marcador')
group.addContact(contact);
}
}
But when I try adding contacts by using the function addContact it returns me an error message. Any idea on what is wrong with the code?

see comments above about declaring variables multiple times and arrays starting with zero. This added the data (and not the headings) and placed the contacts into the group from the spreadsheet. I created the group first.
function createContactGroup() { // this works
let group = ContactsApp.createContactGroup('apps-script');
console.log('group.getName(): ', group.getName() );
}
function addContact() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const sheet = ss.getSheetByName('contact')
const headerRows = 1;
let MaxRow = sheet.getLastRow();
let dataRange = sheet.getDataRange();
let data = dataRange.getValues();
console.log('data: ', data);
let row, firstName, lastName, email, phone, job, address2, Age, obs, group;
for (var i = 1; i < data.length; i++) { // top row is header
row = data[i];
firstName = row[0];
lastName = row[1];
email = row[2];
console.log('fname: ', firstName, ' lname: ', lastName, ' email: ', email );
phone = row[3];
job = row[4];
address2 = row[5];
Age = row[6];
obs = row[7];
group = row[8];
console.log('group: ', group );
try {
contact = ContactsApp.createContact(firstName, lastName, email);
} catch (err) {
console.log('createContact err: ', err );
}
contact.addPhone(ContactsApp.Field.MOBILE_PHONE, phone);
contact.setNotes(obs)
contact.addCompany('', job)
contact.addCustomField("Idade", Age);
contact.addCustomField("Endereço", address2)
addToGroup = ContactsApp.getContactGroup(group);
addToGroup.addContact(contact);
// var group = ContactsApp.getContactGroup('Adicionar marcador')
// group.addContact(contact);
}
}

Related

Exporting from Google Sheets to Google Contacts

I'm trying to add contacts using a spreadsheet and a script.
So far I was able to copy the script from this user: How to sync google sheets database with google contacts
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getSheetByName('Respostas ao formulário 1')
var headerRows = 1;
var MaxRow = sheet.getLastRow();
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
data.splice(0, headerRows);
function addContact() {
for (var i = 0; i < data.length; i++) {
var row = data[i];
var firstName = row[1];
var lastName = row[2];
var email = row[3];
var phone = row[4];
var group = row[5];
var job = row[6];
var address2 = row[7];
contact = ContactsApp.createContact(firstName, lastName, email);
contact.addPhone(ContactsApp.Field.MOBILE_PHONE, phone);
contact.setNotes(address2)
contact.addCompany('', job)
var group = ContactsApp.getContactGroup("System Group: My Contacts");
group.addContact(contact);
}
}
It works great, but I can't find out how to add age or to automatically add a label to the contact. Any help would be awesome
You need to create a custom field. Within your code if you add this line I think you'll get what you need:
contact.addCustomField("Age", '26');
Try to add " var age = row[8];" under "var address2 = row[7];
"or whereever you want. If you place it other you have to ajust the numbers.
I hope i can help!

How do i get the URL of a editable form response in spreadsheets

Im trying to get the url of a editable google form response to show up in google sheets,but it does not seem to be working.
I have seen Awesome Table and Ruben's example. Based of these 2 links and some others, they seem to be working for single form response sheets,but not multiple.
I tried this code 1st:
var formURL = 'https://docs.google.com/forms/d/__Your ID__/viewform';
var sheetName = '__Response sheet__';
var columnIndex = __column where it appears__;
function getEditResponseUrls() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var data = sheet.getDataRange().getValues();
var form = FormApp.openByUrl(formURL);
for(var i = 2; i < data.length; i++) {
if (data[i][0] != '' && data[i][columnIndex-1] == '') {
var timestamp = data[i][0];
var formSubmitted = form.getResponses(timestamp);
if (formSubmitted.length < 1) continue;
var editResponseUrl = formSubmitted[0].getEditResponseUrl();
sheet.getRange(i+1, columnIndex).setValue(editResponseUrl);
}
}
}
2nd is:
// Form URL
var formID = '__Your ID__';
// Sheet name used as destination of the form responses
var sheetName = '__Response sheet__'';
/*
* Name of the column to be used to hold the response edit URLs
* It should match exactly the header of the related column,
* otherwise it will do nothing.
*/
var columnName = '__name of column where it appears__' ;
// Responses starting row
var startRow = 2;
function getEditResponseUrls(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var columnIndex = headers[0].indexOf(columnName);
var data = sheet.getDataRange().getValues();
var form = FormApp.openById(formId);
for(var i = startRow-1; i < data.length; i++) {
if(data[i][0] && !data[i][columnIndex]) {
var timestamp = data[i][0];
var formSubmitted = form.getResponses(timestamp);
if(formSubmitted.length < 1) continue;
var editResponseUrl = formSubmitted[0].getEditResponseUrl();
sheet.getRange(i+1, columnIndex+1).setValue(editResponseUrl);
}
}
}
Nothing is showing up, and when i check the logs for triggers, it is all working fine, no failures.I have tried putting the global variables within the function, but no changes.
The following points are taken from the latest version from #Rubén latest version on github. This code is a thing of beauty and a joy to behold. Combined with Rubén's detailed instructions, this answer can be setup and running in less than 5 minutes.
change
var formID = '__Your ID__';
to
var formURL = 'https://docs.google.com/forms/d/ -insert id - /edit';
you get the URL from the Forms Editor page.
change
var columnName = 'Form URL';
to
var sheetName = 'URL'; // Column U
replace getEditResponseUrls entirely
function getEditResponseUrls(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var columnIndex = headers[0].indexOf(columnName);
var data = sheet.getDataRange().getValues();
var form = FormApp.openByUrl(formURL);
for(var i = startRow-1; i < data.length; i++) {
if(data[i][0] != '' && data[i][columnIndex] == '') {
var timestamp = data[i][0];
var formSubmitted = form.getResponses(timestamp);
if(formSubmitted.length < 1) continue;
var editResponseUrl = formSubmitted[0].getEditResponseUrl();
sheet.getRange(i+1, columnIndex+1).setValue(editResponseUrl);
}
}
}
Remember to set the installable trigger.
In the Google Sheet that you have linked from the question above, you have declared two functions with the same name and this could be a reason why the first one may never be executing. I tested this code and it seemed to work.
You may want to replace everything in the file with just this code.
var id = '1SdSPhOwi1dWQzRsNpA9zFL-ODorgohST3TMRJLqz16I';
var sheetName = 'Order Information';
var columnIndex = 21;
function getEditResponseUrls() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var data = sheet.getDataRange().getValues();
var form = FormApp.openById(id);
for(var i = 2; i < data.length; i++) {
if (data[i][0] != '' && data[i][columnIndex-1] == '') {
var timestamp = data[i][0];
var formSubmitted = form.getResponses(timestamp);
if (formSubmitted.length < 1) continue;
var editResponseUrl = formSubmitted[0].getEditResponseUrl();
sheet.getRange(i+1, columnIndex).setValue(editResponseUrl);
}
}
}

Google Sheet Script to pull data from YouTube API, cannot fetch channel ID

I'm trying to pull data from my YouTube channel, numbers of views, etc, into a Google sheet.
I authorized YouTube APIs, but it cannot retrieve my youtube channel ID.
Here's the error message:
Invalid number of arguments provided. Expected 0-1 only (line 31, file "Code")
line 31 is : var analyticsResponse = YouTubeAnalytics.Reports.query(
I'm using a script found online:
function testingYTpage() {
var url = "https://www.youtube.com/watch?v=ua4QGWmDfB8&list=PLOU2XLYxmsILvfJcIASBDbgfxloFz_XsU&index=7";
var rawData = UrlFetchApp.fetch(url).getContentText();
Logger.log(rawData);
}
//
//
//
function spreadsheetAnalytics() {
// Get the channel ID
var myChannels = YouTube.Channels.list('id', {mine: true});
var channel = myChannels.items[0];
var channelId = channel.id;
// Set the dates for our report
var today = new Date();
var monthAgo12 = new Date();
monthAgo12.setMonth(today.getMonth() - 11);
var todayFormatted = Utilities.formatDate(today, 'UTC', 'yyyy-MM-dd')
var oneMonthAgoFormatted = Utilities.formatDate(monthAgo12, 'UTC', 'yyyy-MM-dd');
// The YouTubeAnalytics.Reports.query() function has four required parameters and one optional
// parameter. The first parameter identifies the channel or content owner for which you are
// retrieving data. The second and third parameters specify the start and end dates for the
// report, respectively. The fourth parameter identifies the metrics that you are retrieving.
// The fifth parameter is an object that contains any additional optional parameters
// (dimensions, filters, sort, etc.) that you want to set.
var analyticsResponse = YouTubeAnalytics.Reports.query(
'channel==' + channelId,
oneMonthAgoFormatted,
todayFormatted,
// dimensions=day metrics=views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage,subscribersGained
'views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage,likes,dislikes,shares',
{
dimensions: 'day',
sort: '-day'
});
// Create a new Spreadsheet with rows and columns corresponding to our dates
var ssName = 'YouTube channel report ' + oneMonthAgoFormatted + ' - ' + todayFormatted;
var numRows = analyticsResponse.rows.length;
var numCols = analyticsResponse.columnHeaders.length;
// Add an extra row for column headers
var ssNew = SpreadsheetApp.create(ssName, numRows + 1, numCols);
// Get the first sheet
var sheet = ssNew.getSheets()[0];
// Get the range for the title columns
// Remember, spreadsheets are 1-indexed, whereas arrays are 0-indexed
var headersRange = sheet.getRange(1, 1, 1, numCols);
var headers = [];
// These column headers will correspond with the metrics requested
// in the initial call: views, likes, dislikes, shares
for(var i in analyticsResponse.columnHeaders) {
var columnHeader = analyticsResponse.columnHeaders[i];
var columnName = columnHeader.name;
headers[i] = columnName;
}
// This takes a 2 dimensional array
headersRange.setValues([headers]);
// Bold and freeze the column names
headersRange.setFontWeight('bold');
sheet.setFrozenRows(1);
// Get the data range and set the values
var dataRange = sheet.getRange(2, 1, numRows, numCols);
dataRange.setValues(analyticsResponse.rows);
// Bold and freeze the dates
var dateHeaders = sheet.getRange(1, 1, numRows, 1);
dateHeaders.setFontWeight('bold');
sheet.setFrozenColumns(1);
// Include the headers in our range. The headers are used
// to label the axes
var range = sheet.getRange(1, 1, numRows, numCols);
var chart = sheet.newChart()
.asColumnChart()
.setStacked()
.addRange(range)
.setPosition(4, 2, 10, 10)
.build();
sheet.insertChart(chart);
}
//
// A Helper function to extract the ID of our video
// It works both on version of links:
// 1. https://www.youtube.com/watch?v=BuHEhmp47VE
// 2. http://youtu.be/BuHEhmp47VE
//
function extractVideoID() {
var curSheet = SpreadsheetApp.getActiveSheet();
var ytLinks = curSheet.getRange("D:D");
var totalRows = ytLinks.getNumRows();
var ytVal = ytLinks.getValues();
// let's run on the rows
for (var i = 1; i <= totalRows - 1; i++) {
var curLink = ytVal[i][0];
if (curLink == "") {
break;
}
var videoID = "";
var inx1 = curLink.indexOf('watch?v=') + 8;
if (inx1 == 7) {
// check if it's the short format: http://youtu.be/75EuHl6CSTo
if (curLink != "" && curLink.indexOf("youtu.be") > 0) {
videoID = curLink.substr(16, curLink.length);
}
}
else {
// we have the link in this format: https://www.youtube.com/watch?v=YIgSucMNFAo
var inx2 = curLink.indexOf("&", inx1);
if (inx2 > inx1) {
videoID = curLink.substr(inx1, inx2-inx1);
} else {
videoID = curLink.substr(inx1, curLink.length);
}
}
curSheet.getRange("E" + (i+1)).setValue(videoID);
}
var htmlMsg = HtmlService
.createHtmlOutput('<h3>Done - Please check the IDs on Column D:D</h3>').setTitle('YT Dashboard Example').setWidth(450).setHeight(300);
SpreadsheetApp.getActiveSpreadsheet().show(htmlMsg);
}
//
// Run on all the rows and according to the video ID fetch the feed
//
function fetchAllData() {
var start = new Date().getTime();
var curSheet = SpreadsheetApp.getActiveSheet();
var ytIds = curSheet.getRange("E:E");
var totalRows = ytIds.getNumRows();
var ytVal = ytIds.getValues();
var errMsg = "<h4>Errors:</h4> <ul>";
// let's run on the rows after the header row
for (var i = 1; i <= totalRows - 1; i++) {
// e.g. for a call: https://gdata.youtube.com/feeds/api/videos/YIgSucMNFAo?v=2&prettyprint=true
if (ytVal[i] == "") {
Logger.log("We stopped at row: " + (i+1));
break;
}
var link = "https://gdata.youtube.com/feeds/api/videos/" + ytVal[i] + "?v=2&prettyprint=true";
try {
fetchYTdata(link, i+1);
}
catch (err) {
errMsg += "<li>Line: " + i + " we could not fetch data for ID: " + ytVal[i] + "</li>";
Logger.log("*** ERR: We have issue with " + ytVal[i] + " On line: " + i);
}
}
if (errMsg.length < 24) {
// we do not have any errors at this run
errMsg += "<li> All good for now </li>";
}
var end = new Date().getTime();
var execTime = (end - start) / 1000;
var htmlApp = HtmlService
.createHtmlOutput('<h2>Done updating!</h2><p>It took us: '+ execTime + 'sec. to update: ' +
(i+1) + ' videos</p>' + errMsg).setTitle('YT Stats').setWidth(450).setHeight(450);
SpreadsheetApp.getActiveSpreadsheet().show(htmlApp);
}
//
// Read YT stats data on our videos and fill the sheet with the data
//
function fetchYTdata(url, curRow) {
//var url = 'https://gdata.youtube.com/feeds/api/videos/Eb7rzMxHyOk?v=2&prettyprint=true';
var rawData = UrlFetchApp.fetch(url).getContentText();
//Logger.log(rawData);
// published <published>2014-05-09T06:22:52.000Z</published>
var inx1 = rawData.indexOf('published>') + 10;
var inx2 = rawData.indexOf("T", inx1);
var publishedDate = rawData.substr(inx1, inx2-inx1);
// viewCount='16592'
var inx1 = rawData.indexOf('viewCount') + 11;
var inx2 = rawData.indexOf("'/>", inx1);
var totalViews = rawData.substr(inx1, inx2-inx1);
// <yt:duration seconds='100'/>
var inx1 = rawData.indexOf('duration seconds') + 18;
var inx2 = rawData.indexOf("'/>", inx1);
var durationSec = rawData.substr(inx1, inx2-inx1);
Logger.log(curRow + ") TotalViews: " + totalViews + " durationSec: " + durationSec);
// update the sheet
var ss = SpreadsheetApp.getActiveSheet();
ss.getRange("C" + curRow).setValue(publishedDate);
ss.getRange("G" + curRow).setValue(totalViews);
ss.getRange("H" + curRow).setValue(durationSec);
}
//
// Our custom menu
//
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{ name : "Update Stats", functionName : "fetchAllData"},
{ name : "Extract Video IDs", functionName : "extractVideoID"}
];
spreadsheet.addMenu("YT Dashboard", entries);
};
non-scripted non-API solution (for meanwhile):
CHANNEL ID:
=ARRAYFORMULA(REGEXREPLACE(QUERY(SUBSTITUTE(ARRAY_CONSTRAIN(
IMPORTDATA(https://www.youtube.com/watch?v=rckrnYw5sOA), 3000, 1), """", ""),
"where Col1 contains '<meta itemprop=channelId content='"),
"<meta itemprop=channelId content=|>", ""))
VIEWS:
=VALUE(REGEXREPLACE(TEXT(IMPORTXML("https://www.youtube.com/watch?v=MkgR0SxmMKo",
"//*[contains(#class, 'watch-view-count')]"),0)," view(s)?",""))
MORE: https://stackoverflow.com/a/55064665/5632629
I also faced the same issue. Used the below syntax for the Reports.query method and got it worked.
YouTubeAnalytics.Reports.query({
ids: 'channel==' + channelId,
startDate: formatDateString(lastMonth),
endDate: formatDateString(today),
metrics: metrics.join(','),
dimensions: 'day',
sort: 'day'
});

Getting error: "Missing ) after argument list. (line 11, file "Code")

I'm new to coding. I am attempting to import e-mail addresses from a Google Sheet to my gmail account. Any help on why this code is not working would be greatly appreciated! Here is the code I have entered:
function myFunction() {
var alreadyAdded = "Already added";
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 396; // Number of rows to process
// Fetch the range of cells A2:F397
var dataRange = sheet.getRange(startRow, 1, numRows, 400
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for
var
for (var i = 0; i < data.length; ++i)
};
var row = data[i];
var lastName = row[0]
var firstName = row[1]
var emailAddress = row[2]
var address = row[3]
var notes = row[4]
if (addedAlready != alreadyAdded) {
// Create contact in Google Contacts
var contact = ContactsApp.createContact(firstName, lastName, emailAddress);
// Add values to new contact
contact.addAddress(address, "");
contact.setNotes(notes);
sheet.getRange(startRow + i, 7).setValue(alreadyAdded);
};
};
}
try it var dataRange = sheet.getRange(startRow, 1, numRows, 400);

Listbox Selection to Textbox

I have a ListBox that is populated from a spreadsheet filled with teacher's names and phone extensions. I want to be able to select a teacher's name and have it populate the textbox with the teacher's phone extension automatically. I have found several ways to do it via C++ but none using Google Apps Script...
//Create a panel which holds all the form elelemnts
var vrtMainPanel = app.createVerticalPanel().setId('vrtMainPanel');
//Create Spreadsheet Source
var spSheet = SpreadsheetApp.openById('0Aur3owCpuUY-dFF0dVZXb3I1Yjlpbzg3SXFIaklEcUE');
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 hdlExt = app.createServerHandler('getExt').addCallbackElement(vrtMainPanel);
var hdlTeacherName = app.createServerHandler('getTeacherName').addCallbackElement(vrtMainPanel);
var lbxTeacherName = app.createListBox().setId('lbxTeacherName').setName('lbxTeacherName').addChangeHandler(hdlExt).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 lblExt = app.createLabel('Ext:');
var txtExt = app.createTextBox().setName('txtExt').setId('txtExt');
//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 lbxSubject = app.createListBox().setId('lbxSubject').setName('lbxSubject');
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 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 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 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);
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);
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 handler which will execute 'createEvents(e)' on clicking the button
var evtHandler = app.createServerClickHandler('createEvents');
evtHandler.addCallbackElement(vrtMainPanel);
//Add this handler to the button
btnCreate.addClickHandler(evtHandler);
//Add all the elemnts to the panel
var formGrid = app.createGrid(12,3).setCellPadding(3);
vrtMainPanel.add(formGrid);
formGrid
.setWidget(0,0,lbxTeacherName)
.setWidget(0,1,txtExt)
.setWidget(0,2,txtTeacherName)
.setWidget(1,0,lbxPeriod)
.setWidget(1,1,lbxSubject)
.setWidget(2,0,lblDate)
.setWidget(2,1,boxDate)
.setWidget(3,0,lblStudentNum)
.setWidget(3,1,lbxStudentNum)
.setWidget(4,0,radHCopy)
.setWidget(4,1,radECopy)
.setWidget(5,0,radTExam)
.setWidget(6,0,radEExam)
.setWidget(6,1,txtElementsID)
.setWidget(7,0,radQExam)
.setWidget(7,1,txtQuiaLink)
.setWidget(8,1,txtQuiaPass)
.setWidget(9,0,txtSourceGrp)
.setWidget(9,1,txtTypeGrp)
.setWidget(10,0,btnCreate)
//Add this panel to the application
app.add(vrtMainPanel);
//Return the application
return app;
}
function getExt(e){
var spSheet = SpreadsheetApp.openById('0Aur3owCpuUY-dFF0dVZXb3I1Yjlpbzg3SXFIaklEcUE');
var spTeacherList = spSheet.getSheetByName('TeacherList');
var lstTeacherNames = spTeacherList.getRange(1,2,spTeacherList.getLastRow(),1).getValues();
var app = UiApp.getActiveApplication();
var txtExt = app.getElementById('txtExt');
txtExt.setText(lstTeacherNames[Number(e.parameter.lbxTeacherName)][0]);// we get the value in the 2D array returned by getValues()
return app;
}
function getTeacherName(e){
var spSheet = SpreadsheetApp.openById('0Aur3owCpuUY-dFF0dVZXb3I1Yjlpbzg3SXFIaklEcUE');
var spTeacherList = spSheet.getSheetByName('TeacherList');
var lstTeacherNames = spTeacherList.getRange(1,1,spTeacherList.getLastRow(),1).getValues();
var app = UiApp.getActiveApplication();
var txtTeacherName = app.getElementById('txtTeacherName');
txtTeacherName.setText(lstTeacherNames[e.parameter.lbxTeacherName][0]);// we get the value in the 2D array returned by getValues()
return app;
}
// CREATE EVENT FUNCTION
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('0Aur3owCpuUY-dGJIOGZ1LXhqT2FNMGVXSGNJazFnUmc').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;
}
}
As mentioned in my first comment you have to create a server Handler to get that but your script would need a few minor modifications :
The listBox must be modified to return a numeric index instead of a name, this will simplify the process of getting the right data on the spreadsheet (when addItem(arg1,arg2) has 2 arguments the first one is shown while the second is returned to the handler function >> you'll have to modify your other handler functions in consequence, use the same principle I used in the getPhone(e) function)
the Labels that you created where not visible so I changed the grid values
The way you get data in this new version right from the spreadsheet is really a good idea, I regret I didn't think about it myself ;-)
keep in mind that values returned by e.parameter.varName are strings, that's why I used Number(e.parameter.lbxTeacherName) to get the value in the spreadsheet data.
I assumed that the phone extensions where in column B on the teacher data sheet... if not modify accordingly in the getPhone handler function.
(edit : I changed the "tomorrow" definition to skip string manipulation but it's a detail)
Here is the full modified code :
function doGet() {
var app = UiApp.createApplication().setTitle('DHS: Kurzweil Calendar');
//Create a panel which holds all the form elelemnts
var vrtMainPanel = app.createVerticalPanel().setId('vrtMainPanel');
//Create Spreadsheet Source
var spSheet = SpreadsheetApp.openById('0Aur3owCpuUY-dFF0dVZXb3I1Yjlpbzg3SXFIaklEcUE');
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 lblTeacherName = app.createLabel('Teacher Name:');
var teacherNameHandler = app.createServerHandler('getPhone').addCallbackElement(vrtMainPanel);
var lbxTeacherName = app.createListBox().setId('lbxTeacherName').setName('lbxTeacherName').addChangeHandler(teacherNameHandler);
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 lblExt = app.createLabel('Ext:');
var txtExt = app.createTextBox().setName('txtExt').setId('txtExt');
//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:');
var boxDate = app.createDateBox().setId('boxDate').setName('boxDate').setFormat(UiApp.DateTimeFormat.DATE_SHORT).setValue(tomorrow);
var lbxSubject = app.createListBox().setId('lbxSubject').setName('lbxSubject');
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 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 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 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);
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);
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 handler which will execute 'createEvents(e)' on clicking the button
var evtHandler = app.createServerClickHandler('createEvents');
evtHandler.addCallbackElement(vrtMainPanel);
//Add this handler to the button
btnCreate.addClickHandler(evtHandler);
//Add all the elemnts to the panel
var formGrid = app.createGrid(12,2).setCellPadding(3);
vrtMainPanel.add(formGrid);
formGrid
.setWidget(0,0,lblTeacherName)
.setWidget(1,0,lbxTeacherName)
.setWidget(0,1,lblExt)
.setWidget(1,1,txtExt)
.setWidget(2,0,lbxPeriod)
.setWidget(2,1,lbxSubject)
.setWidget(3,0,lblDate)
.setWidget(3,1,boxDate)
.setWidget(4,0,lblStudentNum)
.setWidget(4,1,lbxStudentNum)
.setWidget(5,0,radHCopy)
.setWidget(5,1,radECopy)
.setWidget(6,0,radTExam)
.setWidget(7,0,radEExam)
.setWidget(7,1,txtElementsID)
.setWidget(8,0,radQExam)
.setWidget(8,1,txtQuiaLink)
.setWidget(9,1,txtQuiaPass)
.setWidget(10,0,txtSourceGrp)
.setWidget(10,1,txtTypeGrp)
.setWidget(11,0,btnCreate)
//Add this panel to the application
app.add(vrtMainPanel);
//Return the application
return app;
}
function getPhone(e){
var spSheet = SpreadsheetApp.openById('0Aur3owCpuUY-dFF0dVZXb3I1Yjlpbzg3SXFIaklEcUE');
var spTeacherList = spSheet.getSheetByName('TeacherList');
var lstTeacherNames = spTeacherList.getRange(1,2,spTeacherList.getLastRow(),1).getValues();
var app = UiApp.getActiveApplication();
var txtExt = app.getElementById('txtExt');
txtExt.setText(lstTeacherNames[Number(e.parameter.lbxTeacherName)][0]);// we get the value in the 2D array returned by getValues()
return app;
}
EDIT : following your last comment.
Although the method you used to retrieve the teacher's name is excellent (and I guess indeed that I'd have chosen the same approach ) there is another way to achieve it which is less obvious but much more efficient in terms of "number of code lines" .
The trick it to store the teacher name as a TAG on the extension phone number and to retrieve it from there in the createEvent() handler.
The code needs only a very minor modification (get 2 columns of data from the SS and assign a value to the tag+get that value - see comments in code) so I won't reproduce the whole thing, just the relevant part below :
function getPhone(e){
var spSheet = SpreadsheetApp.openById('0AnqSFd3iikE3dEtBQndOYVNEbFVWcDlyQmFoaUV3a1E');
var spTeacherList = spSheet.getSheetByName('TeacherList');
var lstTeacherNames = spTeacherList.getRange(1,1,spTeacherList.getLastRow(),2).getValues();// get 2 columns instead of only one
Logger.log(lstTeacherNames);
var app = UiApp.getActiveApplication();
var txtExt = app.getElementById('txtExt');
txtExt.setText(lstTeacherNames[Number(e.parameter.lbxTeacherName)][1]);// set the phone number
txtExt.setTag(lstTeacherNames[Number(e.parameter.lbxTeacherName)][0]);// set teacher's name in the TAG
return app;
}
function createEvents(e){
//Get the active application
var app = UiApp.getActiveApplication();
//Get the entries
var ssTeacher = e.parameter.txtExt_tag;
Logger.log('teacher = '+ssTeacher)
...

Resources