Integrate Google Calendar API with Codeigniter Calendar Library
Google Calendar allows users to create and edit events. Reminders can be enabled for events, with options available for type and time. Event locations can also be added, and other users can be invited to events. In this article, you will learn how to work with the Google Calendar API with Codeigniter Calendar Library. This is a very simple example, you can just copy paste, and change according to your requirement.
Follow some basic steps
- Register a Google Application and enable Calendar API.
- In your web application, request user for authorization of the Google Application.
- Get the user’s timezone.
- Use the primary calendar of the user.
- Create an event.
Setting up a Google Console Project and enable Calendar API
Step-1 Create a new project in the Google Developers Console.
Click the Library tab on the left. Search for “Calendar API” and enable it.
Credentials tab on the left. In the next screen click on “OAuth consent screen”. Fill out the mandatory fields. Save it
Click on the “Credentials” tab (just beside “OAuth consent screen”). In the screen, click on “Create credentials”. Choose “OAuth Client ID”
Next screen fill out the name. The Application type should be “Web application”
Add a redirect url in the section Authorised redirect URIs
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ "web":{ "client_id":"[hash-string].apps.googleusercontent.com"," project_id":"[project-id]", "auth_uri":"https://accounts.google.com/o/oauth2/auth", "token_uri":"https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs", "client_secret":"[hash-string]", "redirect_uris":[ "https://www.example.com/oauth2callback" ] } } |
Require the Google API Client
Composer setup so first up we require the Google API client:
1 |
composer require google/apiclient:^2.0 |
This gives us a PHP Library to communicate with the Google APIs plus a load of helper functions for each API and OAuth2.
For More information : Google API Client
Before started to implement the Google Calendar API with Codeigniter Calendar, look files structure:
- integrate-google-calendar-api-with-codeigniter-calendar-library
- application
- config
- calendar.php
- constants.php
- routes.php
- libraries
- Googleapi.php
- controllers
- GoogleCalendar.php
- views
- google-calendar
- login.php
- index.php
- popup
- create.php
- renderadd.php
- event.php
- render.php
- templates
- header.php
- footer.php
- google-calendar
- config
- system
- index.php
- vendor
- assets
- css
- style.css
- js
- custom.css
- application
Step 2: Create new config file
Create new file named calendar.php inside “application/config/” folder.
1 2 3 4 |
<?php $config['client_id'] = 'xxxxxxxxxxxxxx.apps.googleusercontent.com'; $config['client_secret'] = 'xxxxxxxxxxxxxx'; ?> |
Step 3: Create file (Googleapi)
Create a file named Googleapi.php inside “application/libraries” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<?php /** * @package Google API : Google Client API * * @author TechArise Team * * @email info@techarise.com * * Description of Contact Controller */ if (!defined('BASEPATH')) exit('No direct script access allowed'); class Googleapi { /** * Googleapi constructor. */ public function __construct() { // load google client api require_once BASH_PATH.'vendor/autoload.php'; $this->client = new Google_Client(); $this->client->setApplicationName('Calendar Api'); $this->ci =& get_instance(); $this->ci->config->load('calendar'); $this->client->setClientId($this->ci->config->item('client_id')); $this->client->setClientSecret($this->ci->config->item('client_secret')); $this->client->setRedirectUri($this->ci->config->base_url().'gc/auth/oauth'); $this->client->addScope(Google_Service_Calendar::CALENDAR); $this->client->addScope('profile'); } public function loginUrl() { return $this->client->createAuthUrl(); } public function getAuthenticate() { return $this->client->authenticate(); } public function getAccessToken() { return $this->client->getAccessToken(); } public function setAccessToken() { return $this->client->setAccessToken(); } public function revokeToken() { return $this->client->revokeToken(); } public function client() { return $this->client; } public function getUser() { $google_ouath = new Google_Service_Oauth2($this->client); return (object)$google_ouath->userinfo->get(); } public function isAccessTokenExpired() { return $this->client->isAccessTokenExpired(); } } ?> |
Step 4: Define constants
Update file named constants.php inside “application/config/” folder.
1 2 3 4 5 6 7 8 9 10 11 |
<?php $root = "http://" . $_SERVER['HTTP_HOST']; $currentDir = str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']); $root .= $currentDir; $constants['base_url'] = $root; define('BASH_PATH', '/Applications/XAMPP/htdocs'.$currentDir); define('HTTP_CSS_PATH', $constants['base_url'] . 'assets/css/'); define('HTTP_JS_PATH', $constants['base_url'] . 'assets/js/'); define('HTTP_IMAGE_PATH', $constants['base_url'] . 'assets/images/'); ?> |
Step 5: Create a controller file
Create a controller file named GoogleCalendar.php inside “application/controllers” folder.
- The GoogleCalendar controller handles the calendar process.
__construct()
– Loads the required library, helper and model.index()
– load index file and render calendar data.getCalendar()
– render dynamic calendar processlogin()
– load form and process.getEvents()
– get google calendar eventaddEvent()
andactionEvent()
– insert event in google caendar.viewEvent()
– fetch event from google caendar.logout()
– Logouts users from their account.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 |
<?php /* * *** * Version: 1.0.0 * * Description of Google Calendar Controller * * @author TechArise Team * * @email info@techarise.com * * *** */ if (!defined('BASEPATH')) exit('No direct script access allowed'); class GoogleCalendar extends CI_Controller { public function __construct() { parent::__construct(); //load library $this->load->library('googleapi'); $this->calendarapi = new Google_Service_Calendar($this->googleapi->client()); } public function index() { if (!$this->isLogin()) { $this->session->sess_destroy(); redirect('gc/auth/login'); } else { $data = array(); $data['metaDescription'] = 'Google Calendar'; $data['metaKeywords'] = 'Google Calendar'; $data['title'] = "Google Calendar - TechArise"; $data['breadcrumbs'] = array('Google Calendar' => '#'); $this->load->view('google-calendar/index', $data); } } // index method public function getCalendar() { if (!$this->isLogin()) { $this->session->sess_destroy(); redirect('gc/auth/login'); } else { $data = array(); $curentDate = date('Y-m-d', time()); if ($this->input->post('page') !== null) { $malestr = str_replace("?", "", $this->input->post('page')); $navigation = explode('/', $malestr); $getYear = $navigation[1]; $getMonth = $navigation[2]; $start = date($getYear.'-'.$getMonth.'-01').' 00:00:00'; $end = date($getYear.'-'.$getMonth.'-t').' 23:59:59'; } else { $getYear = date('Y'); $getMonth = date('m'); $start = date('Y-m-01').' 00:00:00'; $end = date('Y-m-t').' 23:59:59'; } if ($this->input->post('year') !== null) { $getYear = $this->input->post('year'); $start = date($getYear.'-m-01').' 00:00:00'; echo $end = date($getYear.'-m-t').' 23:59:59'; } if ($this->input->post('month') !== null) { $getMonth = $this->input->post('month'); $start = date($getYear.'-'.$getMonth.'-01').' 00:00:00'; $end = date($getYear.'-'.$getMonth.'-t').' 23:59:59'; } $already_selected_value = $getYear; $earliest_year = 1950; $startYear = ''; $googleEventArr = array(); $calendarData = array(); $eventData = $this->getEvents('primary', $start, $end, 40); foreach ($eventData as $element) { $googleEventArr[ltrim(date('d', strtotime($element['start_date'])), 0)] = '<a data-google_event="' . ltrim(date('Y-m-d', strtotime($element['start_date'])), 0) . '" href="#" data-caltoggle="tooltip" data-placement="bottom" title="Google Events" class="small google-event" data-toggle="modal" data-target="#google-cal-data" rel="noopener noreferrer"><i class="fa fa-fw fa-circle text-primary"></i></a>'; } foreach (array_keys($googleEventArr) as $key) { $calendarData[$key] = '<div class="calendar-dot-area small" style="position: relative;z-index: 2;">' . (isset($googleEventArr[$key]) ? $googleEventArr[$key] : '') . '</div>'; } $class = 'href="#" data-currentdate="' . $curentDate . '" class="add-gc-event" data-toggle="modal" data-target="#gc-create-event" data-year="' . $getYear . '" data-month="' . $getMonth . '" data-days="{day}"'; $startYear .= '<div class="col-md-3 col-sm-5 col-xs-7 col-md-offset-3 col-sm-offset-1"><div class="select-control"><select name="year" id="setYearVal" class="form-control">'; foreach (range (date ('Y') + 50, $earliest_year) as $x) { $startYear .= '<option value="' . $x . '"' . ($x == $already_selected_value ? ' selected="selected"' : '') . '>' . $x . '</option>'; } $startYear .= '</select></div></div>'; $startMonth = '<div class="col-md-3 col-sm-5 col-xs-7 col-md-offset-3 col-sm-offset-1"><div class="select-control"><select name="mont h" id="setMonthVal" class="form-control"><option value="0">Select Month</option> <option value="01" ' . ('01' == $getMonth ? ' selected="selected"' : '') . '>January</option> <option value="02" ' . ('02' == $getMonth ? ' selected="selected"' : '') . '>February</option> <option value="03" ' . ('03' == $getMonth ? ' selected="selected"' : '') . '>March</option> <option value="04" ' . ('04' == $getMonth ? ' selected="selected"' : '') . '>April</option> <option value="05" ' . ('05' == $getMonth ? ' selected="selected"' : '') . '>May</option> <option value="06" ' . ('06' == $getMonth ? ' selected="selected"' : '') . '>June</option> <option value="07" ' . ('07' == $getMonth ? ' selected="selected"' : '') . '>July</option> <option value="08" ' . ('08' == $getMonth ? ' selected="selected"' : '') . '>August</option> <option value="09" ' . ('09' == $getMonth ? ' selected="selected"' : '') . '>September</option> <option value="10" ' . ('10' == $getMonth ? ' selected="selected"' : '') . '>October</option> <option value="11" ' . ('11' == $getMonth ? ' selected="selected"' : '') . '>November</option> <option value="12" ' . ('12' == $getMonth ? ' selected="selected"' : '') . '>December</option> </select></div></div>'; //{heading_title_cell}<th colspan="{colspan}">'.$startMonth.' '.$startYear.'{heading}</th>{/heading_title_cell} $prefs['template'] = ' {table_open}<table border="0" width="100%" height="100%" cellpadding="0" cellspacing="0" class="calendar">{/table_open} {heading_row_start}<tr style="border:none;">{/heading_row_start} {heading_previous_cell}<th style="border:none;" class="padB"><a class="calnav" data-calvalue="{previous_url}" href="javascript:void(0);"><i class="fa fa-chevron-left fa-fw"></i></a></th>{/heading_previous_cell} {heading_title_cell}<th style="border:none;" colspan="{colspan}"><div class="row">' . $startMonth . '' . $startYear . '</div></th>{/heading_title_cell} {heading_next_cell}<th style="border:none;" class="padB"><a class="calnav" data-calvalue="{next_url}" href="javascript:void(0);"><i class="fa fa-chevron-right fa-fw"></i></a></th>{/heading_next_cell} {heading_row_end}</tr>{/heading_row_end} {week_row_start}<tr>{/week_row_start} {week_day_cell}<th>{week_day}</th>{/week_day_cell} {week_row_end}</tr>{/week_row_end} {cal_row_start}<tr>{/cal_row_start} {cal_cell_start}<td>{/cal_cell_start} {cal_cell_start_today}<td>{/cal_cell_start_today} {cal_cell_start_other}<td class="other-month">{/cal_cell_start_other} {cal_cell_content}<a ' . $class . '>{day}</a>{content}{/cal_cell_content} {cal_cell_content_today}<a ' . $class . '>{day}</a>{content}<div class="highlight"></div>{/cal_cell_content_today} {cal_cell_no_content}<a ' . $class . '>{day}</a>{/cal_cell_no_content} {cal_cell_no_content_today}<a ' . $class . '>{day}</a><div class="highlight"></div>{/cal_cell_no_content_today} {cal_cell_blank} {/cal_cell_blank} {cal_cell_other}{day}{/cal_cel_other} {cal_cell_end}</td>{/cal_cell_end} {cal_cell_end_today}</td>{/cal_cell_end_today} {cal_cell_end_other}</td>{/cal_cell_end_other} {cal_row_end}</tr>{/cal_row_end} {table_close}</table>{/table_close}'; $prefs['start_day'] = 'monday'; $prefs['day_type'] = 'short'; $prefs['show_next_prev'] = TRUE; $prefs['next_prev_url'] = '?'; $this->load->library('calendar', $prefs); $data['calendar'] = $this->calendar->generate($getYear, $getMonth, $calendarData, $this->uri->segment(3), $this->uri->segment(4)); echo $data['calendar']; } } // login method public function login() { if ($this->session->userdata('is_authenticate_user') == TRUE) { redirect('gc/auth/index'); } else { $data = array(); $data['metaDescription'] = 'Google Plus Login'; $data['metaKeywords'] = 'Google Plus Login'; $data['title'] = "Google Plus Login - TechArise"; $data['breadcrumbs'] = array('Google Plus Login' => '#'); $data['loginUrl'] = $this->loginUrl(); $this->load->view('google-calendar/login', $data); } } // oauth method public function oauth() { $code = $this->input->get('code', true); $this->oauthLogin($code); redirect(base_url(), 'refresh'); } // check login session public function isLogin() { $token = $this->session->userdata('google_calendar_access_token'); if ($token) { $this->googleapi->client->setAccessToken($token); } if ($this->googleapi->isAccessTokenExpired()) { return false; } return $token; } public function loginUrl() { return $this->googleapi->loginUrl(); } // oauthLogin public function oauthLogin($code) { $login = $this->googleapi->client->authenticate($code); if ($login) { $token = $this->googleapi->client->getAccessToken(); $this->session->set_userdata('google_calendar_access_token', $token); $this->session->set_userdata('is_authenticate_user', TRUE); return true; } } // get User Info public function getUserInfo() { return $this->googleapi->getUser(); } // get Events public function getEvents($calendarId = 'primary', $timeMin = false, $timeMax = false, $maxResults = 10) { if ( ! $timeMin) { $timeMin = date("c", strtotime(date('Y-m-d ').' 00:00:00')); } else { $timeMin = date("c", strtotime($timeMin)); } if ( ! $timeMax) { $timeMax = date("c", strtotime(date('Y-m-d ').' 23:59:59')); } else { $timeMax = date("c", strtotime($timeMax)); } $optParams = array( 'maxResults' => $maxResults, 'orderBy' => 'startTime', 'singleEvents' => true, 'timeMin' => $timeMin, 'timeMax' => $timeMax, 'timeZone' => 'Asia/Kolkata', ); $results = $this->calendarapi->events->listEvents($calendarId, $optParams); $data = array(); $creator = new Google_Service_Calendar_EventCreator(); foreach ($results->getItems() as $item) { if(!empty($item->getStart()->date) && !empty($item->getEnd()->date)) { $startDate = date('d-m-Y H:i', strtotime($item->getStart()->date)); $endDate = date('d-m-Y H:i', strtotime($item->getEnd()->date)); } else { $startDate = date('d-m-Y H:i', strtotime($item->getEnd()->dateTime)); $endDate = date('d-m-Y H:i', strtotime($item->getEnd()->dateTime)); } $created = date('d-m-Y H:i', strtotime($item->getCreated())); $updated = date('d-m-Y H:i', strtotime($item->getUpdated())); array_push( $data, array( 'id' => $item->getId(), 'summary' => trim($item->getSummary()), 'description' => trim($item->getDescription()), 'creator' => $item->getCreator()->getEmail(), 'organizer' => $item->getOrganizer()->getEmail(), 'creatorDisplayName' => $item->getCreator()->getDisplayName(), 'organizerDisplayName' => $item->getOrganizer()->getDisplayName(), 'created' => $created, 'updated' => $updated, 'start_date' => $startDate, 'end_date' => $endDate, 'status' => $item->getStatus(), ) ); } return $data; } // add google calendar event public function addEvent() { if (!$this->isLogin()) { $this->session->sess_destroy(); redirect(base_url(), 'refresh'); } else { $json = array(); $calendarId = 'primary'; $post = $this->input->post(); if(empty(trim($post['summary']))){ $json['error']['summary'] = 'Please enter summary'; } // start date time validation if(empty(trim($post['startDate'])) && empty($post['startTime'])){ $json['error']['startdate'] = 'Please enter start date time'; } if(empty(trim($post['endDate'])) && empty($post['endTime'])){ $json['error']['enddate'] = 'Please enter end date time'; } if(empty(trim($post['description']))){ $json['error']['description'] = 'Please enter description'; } if(empty($json['error'])){ $event = array( 'summary' => $post['summary'], 'start' => $post['startDate'].'T'.$post['startTime'].':00+03:00', 'end' => $post['endDate'].'T'.$post['endTime'].':00+03:00', 'description' => $post['description'], ); $data = $this->actionEvent($calendarId, $event); if ($data->status == 'confirmed') { $json['message'] = 1; } else { $json['message'] = 0; } } $this->output->set_header('Content-Type: application/json'); echo json_encode($json); } } // actionEvent public function actionEvent($calendarId, $data) { //Date Format: 2016-06-18T17:00:00+03:00 $event = new Google_Service_Calendar_Event( array( 'summary' => $data['summary'], 'description' => $data['description'], 'start' => array( 'dateTime' => $data['start'], 'timeZone' => 'Asia/Kolkata', ), 'end' => array( 'dateTime' => $data['start'], 'timeZone' => 'Asia/Kolkata', ), 'attendees' => array( array('email' => 'info@techarise.com'), ), ) ); return $this->calendarapi->events->insert($calendarId, $event); } // get event list public function viewEvent() { $json = array(); if (!$this->isLogin()) { $this->session->sess_destroy(); redirect(base_url(), 'refresh'); } else { $google_event_date = $this->input->post('google_event_date'); $start = date($google_event_date).' 00:00:00'; $end = date($google_event_date).' 23:59:59'; $eventData = $this->getEvents('primary', $start, $end, null); /*echo "<pre>"; print_r($eventData);die; */ $json['eventData'] = $eventData; $this->output->set_header('Content-Type: application/json'); $this->load->view('google-calendar/popup/render', $json); } } // render Event Form public function renderEventForm() { $json = array(); if (!$this->isLogin()) { $this->session->sess_destroy(); redirect(base_url(), 'refresh'); } else { $datetime = $this->input->post('datetime'); $json['datetime'] = $datetime; $this->output->set_header('Content-Type: application/json'); $this->load->view('google-calendar/popup/renderadd', $json); } } //logout method public function logout() { $this->googleapi->revokeToken(); $this->session->unset_userdata('is_authenticate_user'); $this->session->sess_destroy(); $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0"); $this->output->set_header("Pragma: no-cache"); redirect('gc/auth/login'); } } ?> |
Step 6: Create a view(header)
Create a view file named header.php inside “application/views/templates” folder
This view contains the header section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header section.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title><?php print $title; ?></title> <link rel="icon" type="image/ico" href="<?php print HTTP_IMAGE_PATH; ?>favicon.ico"> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <!-- Custom fonts for this template --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" /> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="<?php print HTTP_CSS_PATH; ?>style.css" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top header-bg-dark" style="background: ##FFFFFF!;"> <div class="container"> <a class="navbar-brand font-weight-bold" href="https://techarise.com"><h1>Tech Arise</h1></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="https://techarise.com">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="https://techarise.com/php-free-script-demos/">Live Demo</a> </li> </ul> </div> </div> </nav> |
Step 7: Create a view(footer)
Create a view file named footer.php inside “application/views/templates” folder
This view contains the footer section of the webpage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<!-- Footer --> <footer class="footer bg-light footer-bg-dark"> <div class="container"> <div class="row"> <div class="col-lg-6 h-100 text-center text-lg-left my-auto"> <ul class="list-inline mb-2"> <li class="list-inline-item"> <a href="#">About</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Contact</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Terms of Use</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Privacy Policy</a> </li> </ul> <p class="text-muted small mb-4 mb-lg-0">Copyright © 2011 - <?php print date('Y', time());?> <a href="https://techarise.com/">TECHARISE.COM</a> All rights reserved.</p> </div> <div class="col-lg-6 h-100 text-center text-lg-right my-auto"> <ul class="list-inline mb-0"> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-facebook fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-twitter-square fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item"> <a href="#"> <i class="fab fa-instagram fa-2x fa-fw"></i> </a> </li> </ul> </div> </div> </div> </footer> <script> var baseurl = "<?php print site_url();?>"; </script> <!-- Bootstrap core JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script> <script> $(document).ready(function () { bsCustomFileInput.init() }) </script> <script src="<?php print HTTP_JS_PATH; ?>custom.js"></script> </body> </html> |
Step 8: Create a view(login)
Create a view file named login.php inside “application/views/google-calendar” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php $this->load->view('templates/header');?> <!-- container --> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Integrate Google Calendar API with Codeigniter Calendar Library</h2> </div> <form action="<?php print site_url();?>auth/doLogin" class="remember-login-frm" id="remember-login-frm" method="post" accept-charset="utf-8" enctype="multipart/form-data"> <div class="row justify-content-center"> <div class="col-12 col-md-8 col-lg-6 pb-5"> <div class="row"><?php echo validation_errors('<div class="col-12 col-md-12 col-lg-12"><div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert">×</button>', '</div></div>'); ?></div> <!--Form with header--> <div class="card border-info rounded-0"> <div class="card-header p-0"> <div class="bg-info text-white text-center py-2"> <h3><i class="fab fa-google-plus-g"></i> Login</h3> </div> </div> <div class="card-body p-3"> <div class="text-center"> <a href="<?php print $loginUrl; ?>" id="contact-send-a" class="btn btn-danger btn-block rounded-0 py-2"><i class="fab fa-google-plus-g"></i> Login with Google</a> </div> </div> </div> </div> </div> </form> </div> </section> <?php $this->load->view('templates/footer');?> |
Step 9: Create a view(index)
Create a view file named index.php inside “application/views/google-calendar” folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php $this->load->view('templates/header');?> <!-- container --> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Integrate Google Calendar API with Codeigniter Calendar Library</h2> </div> <div class="pb-2 mt-4 mb-2 border-bottom"> <a href="javascript:void(0);" data-toggle="modal" data-target="#gc-create-event" data-year="<?php print date('Y', time()); ?> rel="noopener noreferrer">" data-month="<?php print date('m', time()); ?>" data-days="<?php print date('d', time()); ?>" class="add-gc-event btn btn-sm btn-primary">Create Event</a> <a href="<?php print site_url();?>auth/logout" class="add-gc-event btn btn-sm btn-danger">Logout</a> </div> <span id="success-msg"></span> <div id="event-calendar"> <div class="text-center"><i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i></div> </div> </div> </section> <?php $this->load->view('google-calendar/popup/event');?> <?php $this->load->view('google-calendar/popup/create');?> <?php $this->load->view('templates/footer');?> |
Step 10: Create a view(create.php, renderadd.php, event.php and render.php)
Create a view files inside “application/views/google-calendar/popoup” folder.
a:
create.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<div class="modal fade" id="gc-create-event" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Add Event On Google Calendar</h4> <button type="button" class="close" data-dismiss="modal">×</button> </div> <div class="modal-body"> <form name="gc_event_frm" class="gc-event-frm" id="gc-event-frm"> <span id="render-google-cal-add"><div class="text-center"><i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i></div></span> </form> </div> </div> </div> </div> |
b:
renderadd.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<div class="form-group"> <label for="inputAddress">Summary</label> <input type="text" name="summary" class="form-control summary input-gcevent-summary"> </div> <div class="form-row"> <div class="form-group col-md-8"> <label for="inputAddress2">Start Date </label> <input type="date" name="startDate" class="form-control start-date input-gcevent-startdate" value="<?php print $datetime; ?>"> </div> <div class="form-group col-md-4"> <label for="inputAddress2">Start Time</label> <input type="time" name="startTime" class="form-control start-time input-gcevent-starttime" value="<?php print date("H:i"); ?>"> </div> </div> <div class="form-row"> <div class="form-group col-md-8"> <label for="inputAddress2">End Date</label> <input type="date" name="endDate" class="form-control end-date input-gcevent-enddate" value="<?php print $datetime; ?>"> </div> <div class="form-group col-md-4"> <label for="inputAddress2">End Time</label> <input type="time" name="endTime" class="form-control end-time input-gcevent-endtime" value="<?php print date('H:i'); ?>"> </div> </div> <div class="form-group"> <label for="inputAddress">Description</label> <textarea name="description" class="form-control input-gcevent-description" rows="3"></textarea> </div> <button type="button" name="save_gc_event" id="save-gc-event" class="btn btn-primary">Save</button> |
c:
event.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div class="modal fade" id="google-cal-data" role="dialog"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Google Calendar</h4> <button type="button" class="close" data-dismiss="modal">×</button> </div> <div class="modal-body"> <span id="render-google-cal-data"><div class="text-center"><i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i></div></span> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> |
d:
render.php
1 2 3 4 5 6 7 8 9 |
<?php foreach ($eventData as $key => $element) { echo '<div class="card-hover marg-bot22" style="border:1px dashed #cecccc; background: #f8f8f8;padding: 6px;" id="google-cal1"> <a target="_blank" href="# " rel="noopener noreferrer">'.$element['summary']. ' - '.$element['description'].'</a> <br> <span>'.date('l, F d', strtotime($element['start_date'])).'</span> </div>'; } ?> |
Step 5: Create a AJAX file
Create a js file named custom.js inside “assets/js” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
// render calendar if (jQuery('div#event-calendar').length > 0) { jQuery.ajax({ url: baseurl + 'GoogleCalendar/getCalendar', dataType: 'html', beforeSend: function () { $('#event-calendar').html('<div class="text-center mrgA padA"><i class="fa fa-spinner fa-pulse fa-4x fa-fw"></i></div>'); }, complete: function () { jQuery('[data-caltoggle="tooltip"]').tooltip(); }, success: function (html) { jQuery('#event-calendar').html(html); }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); } // render calendar with navigation jQuery(document).on("click", "a.calnav", function (e) { e.preventDefault(); var page = jQuery(this).data("calvalue"); jQuery.ajax({ url: baseurl + 'GoogleCalendar/getCalendar', type: 'post', data: {page: page}, dataType: 'html', beforeSend: function () { $('#event-calendar').html('<div class="text-center mrgA padA"><i class="fa fa-spinner fa-pulse fa-4x fa-fw"></i></div>'); }, complete: function () { jQuery('[data-caltoggle="tooltip"]').tooltip(); }, success: function (html) { jQuery('#event-calendar').html(html); }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); // render calendar change month jQuery(document).on("change", "#setMonthVal", function (e) { e.preventDefault(); var month = this.value; var year = jQuery('#setYearVal > option:selected').val(); jQuery.ajax({ url: baseurl + 'GoogleCalendar/getCalendar', type: 'post', data: {year: year, month: month}, dataType: 'html', beforeSend: function () { $('#event-calendar').html('<div class="text-center mrgA padA"><i class="fa fa-spinner fa-pulse fa-4x fa-fw"></i></div>'); }, complete: function () { jQuery('[data-caltoggle="tooltip"]').tooltip(); }, success: function (html) { jQuery('#event-calendar').html(html); }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); // render calendar change year jQuery(document).on("change", "#setYearVal", function (e) { e.preventDefault(); var year = this.value; var month = jQuery('#setMonthVal > option:selected').val(); jQuery.ajax({ url: baseurl + 'GoogleCalendar/getCalendar', type: 'post', data: {year: year, month: month}, dataType: 'html', beforeSend: function () { $('#event-calendar').html('<div class="text-center mrgA padA"><i class="fa fa-spinner fa-pulse fa-4x fa-fw"></i></div>'); }, complete: function () { jQuery('[data-caltoggle="tooltip"]').tooltip(); }, success: function (html) { jQuery('#event-calendar').html(html); }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); jQuery(document).on('click', 'a.google-event', function() { var google_event_date = jQuery(this).data('google_event'); $.ajax({ url: baseurl + "GoogleCalendar/viewEvent", type: 'post', data: {google_event_date: google_event_date}, dataType: 'html', beforeSend: function () { jQuery('span#render-google-cal-data').html('<div class="text-center"><i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i></div>'); }, success: function (html) { jQuery('span#render-google-cal-data').html(html); }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); function pad(num, size) { var s = num + ""; while (s.length < size) s = "0" + s; return s; } jQuery(document).on("click", "a.add-gc-event", function () { var myYear = jQuery(this).data('year'); var myMonth = jQuery(this).data('month'); var myDays = pad(jQuery(this).data('days'), 2); var completeDate = myYear + '-' + myMonth + '-' + myDays; $.ajax({ url: baseurl + "GoogleCalendar/renderEventForm", type: 'post', data: {datetime: completeDate}, dataType: 'html', beforeSend: function () { jQuery('span#render-google-cal-add').html('<div class="text-center"><i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i></div>'); }, success: function (html) { jQuery('span#render-google-cal-add').html(html); }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); jQuery(document).on('click', 'button#save-gc-event', function(){ jQuery.ajax({ type:'POST', url:baseurl+'GoogleCalendar/addEvent', data:jQuery("form#gc-event-frm").serialize(), dataType:'json', beforeSend: function () { jQuery('button#save-gc-event').button('loading'); }, complete: function () { jQuery('button#ssave-gc-event').button('reset'); jQuery('form#gc-event-frm').find('textarea, input').each(function () { jQuery(this).val(''); }); setTimeout(function () { jQuery('span#success-msg').html(''), jQuery('gc-create-event').modal('hide'), location.reload() }, 3000); }, success: function (json) { $('.text-danger').remove(); if (json['error']) { for (i in json['error']) { var element = $('.input-gcevent-' + i.replace('_', '-')); if ($(element).parent().hasClass('form-row')) { $(element).parent().after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } else { $(element).after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } } } else { jQuery('span#success-msg').html('<div class="alert alert-success">Your Event has been successfully created.</div>'); } }, error: function (xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); |