Developer Apis and Code examples

Last updated on
30 June 2020

Developers can go through Google Api Client documentation to better understand the code.  Considering the example from the configuration page.

Developers needs to create a new event on user's google calendar, on create of the fundraiser event developer can execute some code to retrieve a list of donors who are subscribed and loop, in our case we have only one account which is authenticated/subscribed.

// User properties to search gauth_user entity
$properties = [
  'google_api_account' => GOOGLE_API_CLIENT_ID, // ID for Google Calendar on admin/config/services/google_api_client
  'uid' => \Drupal::currentUser()->id(), // Assuming current user
];

// Load the account
$google_api_client = \Drupal::entityTypeManager()->getStorage('gauth_user')->loadByProperties($properties);
if (empty($google_api_client)) {
  return;
}
$google_api_client = array_values($google_api_client)[0];
// Get the service.
$googleService = \Drupal::service('google_api_client.client');

// Apply the account to the service
$googleService->setGoogleApiClient($google_api_client);

// Try your API Operations.
try {
  // Fetch calendar object.
  $object = $googleService->getServiceObjects();
  // $object['calendar'] is a object of Google_Service_Calendar

  // Retrieve default calendar id of user (check calendar id field we created)
  $calendar_id = $google_api_client->get('field_calendar_id')->getValue();
  if (empty($calendar_id)) {
    // No calendar entry found so we create new.
    $calendar = new \Google_Service_Calendar_Calendar();
    // Title
    $calendar->setSummary('ABC Fundraiser events');
    $new_calendar = $object['calendar']->calendars->insert($calendar);
    $calendar_id = $new_calendar->getId();
    $google_api_client->set('field_calendar_id', $calendar_id);
    $google_api_client->save();
  }
  else {
    $calendar_id = $calendar_id[0]['value'];
  }

  // Build event params.
  $event = new \Google_Service_Calendar_Event();
  // Start Date
  $start_date = new \Google_Service_Calendar_EventDateTime();
  $start_date->setDateTime(date('Y-m-d\TH:i:s', strtotime('25 december 2020 10 am')));
  $start_date->setTimeZone(drupal_get_user_timezone());

  // End Date
  $end_date = new \Google_Service_Calendar_EventDateTime();
  $end_date->setDateTime(date('Y-m-d\TH:i:s', strtotime('25 december 2020 10 pm')));
  $end_date->setTimeZone(drupal_get_user_timezone());

  $event->setStart($start_date);
  $event->setEnd($end_date);
  $event->setSummary('Christmas fundraiser');


  // Create event on calendar
  $event = $object['calendar']->events->insert($calendar_id, $event);
}
catch (Exception $e) {

  // ksm($e);
}

Above code creates a  ABC Fundraiser events calendar for every subscriber and if calendar exists then it creates a new event for Christmas fundraiser. 

Help improve this page

Page status: No known problems

You can: