Google Form responses (in sheet) create a Google calendar event - javascript

I have a Google Form to automate bookings - the form responses are populated into a Google Sheet - what I want then is to use the trigger for when a form is submitted to create a calendar event in a group calendar.
What I need is the event to show: the email address of organizer, how many boards, the room number, date, start, and end time
function createCalendarEvent() {
let groupCalendar = CalendarApp.getCalendarById("CalendarID#group.calendar.google.com")
let sheet = SpreadsheetApp.getActiveSheet();
let schedule = sheet.getDataRange().getValues();
schedule.splice(0,1);
schedule.forEach(function(entry){
groupCalendar.createEvent(entry[1], entry[3],entry[4], entry[5], entry[6], entry[7]);
});
}

Related

How to create a new row at the end of an existing sheet in Google Spreadsheets after completing a Google Form?

I'm trying to save responses from a linked Google Form into an existing Google sheet. More precisely, the spreadsheet shows employee's time off requests with the employee's Reason for leave, Number of days requested, Date Requested, Name of Manager, etc. Basically, the form asks the employee for these information.
Thanks!
What I'm trying to achieve here is saving the response information into the already created spreadsheet. According to Google's documentation, the only two options are: 1) Create a new spreadsheet: Creates a spreadsheet for responses in Google Sheets
2) Select existing spreadsheet: Choose from your existing spreadsheets in Google Sheets to store responses
In case of option #2, I can save responses in the same spreadsheet BUT it saves them in a new sheet; I'm trying to save the responses in the same
sheet.
I know that Google Form has a Script Editor. Would it be possible to run a function that sends the responses to the Spreadsheet? Maybe something like this?
function sendToSpreadSheet(e)
{
var ss = SpreadsheetApp.openById("abc1234567");
// Send response to spreadsheet
// Populate cells accordingly
}
I don't have much experience with Google Forms, so I'm not sure how to approach this issue. Any suggestion(s) is greatly appreciated.
Try this:
You have to supply the Spreadsheet Id and SheetName. And also create a onFormSubmit trigger for the spreadsheet.
function saveResponse(e) {
SpreadsheetApp.getActive().getSheetByName('SheetName').append(e.values);
}
or
function saveResponse(e) {
SpreadsheetApp.openById('id').getSheetByName('SheetName').append(e.values);
}
onFormSubmit Event Object for Spreadsheet
You can create trigger with something like this:
function createSetResponseTrigger(){
createTrigger('setResponse');
}
function createTrigger(funcname) {
if(!isTrigger(funcname)) {
ScriptApp.newTrigger(funcname).forSpreadsheet(SpreadsheetApp.getActive()).onFormSubmit().create();
}
}
and this
function isTrigger(funcName){
var r=false;
if(funcName){
var allTriggers=ScriptApp.getProjectTriggers();
for(var i=0;i<allTriggers.length;i++){
if(funcName==allTriggers[i].getHandlerFunction()){
r=true;
break;
}
}
}
return r;
}
or you can just create it manually with Edit Menu/Current Project Triggers.

SpreadsheetApp / FormApp - Changelog

I have a script that records a log of all changes in a spreadsheet:
function onEdit() {
var timestamp = new Date();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = sheet.getActiveCell();
var user = Session.getActiveUser();
var columnLabel = sheet.getRange(1, cell.getColumn()).getValue();
var changelogSheet = ss.getSheetByName("Changelog");
changelogSheet.appendRow([timestamp, cell.getA1Notation(), columnLabel, cell.getValue(), user.getEmail()]);
}
This codes beautifully creates a row of data in "Changelog" sheet every time there is an edit on "Sheet1". It tells you the date and time, the cell where it was edited, the contents of edit and user who edited it.
My issue is that "Sheet1" is linked to a Google Form that allows users to edit their responses. When users indeed edit their responses on Google Forms, the edit is not registered on my script and there is no log for it.
I presume my script only logs physical edits on the sheet itself.
Is there a way (perhaps using FormApp) to do a similar code that logs every edit on a Google Form?
I really appreciate your help.
You should create a new onFormSubmit trigger that will include similar logic and create a new row in the Google Sheet when a form response is submitted.

How to detect the change when my google sheet is updated and send an Email

