Drupal 8 Development Cookbook

3.8 (11 reviews total)
By Matt Glaman
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Up and Running with Drupal 8

About this book

Began as a message board, Drupal today is open source software maintained and developed by a community of over 1,000,000 users and developers. Drupal is used by numerous local businesses to global corporations and diverse organizations all across the globe. With Drupal 8’s recent release and the exciting features it brings, this book will be your go-to guide to experimenting with all of these features through helpful recipes.

We’ll start by showing you how to customize and configure the Drupal environment as per your requirements, as well as how to install third-party libraries and then use them in the Drupal environment. Then we will move on to creating blocks and custom modules with the help of libraries. We will show you to use the latest mobile-first feature of Drupal 8, which will help you make your apps responsive across all the major platforms. This book will also show you how to incorporate multilingual facilities in your sites, use web services and third-party plugins with your applications from inside Drupal 8, and test and deploy your apps

Publication date:
March 2016
Publisher
Packt
Pages
370
ISBN
9781785881473

 

Chapter 1. Up and Running with Drupal 8

In this chapter we'll get familiar with Drupal 8 and cover:

  • Installing Drupal

  • Using a distribution

  • Installing modules and themes

  • Using multisites in Drupal 8

  • Tools for setting up an environment

  • Running Simpletest and PHPUnit

 

Introduction


This chapter will kick off with an introduction to getting a Drupal 8 site installed and running. We will walk through the interactive installer that most will be familiar with from previous versions of Drupal, and from the command line with Drush.

Once we have installed a standard Drupal 8 site, we will cover the basics of extending Drupal. We will discuss using distributions and installing contributed projects, such as modules and themes. We will also include uninstalling modules, as this has changed in Drupal 8.

The chapter will wrap up with recipes on how to set up a multisite installation in Drupal 8, getting a local development environment configured and running the available test suites.

 

Installing Drupal


Just like most things, there are many different methods for downloading Drupal and installing it. In this recipe, we will focus on downloading Drupal from https://www.drupal.org/ and setting it up on a basic Linux, Apache, MySQL, PHP (LAMP) server.

In this recipe, we will set-up the files for Drupal 8 and go through the installation process.

Getting ready

Before we start, you are going to need the below mentioned development environments that meet the new system requirements for Drupal 8:

  • Apache 2.0 (or higher) or Nginx 1.1 (or higher) web server.

  • PHP 5.5.9 or higher.

  • MySQL 5.5 or MariaDB 5.5.20 for your database. You will need a user with privileges to create databases, or a created database with a user that has privileges to make tables in that database.

  • Ability to upload or move files to the server!

  • Drupal also requires specific PHP extensions and configuration. Generally a default installation of PHP should suffice. See https://www.drupal.org/requirements/php for up to date requirements information.

    Note

    Drupal 8 ships with Symfony components. One of the new dependencies in Drupal 8, to support the Symfony routing system, is that the Drupal Clean URL functionality is required. If the server is using Apache, ensure that mod_rewrite is enabled. If the server is using Nginx, the ngx_http_rewrite_module must be enabled.

We will be downloading Drupal 8 and placing its files in your web server's document root. Generally, this is the /var/www folder. If you used a tool such as XAMPP, WAMP, or MAPP please consult the proper documentation to know your document root.

How to do it…

