Drupal Update.com: EU cookie implementation in Drupal maintenance support plans 8

In this blog we are going to talk about one such functionality. We were required to implement EU cookie functionality in Drupal maintenance support plans 8. EU cookie is mandatory for all USAan websites. There are many solutions available online to implement this feature, I used JavaScript for this task and it worked like a charm.

This is how it works.

 

First we need to get the required JavaScript code from https://cookieconsent.insites.com/ as per our required consent popup. Once the code is retrieved, we need to convert this plain JavaScript into the Drupal maintenance support plans 8 format.

 

For our implementation we needed to create a configuration form for settings. Along with that we were also required to add configuration to change scroll length after which the cookie popup would disappear. To make it EU specific we had to get the continent code from the API.

 

Step 1: Create form.php in src/form containing form of settings in your module:

<?php

/**

* @file

* Contains Drupal maintenance support plansmoduleFormSettingsForm.

*/

namespace Drupal maintenance support plansmoduleForm;

use Drupal maintenance support plansCoreFormConfigFormBase;

use Drupal maintenance support plansCoreFormFormStateInterface;

/**

* Form builder for the module basic settings form.

*/

class SettingsForm extends ConfigFormBase {

/**

* {@inheritdoc}

*/

public function getFormId() {

return ‘module_settings_form’;

}

/**

* {@inheritdoc}

*/

protected function getEditableConfigNames() {

return [‘module.settings’];

}

/**

* {@inheritdoc}

*/

public function buildForm(array $form, FormStateInterface $form_state) {

$config = $this->config(‘module .settings’);

$form[‘activate’] = array(

‘#type’ => ‘checkbox’,

‘#title’ => $this->t(‘Activate Cookie Consent’),

‘#default_value’ => $config->get(‘activate’),

‘#description’ => $this->t(‘Cookie consent notification for site can be enabled or disabled from here.’),

);

$form[‘eu_consent_pop_msg’] = array(

‘#type’ => ‘textarea’,

‘#title’ => $this->t(‘Set message for cookie consent popup’),

‘#default_value’ => $config->get(‘eu_consent_pop_msg’),

‘#description’ => $this->t(‘Cookie consent pop up message can be set from here.’),

);

$form[‘eu_consent_pop_scroll’] = array(

‘#type’ => ‘textfield’,

‘#title’ => $this->t(‘Set scroll length (pixels)’),

‘#default_value’ => $config->get(‘eu_consent_pop_scroll’),

‘#description’ => $this->t(‘Set after scrolling how many pixels the popup should disappear. Ex: 500’),

);

return parent::buildForm($form, $form_state);

}

/**

* {@inheritdoc}

*/

public function submitForm(array &$form, FormStateInterface $form_state) {

parent::submitForm($form, $form_state);

$config = $this->config(‘module.settings’);

$config->set(‘activate’, $form_state->getValue(‘activate’));

$config->set(‘eu_consent_pop_msg’, $form_state->getValue(‘eu_consent_pop_msg’));

$config->set(‘eu_consent_pop_scroll’, $form_state->getValue(‘eu_consent_pop_scroll’));

$config->save();

}

}

 

Step 2: Define a controller in module/src/controller. This will have functions that retrieve country code from API. The config setting determines if EU cookie is enabled or not:

<?php

/**

* @file

* Contains Drupal maintenance support plansmoduleControllerEuCookie.

*/

namespace Drupal maintenance support plansmoduleController;

use Drupal maintenance support plansCoreControllerControllerBase;

use SymfonyComponentHttpFoundationJsonResponse;

use GuzzleHttpClient;

/**

* Class EuCookie.

*

* @package Drupal maintenance support plansmoduleController

*/