I have been trying to send an email when my sheet gets new values, The sheet is getting values automatically, and email needs to be sent to a specific Email address, and it needs to be sent to every new entry, so google integrated "Notify on change is out of the question".
Here is my scenario:
my source sheet: "Leads"// name of the sheet
my target sheet: "Closer"//name of the sheet
when a new row is inserted into the Leads sheet Its values automatically get inserted into the Closer sheet in the end. So for each new values inserted in the Leads, Closer gets a new row.
I have designed a script of my own for that but it sends me too many emails, what I want my script to do is when a new row is inserted send the email, whether that is to self or any email, I know how to send email I am just getting a lot of problems, with getting the change functionality in my script.
Here is what I have done so far:
function sendNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Leads");
var mycell = sheet.getRange("A:A");
var cellcol = mycell.getColumn();
var cellrow = mycell.getRow();
var recipients = "someone#gmail.com";
var subject = "Notification for sheet updation "+ss.getName();
var body = ss.getName() + "has been updated. Visit " + ss.getUrl() + " to view the changes.";
if (mycell == 1)
{
MailApp.sendEmail(recipients, subject, body);
}}
This function works, but it sends 5,6 emails for each row submitted, I have tried many things but I cannot figure out what is the problem with this code.I just want my code to send one email for each row inserted, I would really appreciate some help with this script, Thank you.

How can I import URL from google calendars to google sheets using Appscript?

I am writing an Appscript that automatically imports google calendar events into google sheets. I do however seem to be experiencing problems with importing the URL to be able to link to the calendar event.
Is there a function that will allow me to do this easily, alternatively, does anyone know of a way of doing it that doesn't involve advanced services.
Thanks in advance
PS. Here is what I have working so far, a bit of a hash of stuff that I have seen online. Apologies if its not good code.
I'm struggling with getting the URL for the calendar invite.
function calendar_importer(){
//
// Import google calendar events into google sheets.
//
// This code retrieves events between the current date and any date in the future.
// It logs the results in the current spreadsheet starting at cell A2 listing the events,
// dates/times, etc and even calculates event duration (via creating formulas in the spreadsheet) and formats the values.
//
// I do re-write the spreadsheet header in Row 1 with every run, as I found it faster to delete then entire sheet content,
// change the parameters, and re-run my exports versus trying to save the header row manually...so be sure if you change
// any code, you keep the header in agreement for readability!
//
// 1. Please modify the value for mycal to be YOUR calendar email address or one visible on your MY Calendars section of your Google Calendar
// 2. Please modify the values for events to be the date/time range you want and any search parameters to find or omit calendar entires
// Note: Events can be easily filtered out/deleted once exported from the calendar
//
// This script is triggered to run once every 5 minutes, doing this will wipe the spreadsheet in its entirity and download a new set of data.
// This way only the most up to date information is displayed from the calendar.
//
// Enter the address of the calendar you wish to download onto the google spreadsheet below.
var mycal = "edmsmedical#gmail.com";
// Request calendar from google calendars
var cal = CalendarApp.getCalendarById(mycal);
// Calculate today + 365 days for rolling yearly end date.
var EndDate = new Date();
EndDate.setDate(EndDate.getDate()+365);
// Set the desired dates for the spreadsheet to show below. () denotes todays date and will only download events from and including todays date until the set end date.
// Should you wish to select specific dates enter a date and time value in the () for start and end date.
var events = cal.getEvents(new Date(), new Date(EndDate));
// Activates sheet so that it can be cleared as per next instruction.
var sheet = SpreadsheetApp.getActiveSheet();
// Uncomment this next line if you want to always clear the spreadsheet content before running - Note people could have added extra columns on the data though that would be lost.
sheet.clearContents();
// Create a header record on the current spreadsheet in cells A1:N1 - Match the number of entries in the "header=" to the last parameter
// of the getRange entry below
var header = [["Date", "Event Details", "Staffing", "Location", "Start", "End", "Duration", "Calendar Link"]]
var range = sheet.getRange(1,1,1,8);
range.setValues(header);
// Loop through all calendar events found and write them out starting on calulated ROW 2 (i+2)
for (var i=0;i<events.length;i++) {
var row=i+2;
var myformula_placeholder = '';
// Matching the "header=" entry above, this is the detailed row entry "details=", and must match the number of entries of the GetRange entry below.
//*var splitEventId = events[i].getId().split('#');
//*var eventURL = "https://www.google.com/calendar/event?eid=" + Utilities.base64Encode(splitEventId[0] + "&ctz=Ect/GMT" );
//*some work required to complete the URL framework - what format does google use to link URLs
//*var EventId = events[i].getId();
var details=[[events[i].getStartTime(), events[i].getTitle(), events[i].getDescription(), events[i].getLocation(), events[i].getStartTime(), events[i].getEndTime(), events[i].getCreators(), "eventURL"]]
var range=sheet.getRange(row,1,1,8);
range.setValues(details);
var cell=sheet.getRange(row,7);
// Calculation for event duration, displayed in HH:MM
cell.setFormula('=HOUR(F' +row+ '-E' +row+ ')+(MINUTE(F' +row+ '-E' + row +')/60)');
}
}
If you check the Apps Script Document and Google Apps Script Quickstart (for Calendar):
The advanced Calendar service allows you to use the public Google Calendar API in Apps Script. Much like Apps Script's built-in Calendar service, this API allows scripts to access and modify the user's Google Calendar, including additional calendars that the user is subscribed to. In most cases, the built-in service is easier to use, but this advanced service provides a few extra features, including setting the background color for individual events.
One way to check the contents of the variable event is use Logger.log. You can try this sample code:
function listUpcomingEvents() {
var calendarId = 'primary';
var optionalArgs = {
timeMin: (new Date()).toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 10,
orderBy: 'startTime'
};
var response = Calendar.Events.list(calendarId, optionalArgs);
var events = response.items;
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
Logger.log(event)
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
Logger.log('%s (%s)', event.summary, when);
}
} else {
Logger.log('No upcoming events found.');
}
}
If you will check the Events Resource :
htmlLink
An absolute link to this event in the Google Calendar Web UI. Read-only.
Also here is a tutorial : Export from Calendar to Sheet using Apps Script.
Hope this helps!

