Jan 07 2015
Jan 07

Drupal 8 is the latest version of Drupal, a modern, PHP 5.4-boasting, REST-capable, object-oriented powerhouse. The concepts are still the same as the previous versions but the approach is now different. Drupal 8 comes with a modern Object Oriented Programming (OOP) approach to most parts of the system thanks to the use of the Symfony2 framework.

I took part in the Drupalcon in Amsterdam and I enjoyed a number of really interesting talks about Drupal 8, among those ‘Drupal 8: The Crash Course’ realized and presented by Larry Garfield. In this post the idea is to recap few key points of his talk as I think they are important to fully understand the basics of this new Drupal version. In case you are interested you can also watch the full talk.

How do I define a module?

In Drupal 8 to define a module we need only a YAML (.info.yml) file:

/modules/d8_example_module/d8_example_module.info.yml

name: D8 Test Module
description: D8 Test Module
type: module
core: 8.x
package: Custom

In Drupal 8 the .module file is not required anymore, so with only the .info.yml file the module is ready to be enabled.

How do I make a page?

Start creating a controller extending the ControllerBase class and return the output of the page:

/modules/d8_example_module/src/Controller/D8ExampleModuleController.php

namespace Drupal\d8_example_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class D8ExampleModuleController extends ControllerBase {

  public function test_page($from, $to) {
    $message = $this->t('%from to %to', [
      '%from' => $from,
      '%to' => $to,
    ]);

    return ['#markup' => $message];
  }
}

Once this is done, within the .routing.yml file we can define the path, the controller, the title and the permissions:

/modules/d8_example_module/d8_example_module.routing.yml

d8_example_module.test_page:
  path: '/test-page/{from}/{to}'
  defaults:
    _controller: 'Drupal\d8_example_module\Controller\D8ExampleModuleController::test_page'
    _title: 'Test Page!'
  requirements:
    _permission: 'access content'

How do I make content themeable?

We still have the hook_theme() function to define our theme:

/modules/d8_example_module/d8_example_module.module

/**
 * Implements hook_theme().
 */
function d8_example_module_theme() {
  $theme['d8_example_module_page_theme'] = [
    'variables' => ['from' => NULL, 'to' => NULL],
    'template' => 'd8-theme-page',
  ];

  return $theme;
}

For the template page Drupal 8 uses Twig, a third-party template language used by many PHP projects. For more info about Twig have a look at Twig in Drupal 8. One of the cool parts of Twig is that we can do string translation directly in the template file:

/modules/d8_example_module/template/d8-theme-page.html.twig

<section>
  {% trans %}
    <strong>{{ from }}</strong> to <em>{{ to }}</em>
  {% endtrans %}
</section>

And then we assign the theme to the page:

/modules/d8_example_module/src/Controller/D8ExampleModuleController.php

namespace Drupal\d8_example_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class D8ExampleModuleController extends ControllerBase {

  public function test_page($from, $to) {
    return [
      '#theme' => 'd8_example_module_page_theme',
      '#from' => $from,
      '#to' => $to,
    ];
  }
}

How do I define a variable?

Drupal 8 has a whole new configuration system that uses human-readable YAML (.yml) text files to store configuration items. For more info have a look at Managing configuration in Drupal 8.