We need to follow the below steps to install Drupal 8:

  1. First we need to head to Drupal.org and download the latest release of Drupal 8.x! You can find the most recent and recommended release at the bottom of this page: https://www.drupal.org/project/drupal. Extract the archive and place the files to your document root as the folder drupal8:

  2. Open your browser and visit your web server, for example http://localhost/drupal8, to be taken to the Drupal installation wizard. You will land on the new multilingual options install screen. Select your language and click Save and continue.

  3. On the next screen keep the default Standard option for the installation profile. This will provide us with a standard configuration with the most commonly used modules installed.

  4. The next step will verify your system requirements. If your system does not have any reportable issues, the screen will be skipped.

    Note

    If you have requirement issues, the installer will report what the specific issues are. Nearly every requirement will link to a Drupal.org handbook page with solution steps.

  5. Enter the database information for Drupal. In most cases, you only need to supply the username, password, and database name and leave the other defaults. If your database does not exist, the installer will attempt to create the database:

    Note

    See the There's more section in for information on setting up your database and any possible users.

  6. Your Drupal 8 site will begin installing! When it is done installing the base modules, you will be taken to a site configuration screen.

  7. The configure site form provides the base configuration for your Drupal site. Enter your site name and the e-mail address for the site. The site email will be used to send administrative notifications and as the originating email for outgoing emails from the Drupal site. The form allows you to set regional information regarding the country and time zone of the site. Setting the timezone ensures time values display correctly.

  8. Fill in the site maintenance account information, also known as user 1, which acts in a similar way to root on Unix based systems. The site maintenance account is crucial. As stated, this acts as the first user and resembles the root user in Unix-based systems. In Drupal, the user with the user ID of 1 can bypass permission checks and have global access.

  9. Enter the site's regional information and whether the site should check for updates available for modules enabled and Drupal itself. By checking for updates automatically, your site will report anonymous usage statistics to Drupal.org along with providing a summary of your version status. You have the option to also opt-in for the site to email you notifications of new releases, including security releases.

  10. When satisfied click Save and continue and Congratulations, you installed Drupal!

How it works…

Drupal 8 supports a multilingual installation. When you visit the installer it reads the language code from the browser. With this language code, it will then select a supported language. If you choose a non-English installation the translation files will be automatically downloaded from https://localize.drupal.org/. Previous versions of Drupal did not support automated multilingual installations.

The installation profile instructs Drupal what modules to install by default. Contributed install profiles are termed distributions. The next recipe discusses distributions

When verifying requirements, Drupal is checking application versions and configurations. For example, if your server has the PHP Xdebug extension installed, the minimum max_nested_value must be 256 or else Drupal will not install.

There's more…

The Drupal installation process can be very straight forward, but there are a few items worth discussing.

Creating a database user and a database

In order to install Drupal you will need to have access to a database server and an existing (or ability to create) database (or the ability to create one). This process will depend on your server environment setup.

If you are working with a hosting provider, there is more than likely a web based control panel. This should allow you to create databases and users. Refer to your hosting's documentation.

If you are using phpMyAdmin on your server, often installed by MAMP, WAMP, and XAMPP, and have root access, you can create your databases and users.

  • Sign into phpMyAdmin as the root user

  • Click Add a new User from the bottom of the privileges page

  • Fill in the user's information

  • Select to create a database for the user with all privileges granted

  • You can now use that user's information to connect Drupal to your database

If you do not have a user interface but have command line access, you can set up your database and user using the MySQL command line. These instructions can be found in the core/INSTALL.mysql.txt files:

  1. Log into MySQL:

    $ mysql -u username -p
    
  2. Create the database you will use:

    $ CREATE DATABASE database CHARACTER SET utf8 COLLATE utf8_general_ci;
    
  3. Create a new user to access the database:

    $ CREATE USER [email protected] IDENTIFIED BY 'password';
    
  4. Grant the new user permissions on the database:

    $ GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES ON databasename.* TO 'username'@'localhost' IDENTIFIED BY 'password';
    

    Note

    If you are installing Drupal with a PostgresSQL or SQLite database, see the appropriate installation instructions, either INSTALL.pgsql.txt or INSTALL.sqlite.txt.

Database prefixes

Drupal, like other content management systems, allows you to prefix its database tables from the database set-up form. This prefix will be placed before table names to help make them unique. While not recommended this would allow multiple installations to share one database. Utilizing table prefixes can, however, provide some level of security through obscurity since the tables will not be their default names.

Downloading and installing with Drush

You may also install Drupal using the PHP command line tool Drush. Drush is a command line tool created by the Drupal community and must be installed. Drush is covered in Chapter 13, Drupal CLI.

The pm-download command will download packages from Drupal.org. The site-install command will allow you to specify an installation profile and other options for installing a Drupal site. The installation steps in this recipe could be run through Drush as:

$ cd /path/to/document/root
$ drush pm-download drupal-8 drupal8
$ cd drupal8
$ drush site-install standard –locale=en-US –-account-name=admin –-account-pass=admin –[email protected] –db-url=mysql://user:[email protected]/database

