site-logo

Google Calendar API – add more fields

The other day I was busy integrating the Google Calendar API for a events website and after working with the API you begin to realise how limited your are with the fields the Google Calendar API makes available to you. It only returns limited fields that is available for a event. In the article I am going to show you how to add more fields. It’s not a perfect solution, but it gets the job done.

Google Calendar API

The new Google Calendar API (v3) is very limited when you want to add more data especially more fields which is not currently possible.

Also the widgets under the Google Calendar Labs does not integrate with the API so you can’t pull in data stored in the add-on widgets like attachments for example. I have found a way to “attach a image” to an event. I will explain this a bit later in the article.

Google Calendar > Settings > Labs https://www.google.com/calendar/render#m

It is also made quite clear on the Lab page.:

Google Calendar Labs is a testing ground for experimental features that aren’t quite ready for primetime. They may change, break or disappear at any time.

This is what the current events editor looks like when you want to add a event. The areas mark in Red is the only fields that you can retrieve.

Google_Calendar Event

This makes is a bit boring. What if you organise events and you need to add more info like the cost, contact person, email address and more?

Google Calendar API custom fields

Basically this is what is available in the array returned by the Google Calendar API. Not much hey?

{
  "kind": "calendar#calendarListEntry",
  "etag": etag,
  "id": string,
  "summary": string,
  "description": string,
  "location": string,
  "timeZone": string,
  "summaryOverride": string,
  "colorId": string,
  "backgroundColor": string,
  "foregroundColor": string,
  "hidden": boolean,
  "selected": boolean,
  "accessRole": string,
  "defaultReminders": [
    {
      "method": string,
      "minutes": integer
    }
  ],
  "notificationSettings": {
    "notifications": [
      {
        "type": string,
        "method": string
      }
    ]
  },
  "primary": boolean,
  "deleted": boolean
}

To be able to add more data to a Google Calendar event do the following. Yes its not perfect, but it works well for a temporary solution until Google give you the option to add more data fields.

In the description box add all your information separated by pipes ” | ” for example.:

Description box.:

Flickr_photo_id_302494 | R4000 | Stay at the luxurious Cape Hotel
in Cape Town for a unforgettable weekend and experience 
the white sandy beach in Clifton under the 
African sun. | 021 000 1000 | info@capem.com

You will need to make a note in the order the data is stored for example.:

Image | Cost | Description | Contact Number | Email Address

Now when you make a connection to the Google Calendar API and you pull in all the fields from the array you will notice the description variable inside the array of data been pulled. This Description variable now contains allot more data fields separate by a pipe ” | “.

The two functions I use to pull in a specific event and then to pull the information apart in the description variable.:

<?php
#Finds a specific event
public function eventId($eventid) {
	
   $service = $this->googleCalendar();
   
   # This will check if it is the "primary" calender or pre-defined calendar.
   (CALENDAR_ID != "") ? $calendarId = CALENDAR_ID : $calendarId = 'primary';

   $event = $service->events->get($calendarId, $eventid);
   
   $this->eventsInfo($event);
}


# Creates a Array for the Event(s)
public function eventsInfo($event) {
    $desc = explode("|", $event['description']);
    $desc['photo_id'] = trim($desc[0]);
    $desc['cost'] = trim($desc[1]);
    $desc['text'] = $desc[2];
    $desc['contact'] = trim($desc[3]);
    $desc['email'] = trim($desc[4]);

    for ($i = 0; $i < count($desc); $i++) { unset($desc[$i]); }

    $image = $this->getflickrImage($desc['photo_id']);

	$html['event_id'] = $event['id'];
	$html['start_time'] = $event['start']['date'];
	$html['end_time'] = $event['end']['date'];
	$html['image'] = $image;
	$html['summary'] = $event['summary'];
	$html['location'] = $event['location'];
	$html['date'] = $event['start']['date'];
	$html['cost'] = $desc['cost'] = ($desc['cost'] == 'no') ? '' : $desc['cost'];
	$html['text'] = $desc['text'] = ($desc['text'] == 'no') ? '' : $desc['text'];
	$html['contact'] = $desc['contact'] = ($desc['contact'] == 'no') ? '' : $desc['contact'];
	$html['email'] = $desc['email'] = ($desc['email'] == 'no') ? '' : $desc['email'];

	$this->htmlData[] = $html;
}
?>

From the above code you will notice that I explode the description variable into a array of items using the pipe ” |” as the string delimiter. So now I have whole lot more physicals data fields I can manipulate or inject into a database with each data value into its own field.