We define variables in config/install/*.settings.yml:

/modules/d8_example_module/config/install/d8_example_module.settings.yml

default_count: 3

The variables will be stored in the database during the installation of the module. We define the schema for the variables in config/schema/*.settings.yml:

/modules/d8_example_module/config/schema/d8_example_module.settings.yml

d8_example_module.settings:
  type: mapping
  label: 'D8 Example Module settings'
  mapping:
    default_count:
      type: integer
      label: 'Default count'

How do I make a form?

To create a form we extend a ConfigFormBase class:

/modules/d8_example_module/src/Form/TestForm.php

namespace Drupal\d8_example_module\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class TestForm extends ConfigFormBase {
  public function getFormId() {
    return 'test_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('d8_example_module.settings');

    $form['default_count'] = [
      '#type' => 'number',
      '#title' => $this->t('Default count'),
      '#default_value' => $config->get('default_count'),
    ];
    return parent::buildForm($form, $form_state);
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config('d8_example_module.settings');
    $config->set('default_count', $form_state->getValue('default_count'));
    $config->save();
    parent::submitForm($form, $form_state);
  }
}

Then within the .routing.yml file we can define the path, the form, the title and the permissions:

/modules/d8_example_module/d8_example_module.routing.yml

d8_example_module.test_form:
  path: /admin/config/system/test-form
  defaults:
    _form: 'Drupal\d8_example_module\Form\TestForm'
    _title: 'Test Form'
  requirements:
    _permission: 'configure_form'

We use another YAML file (.permissions.yml) to define permissions:

/modules/d8_example_module/d8_example_module.permissions.yml

'configure_form':
  title: 'Access to Test Form'
  description: 'Set the Default Count variable'

We also use another YAML file (.links.menu.yml) to define menu links:

/modules/d8_example_module/d8_example_module.links.menu.yml

d8_example_module.test_form:
  title: 'Test Form'
  description: 'Set the Default Count variable'
  route_name: d8_example_module.test_form
  parent: system.admin_config_system

How do I make a block?

To create a block we extend a ConfigFormBase class:

/modules/d8_example_module/src/Plugin/Block/TestBlock.php

namespace Drupal\d8_example_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Test Block.
 *
 * @Block(
 *   id = "test_block",
 *   admin_label = @Translation("Test Block"),
 *   category = @Translation("System")
 * )
 */
class TestBlock extends BlockBase {

  public function build() {
    return [
      '#markup' => $this->t('Block content...'),
    ];
  }
}

In this way the block is ready to be configured in the CMS (/admin/structure/block). Here is an example of a more complex block:

namespace Drupal\d8_example_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Test Block.
 *
 * @Block(
 *   id = "test_block",
 *   admin_label = @Translation("Test Block"),
 *   category = @Translation("System")
 * )
 */
class TestBlock extends BlockBase {

  public function defaultConfiguration() {
    return ['enabled' => 1];
  }

  public function blockForm($form, FormStateInterface $form_state) {
    $form['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Configuration enabled'),
      '#default_value' => $this->configuration['enabled'],
    ];

    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['enabled'] = (bool)$form_state->getValue('enabled');
  }

  public function build() {
    if ($this->configuration['enabled']) {
      $message = $this->t('Configuration enabled');
    }
    else {
      $message = $this->t('Configuration disabled');
    }
    return [
      '#markup' => $message,
    ];
  }
}

Structure of a module

The structure of a module should look like the example module d8_example_module:

d8_example_module/
 |
 |- config/
   |
   |- install/
     |
     |- d8_example_module.setting.yaml
     |
     |- schema/
       |
       |- d8_example_module.settings.yaml
 |
 |- src/
   |
   |- Controller/
     |
     |- D8ExampleModuleController.php
   |
   |- Form/
     |
     |- TestForm.php
   |
   |- Plugin/
     |
     |- Block/
       |
       |- TestBlock.php
 |
 |- templates/
   |
   |- d8-theme-page.html.twig
 |
 |- d8_example_module.info.yml
 |
 |- d8_example_module.links.menu.yml
 |
 |- d8_example_module.module
 |
 |- d8_example_module.permissions.yml
 |
 |- d8_example_module.routing.yml

Drupal 8 in 2 steps: Extend a base Class or implement an Interface and tell Drupal about it.

Download the example module

Updates:

  • 19th January 2015
    • The code in this post has been updated to reflect changes in Drupal 8 Beta 4. Thanks to Geoff Lawrence for the updates to the example repo.
Oct 22 2014
Oct 22

