CHAPTER 8

image

Adding JavaScript to Your Drupal Module

In this chapter you will once again be adding to the hello_world module you created earlier. This time you add some basic JavaScript to the simple page you programmatically created in Drupal. You’ll be using the basic JavaScript skills you just learned in Chapter 7. Being able to add JavaScript to your Drupal module will mean you’ll be able to add click events, hover events, and all the other JavaScript goodness to make your pages dynamic and user friendly without needing to reload the page unnecessarily to get more information for your users (reloading the page takes about two to four seconds or more if poorly designed, depending on the web page). Enabling users to get the information they need with a great graphical user interface with dynamic JavaScript is in high demand in the marketplace today. The market is actually starting to value JavaScript skills as high or higher than back-end database and PHP skills, but knowing all these skills is ideally still very necessary.

Image Note  The code for this Drupal module is on Github: https://github.com/barnettech/drupal8_book/tree/with_css_jss.

Adding JavaScript to Your Drupal Module

Following is the code for the hello_world module, but this time it contains the code to include some basic JavaScript. First, as always, is the info.yml file, which stays the same as in the first version of the module.

name:  Hello World
type:  module
description:  'A basic Drupal 8 Hello World Module.'
package:  Custom Modules
version:  1.0
core:  8.x

The hello_world.routing.yml file is also the same. Again, this file maps URLs (uniform resource locators) to what code to run and display on the page.

hello_world_settings:
  path:  '/hello/world'
  defaults:
    _controller:  'Drupalhello_worldControllerHelloWorldController::
myCallbackMethod'
    _title: 'Hello World'
  requirements:
    _permission: 'view hello world'

The hello_world.module file also remains the same.

<?php

/**
 * @file
 * A basic Drupal 8 Hello World Module.
 */

use DrupalCoreRoutingRouteMatchInterface;

/**
 * Implements hook_permission().
 */
function hello_world_permission() {
  $permissions = array(
    'view hello world' => array(
      'title' => t('View Hello World module'),
      'description' => t('View the Hello World module page.'),
    ),
  );
 return $permissions;

}

Note, however, that unlike the other files, the HelloWorldController.php file now will include lines to add JavaScript to the file. In Drupal 8 you add your JavaScript and CSS by attaching a library defined in a file called your_module.libraries.yml. Add a new file hello_world.libraries.yml or your_module_name.libraries.yml, with the following code:

hello-world:
  version: 1.x
  css:

    theme:
      css/hello_world.css: {}
js:
    js/hello_world.js: {}

This file and the code within define any CSS and JavaScript libraries you’ll use in your module, you’ll see how we include them in the highlighted code below in the HelloWorldController.php file. This file and the code within define any CSS and JavaScript libraries you’ll use in your module, you’ll see how we include them in the highlighted code below in the HelloWorldController.php file.

<?php
     /**
      * @file
      * Contains Drupalhello_worldHelloWorldController.
      */

     namespace Drupalhello_worldController;

     /**
      * Provides route responses for the hello world page example.
      */
     class HelloWorldController {
       /**
        * Returns a simple hello world page.
        *
        * @return array
        *   A very simple renderable array is returned.
        */
       public function myCallbackMethod() {
         $content = '
         <div class="myDiv">
           <div class="bg"></div>
             <div class="block-title">A basic Drupal page
             created programmatically, Hello World</div>

             Some random text to show off this transparent
             background ....
             Lorem ipsum dolor sit amet, consectetur adipiscing
             elit. Morbi nisi purus, gravida sit amet molestie
             et, facilisis vel nulla.
             Mauris faucibus augue eu quam feugiat at lacinia
             velit malesuada. Sed bibendum faucibus mattis.
             Maecenas quis ligula nibh, sit amet iaculis metus.
             Aenean lobortis massa ut nulla tristique eu
             vestibulum leo eleifend. Maecenas arcu lectus,
             facilisis in mattis sed, pretium et metus. Phasellus
             elementum, elit fringilla mollis sollicitudin ...
         </div>';
         $element = array(
           '#markup' => '<p><b>Saying Hello World in Drupal 8
           is cool!</b></p>' . $content,
           '#attached' => array(
             'library' => array(
               'hello_world/hello-world',
             ),
           ),
         );
         return $element;
       }
     }

Drupal comes with several jQuery UI (user interface) libraries installed, as it turns out, so you don’t need to download the draggable jQuery library, for instance. The draggable library allows you to click an element and drag it around the screen (a little like dragging a file you don’t want any more to the trash bin on your Windows or Mac desktop). Because this library comes with Drupal, you can just invoke the draggable library with the following line: $('.title').draggable();. The code in this JavaScript example makes all the elements with a title class draggable.

Image Note  You can find the additional libraries that come pre-installed with Drupal here: https://api.drupal.org/api/drupal/core!modules!system!system.module/function/system_library_info/8. You’ll have to wade through the code, but as you get to know the names of various jQuery libraries you’ll come to recognize them (ui.accordion, datepicker, droppable, progressbar, etc.).

The line you added allowed you to add your own JavaScript file, hello_world.js, and in it you write to the Firebug console and make any text wrapped in the title class draggable.

If you load the page now, you’ll be able to click the title and drag it around the screen. Instead of having to write out the whole path, you used the PHP: drupal_get_path('module', 'hello_world'). This code is a function to get the path to the module specified—in this case, hello_world—then you concatenate to that path, the path to your JavaScript file: /js/hello_world.js. Although could just write out the whole path, I find this method much easier.

The line you added in the preceding code looks in this module’s js folder for the hello_world.js file. Make sure to create the js folder within your module’s directory structure. Add the file hello_world.js, and add the following code to it:

(function($) {
    $(document).ready(function() {
      console.log('hello');
      $('.title').draggable();
    });
}(jQuery));

Image Note  The code used here is more standard JavaScript, and it will work in Drupal and outside Drupal. But there is another way to add JavaScript to Drupal. This particular method works only in Drupal (not in standard JavaScript files). For more information, visit www.drupal.org/node/304258.

You’re now finished with this exercise. Figure 8-1 shows what the web page looks like. If you have any questions about what folders to make, and so on, take a look at the code and directory structure for the module at Github: https://github.com/barnettech/drupal8_book/tree/with_css_js .

9781430264668_Fig08-01.jpg

Figure 8-1. The draggable jQuery library and a console.log message

Summary

In this chapter you learned how to add the JavaScript you worked with in the previous chapter to your custom-created Drupal module. JavaScript can bring your page alive, allowing you to respond to user clicks and other events on the page, without ever needing to slow down the user to reload the page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.133.138