We use Drush to download the latest Drupal 8 and place it in a folder named drupal8. Then the site-install command instructs Drush to use the standard install profile, configure the maintenance account, and provides a database URI string so that Drupal can connect to its database.

Security updates

If you choose to disable the update options, you will have to check manually for module upgrades. While most upgrades are for bug fixes or features, some are for security updates. It is highly recommended that you subscribe to the Drupal security team's updates. These updates are available on Twitter at @drupalsecurity or the feeds on https://www.drupal.org/security.

See also

 

Using a distribution


A distribution is a contributed installation profile that is not provided by Drupal core. Why would you want to use a distribution? Distributions provide a specialized version of Drupal with specific feature sets. On Drupal.org when you download an installation profile it not only includes the profile and its modules but a version of Drupal core. Hence the name distribution. You can find a list of all Drupal distributions here https://www.drupal.org/project/project_distribution.

How to do it…

We will follow these steps to download a distribution to use as a customized version of Drupal 8:

  1. Download a distribution from Drupal.org. For this recipe let's use the Demo Framework provided by Acquia https://www.drupal.org/project/df.

  2. Select the recommended version for the 8.x branch.

  3. Extract the folder contents to your web server's document root. You'll notice there is Drupal core and, within the profiles folder, the installation profile's folder df.

  4. Install Drupal as you would normally, by visiting your Drupal site in your browser.

  5. Demo Framework declares itself as an exclusive profile. Distributions which declare this are automatically selected and assumed to be the default installation option.

    Note

    The exclusive flag was added with Drupal 7.22 to improve the experience of using a Drupal distribution http://drupal.org/node/1961012.

  6. Follow the installation instructions and you'll have installed the distribution!

How it works…

Installation profiles work by including additional modules that are part of the contributed project realm or custom modules. The profile will then define them as dependencies to be installed with Drupal. When you select an installation profile, you are instructing Drupal to install a set of modules on installation.

There's more…

Distributions provide a specialized version of Drupal with specific feature sets, but there are a few items worth discussing.

Makefiles

The current standard for generating a built distribution is the utilization of Drush and makefiles. Makefiles allow a user to define a specific version of Drupal core and other projects (themes, modules, third party libraries) that will make up a Drupal code base. It is not a dependency management workflow, like Composer, but is a build tool.

If you look at the Demo Framework's folder you will see drupal-org.make and drupal-org-core.make. These are parsed by the Drupal.org packager to compile the code base and package it as a .zip or .tar.gz, like the one you downloaded.

Installing with Drush

As shown in the first recipe, you can install a Drupal site through the Drush tool. You can instruct Drush to use a specific installation profile by providing it as the first argument. The following command would install the Drupal 8 site using the Demo Framework.

$ drush pm-download df
$ drush site-install df –db-url=mysql://user:[email protected]/database

See also…

 

Installing modules and themes


Drupal 8 provides more functionality out of the box than previous versions of Drupal – allowing you to do more with less. However, one of the more appealing aspects of Drupal is the ability to extend and customize.

In this recipe, we will download and enable the Honeypot module, and tell Drupal to use the Bootstrap theme. The Honeypot module provides honeypot and timestamp anti-spam measures on Drupal sites. This module helps protect forms from spam submissions. The Boostrap theme implements the Bootstrap front-end framework and supports using Bootswatch styles for theming your Drupal site.

Getting ready

If you have used Drupal previously, take note that the folder structure has changed. Modules, themes, and profiles are now placed in their respective folders in the root directory and no longer under sites/all. For more information about the developer experience change, see https://www.drupal.org/node/22336.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

How to do it…

Let's install modules and themes:

  1. Visit https://www.drupal.org/project/honeypot and download the latest 8.x release for Honeypot.

  2. Extract the archive and place the honeypot folder inside the modules folder inside of your Drupal core installation:

  3. In Drupal, log in and select the Extend option to access the list of available modules.

  4. Using the search text field, type in Honeypot. Check the checkbox and click Install.

  5. Once enabled, search for it again. Clicking on the module's description will expand the row and expose links to configure permissions and module settings:

  6. Visit https://www.drupal.org/project/bootstrap and download the latest 8.x release for Bootstrap.

  7. Extract the archive and place the bootstrap folder inside the themes folder inside your Drupal core installation.

  8. In Drupal, select the Appearance option to manage your Drupal themes.

  9. Scroll down the page and click Install and set as default under Bootstrap to enable and set the theme as default:

How it works…

The following outlines the procedure for installing a module or theme and how Drupal discovers these extensions.

Discovering modules and themes

Drupal scans specific folder locations to identify modules and themes defined by the .info.yml file in their directory. The following is the order in which projects will be discovered:

  • Respective core folder (modules, themes)

  • Current installed profile

  • The root modules or themes folder

  • The current site directory (default or current domain)

Module installation

By placing the module inside the root modules folder, we are allowing Drupal to discover the module and allow it to be installed. When a module is installed, Drupal will register its code with the system through the module_installer service. The service will check for required dependencies and prompt for them to be enabled if required. The configuration system will run any configuration definitions provided by the module on install. If there are conflicting configuration items, the module will not be installed.

Theme installation

A theme is installed through the theme_installer service and sets any default configuration by the theme along with rebuilding the theme registry. Setting a theme to default is a configuration change in system.theme.default to the theme's machine name (in the recipe it would be bootstrap.)

There's more…

The following outlines the procedure for installing a module or theme and some more information on it.

Installing a module with Drush

Modules can be downloaded and enabled through the command line using drush. The command to replicate the recipe would resemble:

$ drush pm-download honeypot
$ drush pm-enable honeypot

It will prompt you to confirm your action. If there were dependencies for the module, it would ask if you would like to enable those, too.

Uninstalling a module

One of the larger changes in Drupal 8 is the module disable and uninstall process. Previously modules were first disabled and then uninstalled once disabled. This left a confusing process which would disable its features, but not clean up any database schema changes. In Drupal 8 modules cannot just be disabled but must be uninstalled. This ensures that when a module is uninstalled it can be safely removed from the code base.

A module can only be uninstalled if it is not a dependency of another module or does not have a configuration item in use – such as a field type – which could disrupt the installation's integrity.

Note

With a standard installation, the Comment module cannot be uninstalled until you delete all Comment fields on the article content type. This is because the field type is in use.

See also…

  • Chapter 4, Extending Drupal, to learn about setting defaults on enabling a module

  • Chapter 9, Confiuration Management – Deploying in Drupal 8

 

Using multisites in Drupal 8


Drupal provides the ability to run multiple sites from one single Drupal code base instance. This feature is referred to as multisite. Each site has a separate database; however, projects stored in modules, profiles, and themes can be installed by all of the sites.

Site folders can also contain their own modules and themes. When provided, these can only be used by that one site.

The default folder is the default folder used if there is not a matching domain name.

Getting ready

If you are going to work with multisite functionality, you should have an understanding of how to setup virtual host configurations with your particular web server. In this recipe, we will use two subdomains under localhost called dev1 and dev2.

How to do it…

We will use multisites in Drupal 8 by two subdomains under localhost:

  1. Copy sites/example.sites.php to sites/sites.php.

  2. Create a dev1.localhost and a dev2.localhost folder inside of the sites folder.

  3. Copy the sites/default/default.settings.php file into dev1.localhost and dev2.localhost as settings.php in each respective folder:

  4. Visit dev1.localhost and run the installation wizard.

  5. Visit dev2.localhost and see that you still have the option to install a site!

How it works…

The sites.php must exist for multisite functionality to work. By default, you do not need to modify its contents. The sites.php file provides a way to map aliases to specific site folders. The file contains the documentation for using aliases.

The DrupalKernel class provides findSitePath and getSitePath to discover the site folder path. On Drupal's bootstrap this is initiated and reads the incoming HTTP host to load the proper settings.php file from the appropriate folder. The settings.php file is then loaded and parsed into a \Drupal\Core\Site\Settings instance. This allows Drupal to connect to the appropriate database.

There's more…

Let's understand the security concerns of using multisite:

Security concerns