Along with Malcolm and other colleagues from the Capgemini Drupal team, I attended the recent Drupalcon in Amsterdam. And as well as admiring the Dutch attitude to cycling and its integration in the city (btw London, blue paint on the road != a cycle superhighway), we also caught up on the state of Drupal and its future. So here a few reflections from Drupalcon Amsterdam.

Drupal In The Enterprise - A Key Component In The Wider Web

I’ve been to a few Drupalcons now, and compared to previous years, use of Drupal in the enterprise (or more generally at scale) seems much more commonplace. Dries Buytaert’s (Drupal founder) keynotes have made reference to Drupal’s ability to integrate with other systems as a key strength, and in these types of projects, Drupal is not used as the all-in-one solution that maybe was more commonplace a few years ago.

Partly this is also due to the way the web has moved far beyond the idea of ‘a thing you use on your desktop computer’, and Drupal has shown itself to be adaptable to this. For example, the idea of Headless Drupal was a well covered topic this year. Of course, previous ‘cons have had talks on uses of Drupal with other technologies (e.g. node.js talk from London 2011) but whereas it seemed more an interesting edge case then, now there are many successful real-world projects adopting these ideas.

The Sessions

Based on my not-entirely-comprehensive memory of the subset of sessions I attended from past Drupalcons, this year there seemed to be many more talks which could have easily been at a frontend or PHP specific conference. Drupal 8’s use of Symfony 2 components and shift to making use of components Proudly Found Elsewhere is part of this.

A few talks that those of us who attended would recommend (not an exhaustive list). I won’t go into too much detail (that’s all in the slides and the video) but these are worth checking out.

Automated Frontend Testing

The types of frontend testing which can be automated, covering performance (Phantomas), CSS (Wraith) and end-to-end (CasperJS) and integrating this into your build workflow. Slides Video

Models & Service Layers; Hemoglobin & Hobgoblins

I think the PHP track is a welcome addition to Drupalcon. When developing custom functionality on projects here at Capgemini, we often write the business models and logic as separate classes to Drupal which are then ‘glued’ via hooks which implement those classes. That kind of separation has advantages with portability, testability and some amount of simplification in that Drupal isn’t a dependency. Video

Cory Doctorow’s Keynote

Very interesting talk on how open-source is (in some ways) critical to our individual freedom in the modern world. In an age where “a modern house is a computer that you co-inhabit”, if a system went down - or arguably worse, were controlled by overzealous authorities - it can become uninhabitable. What do we do in this case? Is the Apple iTunes/U2 debacle merely the thin end of the wedge? Interesting viewing for anyone who contributes or uses open source. Video

Drupal 8 And The Future

As Drupal 8 entered beta during the conference, it was an opportunity to check out the changes. The plugin system for extending functionality looks interesting. In Drupal projects at Capgemini we have adopted approaches such as abstracting business logic and objects into standalone libraries and classes, called from hooks and callbacks where we need integration with Drupal. This approach allows us easier unit-testing and portability of classes. D8’s plugin system looks like a good way of achieving those advantages while implementing a Drupal API.

Having spent a lot of time on projects wrestling with the various methods of deploying and updating configuration, the CMI (Configuration Management Initiative), which imports and exports YAML files to update and dump site configuration is a very welcome addition.

In the frontend, I’m looking forward to using the Twig templating. The idea of having cleaner PHP-free templates yet still with the flexibility to have filters and basic logic is going to help improve separation between the theme and module layer. It’ll be new to me (as will other things) but as with other components, they have been successfully used in other PHP projects so there is documentation and examples already out there. There are some smaller changes too - removing drupal.js’s dependency on jQuery (thereby gently encouraging use of native JS), updating the versions of included libraries (and committing to keeping them up-to-date during D8’s lifetime) and including no JavaScript by default are good steps to optimising the frontend.