Multiple forms triggered to single sheet

I have a google spreadsheet that takes information from two different forms.
Manually triggering using the spreadsheet UI does not let you distinguish which form is specified when choosing "OnFormSubmit" in the triggers menu.
Thus, I am using the following code (for my sheet) to manage two different triggering events for two different form-submits:
function onOpen(e) {
var form = FormApp.openById('ID of Form 1');
ScriptApp.newTrigger('onForm1Submit')
.forForm(form)
.onFormSubmit()
.create();
var signup = FormApp.openById('[ID of Form 2]');
signup.setRequireLogin(true)
ScriptApp.newTrigger('SignUpEvent')
.forForm(signup)
.onFormSubmit()
.create();
}
function SignUpEvent(e) {
\\stuff
}
function onForm1Submit(e) {
\\stuff
}
But when I do it this way, I am recieving a failure notification on form submit:
Function: UpdateLadder
Error Message: "Authorization is required to perform that action."
Trigger: "formSubmit"
First off, how am I recieving these email notifications to begin with? I didn't manually ask for email notifications of error messages.
Secondly, what's the best way for me to get "authorization"?
For the onFormSubmit() function, you can write code to match the destination sheet to a certain function. For example, I have a spreadsheet that has 2 forms that both have sheets for destination within it. In the onFormSubmit() trigger code, here is what I did:
function onFormSubmit(e) {
Logger.log("[METHOD] onFormSubmit");
var sheet = e.range.getSheet();
var sheetId = sheet.getSheetId();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var student = ss.getSheetByName("Student Requests");
var studentId = student.getSheetId();
var teacher = ss.getSheetByName("Teacher Requests");
var teacherId = teacher.getSheetId();
if (sheetId == studentId){
sendStudentEmail(e.range);
}
if (sheetId == teacherId){
sendTeacherEmail(e.range)
}
}
So, in this example, a Teacher can request using a form, and if the onFormSubmit is related to the Teacher form, then send the Teacher email, etc..
I'm reasonably certain that onFormSubmit ties one spreadsheet to one form; it doesn't know what to do with two onFormSubmit triggers.

Categories