O…before I forget. To “include a image” with your event you can use the Flickr API. So basically you create a flickr account just for Google Calendar events. Upload images to that Flickr account. Now you can pull them into your application via the flickr API with the photo_id(s) you specified in the description field of the Google Calendar Event.

This is how I did it.:

# Loads the flicker API and pulls the image from flicker with requested photo id:
		public function getflickrImage($photoID) {

			$f = new phpFlickr(FLICKR_KEY);
			$photoInfo = $f->photos_getInfo($photoID);
		    $photoFarm = $photoInfo['photo']['farm'];
			$photoServerId = $photoInfo['photo']['server'];
			$photoId = $photoInfo['photo']['id'];
			$photoSecret = $photoInfo['photo']['secret'];
			$photoSize = 'm'; //see below:

			/*s	small square 75x75
			q	large square 150x150
			t	thumbnail, 100 on longest side
			m	small, 240 on longest side
			n	small, 320 on longest side
			-	medium, 500 on longest side
			z	medium 640, 640 on longest side
			c	medium 800, 800 on longest side†
			b	large, 1024 on longest side*
			o	original image, either a jpg, gif or png, depending on source format
			*/
			return $image = 'https://farm'.$photoFarm.'.staticflickr.com/'.$photoServerId.'/'.$photoId.'_'.$photoSecret.'_'.$photoSize.'.jpg';
		}

So there you have it. This is the best way I could find to add more “fields” to my Google Calendar Events.

Also as a extra bonus if you want to start playing with date ranges. For example to display all the events for one year plus one month see the following code.:

<?php

public function getYearRange() {

	$service = $this->googleCalendar();

	# This will check if it is the "primary" calendar or pre-defined calendar.
	(CALENDAR_ID != "") ? $calendarId = CALENDAR_ID : $calendarId = 'primary';

	#Set the the date range for one year. Plus work out the range for one year + 1 month:
	$currentDate = date('Y-m-d'); //get the current date
	$startDate = $currentDate;
	$y = (int) date('Y');
	$y = $y + 1;
	$y = (string) $y;
	$m = (int) date('m');
	$m = $m + 1;
	$m = ($m == 13) ? 1 : $m;
	$m = (string) $m;
	(strlen($m) == 1) ? $m = '0'.$m : $m;
	$endDay = date("t", strtotime(''.$y.'-'.$m.'-01'));
	$yearOne = date($y.'-'.$m.'-'.$endDay);
	$endDate = $yearOne;

	# Optional Paramaters (Filter) on the data returned. - https://developers.google.com/google-apps/calendar/v3/reference/events/list
	$optParams = array(
				'maxResults' => '10000',
				'orderBy' => 'updated',
				'timeMin' => $startDate.'T00:00:00.000Z', //From date
				'timeMax' => $endDate.'T23:59:59.999Z' //To date
				);

	# Now work out WHAT months is available in that one year + 1 month period.
	$events = $service->events->listEvents($calendarId,$optParams);

	$html = array();

	$theDate = array(); 

	if(isset($events)) {
	  	foreach ($events->getItems() as $event) {

	  		$theDate = $event['start']['date'];
	  		$theDate = explode('-',$theDate);
	  		$thisDate['day'] = $theDate[2];
	  		$thisDate['month'] = $theDate[1];
	  		$thisDate['year'] = $theDate[0];
	  		if ($thisMonth != $thisDate['month'])  {
	  			$thisMonth = $thisDate['year']."-".$thisDate['month']."-01";
	  			$monthNum  = $thisDate['month'];
				$dateObj   = DateTime::createFromFormat('!m', $monthNum);
				$monthName = $dateObj->format('F');
				$daysInMonth = date("t", strtotime('2014-'.$thisDate['month'].'-01'));

				$html['date'] = $monthName . ' ' . $thisDate['year'];
				$html['startDate'] = $thisMonth;
				$html['endDate'] = $thisDate['year']."-".$thisDate['month']."-".$daysInMonth;
				
				$this->htmlData[] = $html;
	  		}	

	  		$thisMonth = $thisDate['month'];
	  		$thisYear = $thisDate['year'];
	  	
		}
	}
?>

I hope that I sparked off some ideas and that this article helps you on your quest to build better Google Calendar integrations. Have fun!

If you want to use my code just remember to credit me and include a reference to my website.

GO BACK : BLOG-PAGE