Where things may be more challenging is the APIs which have both new object-oriented components and retain the hook and callback system in some combination (for example, declaring widgets via hook_element_info). To take an example from a core module, the file module’s managed_file widget functionality is spread across a number of callbacks as well as its own FileWidget class. It’s not the most straightforward development flow to follow. Where this has some advantages is that existing modules will not need a complete OO rewrite just to be compatible with D8 - a module author could do a simple port at first before rewriting to take advantage of the new APIs. But some care is need to ensure that the advantages of encapsulation, increased unit-testability and extendability that the OO patterns introduce are not compromised by dependencies on a particular hook or callback.

Taking The Leap

Finally, as Drupal 8 progressed from alpha to beta during Amsterdam Drupalcon, it does seem now that it can be realistically considered for projects coming up on the horizon. Obviously there will a lot more work going into the project to fix bugs and improve performance and so forth. But now the major API decisions and changes have been made. But with this iteration of Drupal incorporating many more features from the contrib world (Views, WYSIWYG, etc) and PHP (Symfony2 components), it looks to be a healthy position for use when that 8.0.0 finally lands.

Oct 20 2014
Oct 20

Recently 10 members of the Drupal development team at Capgemini went to Drupalcon Amsterdam. Having been to two Drupalcons before, I more or less knew what to expect, but something I hadn’t previously given much thought to was how big an event it is. Compared to most other web conferences, it’s a beast. For me personally, I wonder if it’s getting too big and too impersonal, and I think that I’ll be more interested in going to smaller events.

Some of the more interesting sessions for me were the BoFs - in particular a discussion of open source training material and apprenticeships provided a lot of food for thought, and hopefully we can get involved at some level. Capgemini already does a lot of work getting graduates and apprentices into our engineering practice, and with such a big Drupal team, I hope we can benefit from and contribute to the Open Drupal initiative in 2015.

Whenever I go to an event, I come back with a to-do list, and this was no exception. I’ll definitely be digging further into CasperJS following Chris Ruppel’s session on Automated Frontend Testing. I was also very interested to hear about the way that Lullabot spin up test environments for pull requests - it will be good to investigate the feasibility of incorporating this into our workflow.

The other talk that stood out for me was John Albin Wilkins on Styleguide-Driven Development. For a long time, I’ve had a bee in my bonnet about the value of component libraries over Photoshop comps, and it was good to be reminded that I’m not alone. In an interesting session, John outlined an approach to integrating component-based design and automated style guides to agile development projects.

It’s been said many times before, but it’s worth remembering that all too often, people are still thinking in terms of pages, rather than systems.

In the context of the work that we do, this is even more important. We’re a large development team, building CMS-driven sites for large corporate clients, where the design is done by a team working for another company. We’ve made some inroads into building a more collaborative process, but it’s still too easy to end up with the designers throwing things over the wall to the developers. Very often the designer isn’t closely involved during the build phase, and design tweaks are agreed between the client and the developer without the opportunity to go back to get the designer’s opinion.

This is the whole point of living style guides - component libraries that stay in sync with the code as it evolves. As Shay Howe has discussed, component libraries help everyone on the project.

Designers are reminded of the visual language of the project, and it’s easier for them to see when they’re about to reinvent the wheel.

Style guides help developers by defining and documenting standards, and make it easier to dig in and find the way you solved some problem six months ago.

The projects we work on are large and complex, with a long lifecycle, and as developers we need to value maintainability of the front end code. Part of John’s approach to this was his class-naming convention. Having seen Jonathan Snook present on SMACSS I’d thought it was interesting, but to a certain extent it felt like a fancy name for something that was basically common sense. John’s presentation brought the concept to life well, and persuaded me that there’s more to it than that, with an impressive display of flower power.

The other interesting aspect was splitting up SASS files into components, and using KSS to create the style guide - this is something I definitely intend to do on my next project.

Modularity makes sense - it’s how the back-end is going, it’s how Javascript is going, so why shouldn’t design and CSS go the same way?

UPDATED 3rd December 2014: Unfortunately we got Chris Ruppel’s name wrong in the original version of this post, calling him “Dave Rupl”. Sorry Chris.

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web