There can be cause for concern if using multisite. Arbitrary PHP code executed on a Drupal site might be able to affect other sites sharing the same code base. Drupal 8 marked the removal of the PHP Filter module that allowed site administrators to use PHP code in the administrative interface. While this mitigates the various ways an administrator had easy access to run PHP through an interface it does not mitigate the risk wholesale. For example, the PHP Filter module is now a contributed project and could be installed.

 

Tools for setting up an environment


One of the initial hurdles to getting started with Drupal is a local development environment. This recipe will cover how to set up the DrupalVM project by Jeff Geerling. DrupalVM is a VirtualBox virtual machine run through Vagrant, provisioned and configured with Ansible. It will set up all of your services and build a Drupal installation for you.

Luckily you only need to have VirtualBox and Vagrant installed on your machine and DrupalVM works on Windows, Mac OS X, and Linux.

Getting ready

To get started, you will need to install the two dependencies required for DrupalVM:

How to do it…

Let's set up the DrupalVM project by Jeff Geerling. DrupalVM is a VirtualBox virtual machine run through Vagrant, provisioned and configured with Ansible:

  1. Download the DrupalVM archive from https://github.com/geerlingguy/drupal-vm/archive/master.zip.

  2. Extract the archive and place the project in your directory of choice.

  3. Copy example.drupal.make.yml to drupal.make.yml.

  4. Copy example.config.yml to config.yml

  5. Edit config.yml and modify the local_path setting to be the directory where you've placed the DrupalVM project. This will be synchronized into the virtual machine:

    vagrant_synced_folders:
      - local_path: /path/to/drupalvm
        destination: /var/www
      type: nfs
      create: true
  6. Open a terminal and navigate to the directory where you have placed the DrupalVM project.

  7. Enter the command vagrant up to tell Vagrant to build the virtual machine and begin the provisioning process.

  8. While this process is ongoing, modify your hosts file to provide easy access to the development site. Add the line 192.168.88.88 drupalvm.dev to your hosts file.

  9. Open your browser and access http://drupalvm.com/.

  10. Login to your Drupal site with the username admin and password admin.

How it works…

DrupalVM is a development project that utilizes the Vagrant tool to create a VirtualBox virtual machine. Vagrant is configured through the project's Vagrantfile. Vagrant then uses Ansible – an open source IT automation platform – to install Apache, PHP, MySQL, and other services on the virtual machine.

The config.yml file has been set up to provide a simple way to customize variables for the virtual machine and provisioning process. It also uses Drush to create and install a Drupal 8 site, or whatever components are specified in drupal.make.yml. This file is a Drush make file, which contains a definition for Drupal core by default and can be modified to include other contributed projects.

The vagrant up command tells Vagrant to either launch an existing virtual machine or create one anew in a headless manner. When Vagrant creates a new virtual machine it triggers the provisioning process. In this instance Ansible will read the provisioning/playbook.yml file and follow each step to create the final virtual machine. The only files needing to be modified, however, are the config.yml and drupal.make.yml files.

There's more…

The topic of automating and streamlining a local environment is quite popular right now with quite a few different options. If you are not comfortable with using Vagrant, there are a few other options that provide a server installation and Drupal.

Acquia Dev Desktop

Acquia Dev Desktop is developed by Acquia and can be found at https://docs.acquia.com/dev-desktop2. It is an automated environment installer for Windows and Mac. The Dev Desktop application allows you to create a regular Drupal installation or select from a distribution.

XAMPP + Bitnami

XAMPP – Apache + MySQL + PHP + Perl – is a cross platform environment installation. XAMPP is an open source project from Apache Friends. XAMPP has partnered with Bitnami to provide free all-in-one installations for common applications – including Drupal 8! You can download XAMPP at https://www.apachefriends.org/download.html.

Kalabox

Kalabox is developed by the Kalamuna group and intends to be a robust workflow solution for Drupal development. Kalabox is cross-platform compatible, allowing you to easily work on Windows machines. It is based for the command line and provides application binaries for you to install. You can learn more about Kalabox at http://www.kalamuna.com/products/kalabox/.

See also…

 

Running Simpletest and PHPUnit