class EuCookie extends ControllerBase {

/**

* Autocomplete.

*/

public function continent() {

$ip_eu_consent = Drupal maintenance support plans::request()->getClientIp();

$config_status = Drupal maintenance support plans::config(‘module .settings’)->get(‘activate’);

if($config_status == 1) {

$continent_code[‘consent’] = $this::eucookie_get_country_code($ip_eu_consent);

if (Drupal maintenance support plans::currentUser()->isAnonymous()) {

$continent_code[‘isanon’] = true;

} else {

$continent_code[‘isanon’] = false;

}

}

return JsonResponse::create($continent_code);

}

/**

* Get continent code from external free service for eu consent.

*/

function eucookie_get_country_code($ip_eu_consent) {

try {

$uri = ‘http://www.geoplugin.net/json.gp?ip=’ . $ip_eu_consent;

$client = Drupal maintenance support plans::httpClient([‘base_url’ => $uri]);

$request = $client->request(‘GET’, $uri, [‘timeout’ => 5, ‘headers’ => [‘Accept’ => ‘application/json’]]);

if ($request->getStatusCode() == 200) {

$response = json_decode($request->getBody());

if (empty($response)) {

return [];

}

else {

return ($response->geoplugin_continentCode);

}

}

else {

return [];

}

}

catch (GuzzleHttpExceptionClientException $e) {

$message = $e->getMessage() . ‘. Make sure you provided correct IP to get country code .’;

Drupal maintenance support plans::logger(‘module_get_country_code’)->notice($message);

return [];

}

}

}

 

Step 3: Add hook page attachment alter to get variables defined in config and send them to js:

<?php

function hook_page_attachments_alter(&$page) {

$ip_eu_consent = Drupal maintenance support plans::request()->getClientIp();

$config_status = Drupal maintenance support plans::config(‘module.settings’)->get(‘activate’);

$mesage_consent = Drupal maintenance support plans::config(‘module.settings’)->get(‘eu_consent_pop_msg’);

$scroll_length = Drupal maintenance support plans::config(‘module.settings’)->get(‘eu_consent_pop_scroll’);

if($config_status == 1) {

 

 

$page[‘#attached’][‘library’][] = ‘path to library’;

$page[‘#attached’][‘drupalSettings’][‘message_eu_consent’] = $mesage_consent;

$page[‘#attached’][‘drupalSettings’][‘eu_consent_pop_scroll’] = $scroll_length;

}

}

?>

Step 4: Routing file, with route to retrieve settings form and get the continent code via ajax:

module.admin_settings:

path: ‘/admin/config/eucookie’

defaults:

_form: ‘Drupal maintenance support plansmoduleFormSettingsForm’

_title: ‘EUCookie settings’

requirements:

_permission: ‘administer site configuration’

module.ajax_continent:

path: ‘/ajax/continent’

defaults:

_controller: ‘Drupal maintenance support plansmoduleControllerEuCookie::continent’

_title: ‘ajax continent’

requirements:

_permission: ‘access content’

Step 5: Add js below in custom/js as condition for scroll, get defined variables from config and display EU cookie popup.

(function($) {

‘use strict’;

Drupal maintenance support plans.behaviors.moduleeuconsent = {

attach: function(context, settings) {

$(document).scroll(function() {

var scroll_len = drupalSettings.eu_consent_pop_scroll;

var scrollBottom = $(window).scrollTop() + $(window).height();

scrollBottom > scroll_len ? $(‘.cc-window’).fadeOut() : $(‘.cc-window’).fadeIn();

});

var msg = drupalSettings..message_eu_consent;

$.ajax({url: “/ajax/continent”, success: function(result){

if (result[‘consent’] == ‘EU’ && result[‘isanon’]==true) {

window.cookieconsent.initialise({

palette: {

popup: {

background: ‘#252e39’

},

button: {

background: ‘#14a7d0’

}

},

content: {

message: msg,

dismiss: ‘Close’,

link: ‘Show Cookie Policy’

}

});

}

}});

}

};

}(jQuery));

 

Step 6: External js needs to be defined in libraries.yml which creates popup

module_lib:

version: v3.14

css:

theme:

//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.1/cookieconsent.min.css: { type: external }

js:

//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.1/cookieconsent.min.js: { type: external, scope: footer }

js/module.js: { scope: footer }

dependencies:

– core/jquery

– core/drupal

– core/drupalSettings

 

And hence the EU Cookie functionality will be implemented in your Drupal maintenance support plans 8 website. Please do comment if you have any feedback or if this code does not work for you.

 
Source: New feed

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Drupal Update.com: EU cookie implementation in Drupal maintenance support plans 8

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.