Drupal 8 ships with two testing suites. Previously Drupal only supported Simpletest. Now there are PHPUnit tests as well. In the official change record, PHPUnit was added to provide testing without requiring a full Drupal bootstrap, which occurs with each Simpletest test. Read the change record here: https://www.drupal.org/node/2012184.

Getting ready

Currently core comes with Composer dependencies prepackaged and no extra steps need to be taken to run PHPUnit. This recipe will demonstrate how to run tests the same way that the QA testbot on Drupal.org does.

Note

The process of managing Composer dependencies may change, but is currently postponed due to Drupal.org's testing and packaging infrastructure. Read more here https://www.drupal.org/node/1475510.

How to do it…

  1. First enable the Simpletest module. Even though you might only want to run PHPUnit, this is a soft dependency for running the test runner script.

  2. Open a command line terminal and navigate to your Drupal installation directory and run the following to execute all available PHPUnit tests:

    php core/scripts/run-tests.sh PHPUnit
    
  3. Running Simpletest tests required executing the same script, however, instead of passing PHPUnit as the argument, you must define the url option and tests option:

    php core/scripts/run-tests.sh --url http://localhost --all
    
  4. Review test output!

How it works…

The run-tests.sh script has been shipped with Drupal since 2008, then named run-functional-tests.php. The command interacts with the other suites in Drupal to run all or specific tests and sets up other configuration items. We will highlight some of the useful options below:

  • --help: This displays the items covered in the following bullets

  • --list: This displays the available test groups that can be run

  • --url: This is required unless the Drupal site is accessible through http://localhost:80

  • --sqlite: This allows you to run Simpletest without having to have Drupal installed

  • --concurrency: This allows you to define how many tests run in parallel

There's more…

Is run-tests a shell script?

The run-tests.sh isn't actually a shell script. It is a PHP script which is why you must execute it with PHP. In fact, within core/scripts each file is a PHP script file meant to be executed from the command line. These scripts are not intended to be run through a web server which is one of the reasons for the .sh extension. There are issues with discovered PHP across platforms that prevent providing a shebang line to allow executing the file as a normal bash or bat script. For more info view this Drupal.org issue at https://www.drupal.org/node/655178.

Running Simpletest without Drupal installed

With Drupal 8, Simpletest can be run from SQLlite and no longer requires an installed database. This can be accomplished by passing the sqlite and dburl options to the run-tests.sh script. This requires the PHP SQLite extension to be installed.

Here is an example adapted from the DrupalCI test runner for Drupal core:

php core/scripts/run-tests.sh --sqlite /tmp/.ht.sqlite --die-on-fail --dburl sqlite://tmp/.ht.sqlite --all

Combined with the built in PHP webserver for debugging you can run Simpletest without a full-fledged environment.

Running specific tests

Each example thus far has used the all option to run every Simpletest available. There are various ways to run specific tests:

  • --module: This allows you to run all the tests of a specific module

  • --class: This runs a specific path, identified by a full namespace path

  • --file: This runs tests from a specified file

  • --directory: This run tests within a specified directory

    Note

    Previously in Drupal, tests were grouped inside module.test files, which is where the file option derives from. Drupal 8 utilizes the PSR-4 autoloading method and requires one class per file.

DrupalCI

With Drupal 8 came a new initiative to upgrade the testing infrastructure on Drupal.org. The outcome was DrupalCI. DrupalCI is open source and can be downloaded and run locally. The project page for DrupalCI is https://www.drupal.org/project/drupalci.

The test bot utilizes Docker and can be downloaded locally to run tests. The project ships with a Vagrant file to allow it to be run within a virtual machine or locally. Learn more on the testbot's project page: https://www.drupal.org/project/drupalci_testbot.

See also…

About the Author

  • Matt Glaman

    Matt Glaman is a Senior Drupal Consultant at Commerce Guys and co-maintainer of Drupal Commerce. He is an open source developer who has been working with Drupal since 2013. Since then, he has contributed to over 60 community project.

    Browse publications by this author

Latest Reviews

(11 reviews total)
Good starting point to develop new Drupal 8 modules and in general for D8 development
I waited one month but did not receive my book to Cyprus. Then I requested for another delivery to UK address which arrived by three days.
Good
Book Title
Access this book, plus 7,500 other titles for FREE
Access now