Skip to Content

Newsfeeds

Better Module Dependencies

New Drupal Modules - 21 April 2016 - 1:21am

This module enhances modules list page and comes in handy if you have a large amount of modules installed on your Drupal website. In cases like that each module's requirements list becomes larger and larger, therefore it becomes very hard to read and work with module dependencies. So what this module actually does is making any module dependency clickable.

Categories: Drupal

Media entity document

New Drupal Modules - 21 April 2016 - 12:56am

Local document integration for Media entity module.

Categories: Drupal

Vardot: Project Manager’s Guide to Breaking Down a Drupal Site for Incremental Delivery

Planet Drupal - 21 April 2016 - 12:39am
How to, Resources Read time: 8 minutes

TL;DR. Jump to the free template: Standard Drupal Work Breakdown Structure Template.

Building a new site on a content management system has always been a tricky project to manage for a project manager, when compared to building a site on a framework or from scratch. That is because you are dealing with building blocks that are provided as a standard from the CMS. A project manager should have the necessary knowledge of the CMS’s building blocks to be able to manage a successful project.

Put this in context of today’s Scrum management approach (an agile way to manage a project, usually software development) and you’ll end up with a puzzled project manager with several questions such as:

  1. What can my team deliver in the first sprint?

  2. How can I breakdown the project’s deliveries into sprints?

  3. What expectations of deliverables should I set with my project’s stakeholders (product owner, business owner, client)

  4. When do I deliver the homepage for my stakeholder to look at?

  5. Are we supposed to deliver on page by page basis?

 

Drupal disrupts the “page” methodology that we are used to thinking of. One naturally tends to think of a website as a folder, with sub-folders, and pages (.html) inside those folders. That’s the 90s. We’re in 2016. Drupal is a database-driven CMS that takes a content-first (or content-out) approach of building rich web experiences, instead of a page-first approach. See “Drupal is content first, and that's good” and “A Richer Canvas”.

   

Due to this approach of how Drupal works, we at Vardot have came up with a framework of planning the phases of building a Drupal site, to lead to an incremental development that can be broken down and fit into Scrum sprints. This will apply to almost all Drupal projects.

This standard way we'll call: The Standard Drupal Work Breakdown Structure

 

Why Do I Need a Breakdown of Work for Planning My Drupal Site?

Because this what project managers do. I have seen in the many Drupal projects that I was part of, that project managers (and/or coordinators) must understand how Drupal works, how the development process goes, and how do we get 80% of the site done in 20% of the time.

A work breakdown structure will help you (as a project manager) to understand how a Drupal site is built. It will also ease the process for getting high quality incremental deliveries to fit in your sprints. In this post, I will walk you through the high-level breakdown for any Drupal site.

 

Most importantly, the goals and outcomes of a breakdown are for you to understand and communicate to your project’s stakeholders your timeline of deliveries, and to be able to fit these deliveries into sprints.

To summarize, these goals are:

  1. Breakdown of deliverables. Define needed outcomes of initial sprints

  2. Provide a holistic view and analysis of the site’s functionality and its building blocks

  3. Remember, we are building a CMS, not a website. Therefore you need to architect your “CMS solution”, and not your “website solution”

 

Let’s Start With The How

Now we enforce these goals by implementing the The Standard Drupal Work Breakdown Structure, that will fit for almost all of the Drupal projects you will work with.

These phases will be divided into:

  1. Initialization Work Breakdown Structure: This phase is the cornerstone phase for starting right, it’s most probably a typical standard way that you should do in every project.

  2. Project’s Epics Work Breakdown Structure: Careful analysis of the site’s components and how it will be developed in the CMS will be implemented here.

  3. Finalization Work Breakdown Structure: This is the ending phase, where you make sure your site is ready for launch. Final preparations, tuning, and tweaks are carried out in this phase to prepare for your big day.

Note that you will be able to deliver something for your stakeholders to look at, in the “Initialization” phase.

This breakdown must happen after high-fidelity wireframes are done, or if you have the full visual mockups of a Drupal site done for your key pages.

It’s important to note that the visual mockups should use and adhere to Drupal’s design language and patterns. But what is Drupal’s design language and patterns? That’s for another article to discuss.

Now that we have designs handed to us with a clear communication of how the new website will look like. We are ready to breakdown our Drupal site for a successful delivery.

 

The Work Breakdown

Disclaimer: the terminology that I’m using below to name some components that make up your site is not an “official Drupal language”. No worries if you stick with the same terminology or use your own names, what really matters is just the breakdown structure.

So I’m categorizing what makes a (Drupal) site into six components:

  1. Wrapping components: Header and Footer.
    These are the components that provide your site with a wrapper for all your next components. Start with these as soon as you install Drupal; it will help you get through the easy stuff that makes up your site.
     
  2. Global components: Page title, Breadcrumbs, Tabs (a.k.a menu local tasks), System messages ...etc.
    These are the components that make up the uniformity of a CMS. These are your next target.
     
  3. Site-unified components: Ad blocks, Newsletter subscribe block, Social media feeds or “follow us” blocks, Static “about us” block ..etc.
    These are the components that most likely appear in the same style across multiple pages in the site.
     
  4. Full nodes and entities: Your “Full content” node/user/entity pages.
    Getting back to “content-out” approach, always start with the full-node or entities completion.
     
  5. Views, view modes, and other content: Views of recent content, Featured content, Node pages, Feeds integration, CRM integration, Single Sign On integration, ...etc.
    This is the major work; components that define your site.
     
  6. The annoying 20% of the site: This is where the built 80% of your site gets the final hidden work, iterative tweaking and enhancements to your site, whether it is requested by your QA team, the client, or the product owner.

In light of this breakdown of CMS’s categories, here’s an animated illustration of how a site can be made possible when following the flow of development based on the components above:

In this order, you can now think of a Drupal site to be developed according the following steps:

Initialization Work Breakdown Structure

  1. Delivering “1. Wrapping components

    1. Install Drupal (or the distribution you want to use), setup the development environment ..etc.

    2. Populate the things that make up the “Wrapping components”: Menus, logo, search ..etc.

    3. Create your theme, and theme the “Wrapping components”

  2. Delivering “2. Global components

    1. Just populate then and theme them.

  3. Delivering “3. Site-unified components

    1. Create and populate the things that make up your “site-unified components”

    2. Theme them

Project’s Epics Work Breakdown Structure

  1. Outline your content types starting from the “Full node” view modes. Identify other view modes for your content types. Start creating those into “Tasks”

  2. Do the same for other Drupal entities: Entities, Files, Comments ..etc.

  3. Deliver “4. Full nodes and entities

  4. Deliver “5. Views, view modes, and other content

  5. Deliver “6. The annoying 20% of the site

Finalization Work Breakdown Structure

  1. Final overall testing

  2. SEO, Printability, Performance, Security, and Accessibility tuning and configuration

  3. Your pre-launch checklists

  4. Go live!

 

FREEBIE: The Standard Drupal Work Breakdown Structure Template

Our Standard Drupal Work Breakdown Structure Template provides an outline of these phases and detailed tasks to be done that we use for every Drupal project. This template is made to be easily imported to JIRA. It contains:

  • a master sheet that aggregates the standard epics, tasks and stories to be easily imported to JIRA.

  • a sheet for defining the project’s own epics and stories

  • the standard Initialization and Finalization work breakdown structure that must not be missed for any project

All of this helps to reduce discrepancies in developing each project, not to miss important tasks and also allows our team to deliver a project fast, and incrementally (delivering in the first week of development).

Using The Template

The template is a Google Spreadsheet that you can easily clone and customize. To do so:

  1. Open the sheet and copy it to make it yours.

  2. Feel free to edit the sheet to make it your own. There are some instructions on how to use the sheet to make it yours.

  3. Follow the instructions on what to edit. We recommend that the “Initialization WBS” and the “Finalization WBS” stay intact (you can edit them once to your standard flow, then replicate for all projects).

  4. For each project, you will want to copy your template to customize the “Project’s Epics WBS” as per the project. The template has some samples for you to consider.

  5. Once done, export the “Master WBS” sheet to CSV. So you can import to your JIRA project.

  6. Map fields to your JIRA. See sample [image to illustrate mapping]

  7. That’s it!

 

Conclusion

Two things have helped us to standardize our work process when developing a Drupal site, and insure consistency and quality:

  1. Starting a project by finishing up components-first approach, not page-first approach.

  2. Documenting our recurring tasks and processes in a Template that uses this approach. This template makes applying this process easier for you.

Next time you start a Drupal project, consider this approach and let us know how this would help you in the comments section below.

Note: This does not depend on a specific Drupal version, this methodology works with Drupal 6, 7 or 8. It depends on Drupal’s conceptual building approach.

Tags:  Drupal Planet drupal 8 Project Management Drupal Templates Title:  Project Manager’s Guide to Breaking Down a Drupal Site for Incremental Delivery
Categories: Drupal

Drupal Console: Drupal Console alpha1 is now available

Planet Drupal - 21 April 2016 - 12:24am
We are so excited to announce the first Alpha release of Drupal Console. Almost three years of working on this project and after 84 releases, almost 86,000 downloads and the awesome help of 169 contributors we released the 1.0.0-alpha1 version. What is so great about this version  This release provides support for latest Drupal 8.1.x version released on April the 20th. For more information and details about this Drupal release you can visit Drupal 8.1.0 is now available. This release includes minor fixes and improvements and only one new feature. Support for placeholders on chain files, I will elaborate about this on another blog post, but if you are interested to know about this please visit the issue 2055. What is not so great about it Drupal 8.0.x is no longer supported. We are still trying to confirm if the Embedded Composer project can help us with this issue. If this is not doable, we can open a discussion to find a better way to approach this issue.
Categories: Drupal

The RPGnet Interview: Ed Jowett, Shades of Vengeance

RPGNet - 21 April 2016 - 12:00am
A talk with Ed Jowett, whose Shades of Vengeance has created the Era games.
Categories: Game Theory & Design

qed42.com: Pune Drupal Meetup - March 2016

Planet Drupal - 20 April 2016 - 11:44pm
Pune Drupal Meetup - March 2016 Body

The monthly meet-up for March was moved from the last friday of the month, which was the good Friday, to the 1st of April and hoped really hard that people didn't think it was an April fools prank. This PDG meetup was hosted by Rotary International thanks to diligence of Dipak Yadav who works there. It is always fun when the meetup is hosted in different locations because we get to explore different parts of Pune and see new faces.

With 25 members in attendence, the meetup was kicked off by Dipak giving us an informative talk about Rotary International and the work they do.

 

The speaker for the evening was Sushil Hanwate of Axelerant and he spoke on,“ Services and dependency injections in Drupal 8.”

 

The session ended after a short Q&A, we broke off into smaller groups for BOF sessions. Saket headed the BOF for Service workers and the second group discussed about the Drupal 8 Module development.

Once we were done with technical talks, we were served one of the best Kachoris we have tasted :). While we happily munched on the snacks, we decided on the preliminary team members for the upcoming Pune Drupal Camp.

Though the meetups are being held regularly we still need to figure a way of involving newer members into the community and one of the way that is possible is if we get more people volunteering to host the meetups. Kudos to Rotary for hosting us, if you are a Pune based company / group who would like to host the next meetup then please get in touch via comments. 

Our next PDG meetup is scheduled for the 29th of April. Along with a session on,"Experience with Drupal" by Rahul Savaria and Prashant Kumar from QED42, we shall also be planning and discussing further about the upcoming Pune Drupal Camp.
Dont forget to RSVP, See you soon!

aurelia.bhoy Thu, 04/21/2016 - 12:14
Categories: Drupal

User Registration Limit

New Drupal Modules - 20 April 2016 - 11:41pm

This module allows to limit user registrations based on the configurations.
like, 50 number of user registration allowed.

Installation
Install as you would normally install a contributed Drupal module.

Configuration
Visit admin/config/people/accounts, under 'Registration and cancellation' section, you will be able to enter the user registration limit value.

Categories: Drupal

Games deals rebound in Q1, but rocks below the surface - by Tim Merel

Gamasutra.com Blogs - 20 April 2016 - 11:02pm
Last year was the worst games deals ice age in a decade, but the topline numbers in Digi-Capital’s Games Report for Q1 2016 make it look like there has been a thaw. However, the buoyant waters of the first quarter hide rocks beneath the surface.
Categories: Game Theory & Design

Setting the Tone: Main Menus are the Game - by Max Pears

Gamasutra.com Blogs - 20 April 2016 - 11:02pm
The following is taken from my portfolio http://maxpears.com/ Discussing how the main menu can be used for more than just navigation but leave an impact on the player.
Categories: Game Theory & Design

A Method For Creative Paper Map Design - by Ryan Darcey

Gamasutra.com Blogs - 20 April 2016 - 11:02pm
Ryan Darcey discusses his process for generating unique map designs on Star Wars: First Assault.
Categories: Game Theory & Design

Balancing exposition and player agency in indie narratives - by Wes Platt

Gamasutra.com Blogs - 20 April 2016 - 11:02pm
We wanted to hold a panel on the topic of narrative approaches by indie games during PAX East 2016, but scheduling didn't work out. So I invited a few neighbors from the IndieMEGABOOTH to share their thoughts for this blog post.
Categories: Game Theory & Design

KnackForge: Programmatically create and trigger feeds importer

Planet Drupal - 20 April 2016 - 10:21pm
Programmatically create and trigger feeds importer

We met with a challenging requirement where we needed to create a feeds importer on node creation of particular content type. It’s like for ‘n’ number of nodes there must be a ‘n’ number of feeds importer.

For that I created a feeds importer which will be considered as the template. Whenever the node of specific content type is created, the template will be cloned and a new importer will be created.

The following code needs to reside in hook_node_insert() and will be used to clone the feeds importer:

Thu, 04/21/2016 - 10:51
Categories: Drupal

COD Mobile

New Drupal Modules - 20 April 2016 - 10:18pm

The COD mobile module works with drupal's 'Conference Organizing Distribution' and will generate a json file with session and related data such as speakers, tracks, room etc. The json file will generate automatically on drupal cron run or you can generate it manually by accessing the link example.com/generate-json.

The genrated json file will be placed inside the public files folder of the drupal installation eg: example.com/sites/default/files/sessions.json
This can be later used as a data provider for mobile applicatons.

Categories: Drupal

KnackForge: Apache Solr View Count module

Planet Drupal - 20 April 2016 - 9:46pm
Apache Solr View Count module

While working with Apache solr in drupal, I had to sort the results based on relevancy, date and popularity. The Apache solr sort module allowed me to sort based on relevancy and date, but sorting based on popularity wasn't available. What I mean by sorting based on popularity is that sorting based on the view count of each result.

suresh Thu, 04/21/2016 - 10:16
Categories: Drupal

govCMS CKAN

New Drupal Modules - 20 April 2016 - 6:36pm

govCMS CKAN provides integration with CKAN (http://ckan.org/). CKAN is a powerful data management system that makes data accessible by providing tools to streamline publishing, sharing, finding and using data.

This module provides a connector to any CKAN DataStore endpoint and pluggable visualisation layer using ctools.

Categories: Drupal

Commerce Chilexpress

New Drupal Modules - 20 April 2016 - 5:34pm

Integrates Chilexpress with Commerce Shipping.

Dependencies
Categories: Drupal

Chilexpress

New Drupal Modules - 20 April 2016 - 5:19pm

This module integrates Chilexpress service via SOAP web services. A services available in Chile.

Dependencies

This module requires the PHP SOAP extension.

Categories: Drupal

FFW Agency: Drupal Console: An Overview of the New Drupal CLI

Planet Drupal - 20 April 2016 - 5:01pm
Drupal Console: An Overview of the New Drupal CLI jmolivas Thu, 04/21/2016 - 00:01

Drupal Console is the new CLI (Command Line Interface) for Drupal. This tool can help you to generate boilerplate code, as well as interact with, and debug Drupal 8. From the ground up, it is built to utilize the same modern PHP practices that have been adopted in Drupal 8.

Drupal Console takes advantage of the Symfony Console and other well-known third-party components like Twig, Guzzle, and Dependency Injection among others. By embracing those standard components, we’re fully participating in the PHP community, building bridges and encouraging the PHP community to join the Drupal project and allow us to reduce the isolation of Drupal.

Why is Drupal Console important?

Drupal is infamous for having a steep learning curve, complete with its own language of “Drupalisms”. While Drupal 8 simplifies and standardizes the development process, it is more technically advanced and complex than its predecessor. 

Managing the increasing complexity of Drupal 8 could be a daunting task for anyone. Drupal Console has been designed to help you manage that complexity, facilitating Drupal 8 adoption while making development and interaction more efficient and enjoyable. Drupal Console was created with one goal in mind: to allow individuals and teams to develop smarter and faster on Drupal 8. 

Drupal Console features

In this blog post, I will mention some of the most common features and commands of Drupal Console, to serve as a good introduction.

Install Drupal Console

Copy configuration files

The init command copy application configuration files to the user home directory. Modifying this configuration files is how the behavior of the application can be modified. 

  Validate system requirements

The check command will verify the system requirements and throw error messages if any required extension is missing.

Install Drupal 8

The easiest way to try Drupal 8 on your local machine is by executing the chain command and pass the option --file=~/.console/chain/quick-start.yml

The chain command helps you to automate command execution, allowing you to define an external YAML file containing the definition name, options, and arguments of several commands and execute that list based on the sequence defined in the file.

In this example, the chain command will download and install Drupal using SQLite, and finally, start the PHP's built- in server. Now you only need to open your browser and point it to 127.0.0.1:8088.

  Generate a module

The generate:module command helps you to:

  • Generate a new module, including a new directory named hello_world at modules/custom directory.
  • Creates a hello_world.info.yml file at modules/custom/hello_world directory.
  Generate a service

The generate:service command helps you to: 

  • Generate a new service class and register it with the hello_world.services.yml file.

 

Generate a Controller

The generate:controller command helps you to:

  • Generate a new HelloController Class with a hello method at src/Controller directory.
  • Generate a route with a path to /hello/{name} at hello_world.routing.yml file.

 

Generate a Configuration Form

The generate:form:config command helps you to:

  • Generate a SettingsForm.php class at src/Form directory,
  • Generate a route with path to /admin/config/hello_world/settings at hello_world.routing.yml
  • Register at the hello_world.links.menu.yml file the hello_world.settings_form route using system.admin_config_system as parent.

This command allows you to add a form structure to include form fields based on the field API. Also generates a buildForm and submitForm methods with the required code to store and retrieve form values from the configuration system.

NOTE: The parent route system.admin_config_system for the menu_link can be selected from the command interaction.

  Debug Services

The container:debug command displays the currently registered services for an application. Drupal contains several services registered out-of-the-box plus the services added by custom and contributed modules, for that reason I will use peco a simplistic interactive filtering tool to make this debug easier.

 

Debug Routes

The router:debug command displays the currently registered routes for an application. Similar to debugging services. In this example, I will use peco to make this debugging task easier.

 

Create Data

The create:nodes command creates dummy nodes for your application.

 

Drupal Console provides a YAML to execute using the chain command. This file contains instructions to execute create:users, create:vocabularies, create:terms and create:nodes command using one command.

Change the application language

The settings:set command helps to change the application configuration in this example using the arguments language es we can set Spanish as the application language. After switching the default language the interface is translated.

  All of the available commands

The list command can be used to show all of the available commands. A print screen was not included because the more that 130 commands make the image huge to show on this blog post. 

For the full list of commands, you can also visit the documentation page at http://docs.drupalconsole.com/en/commands/available-commands.html 

What makes Drupal Console unique
  • Has been built to utilize the same modern PHP practices adopted by Drupal 8.
  • Generates the code and files required by Drupal 8 modules and components.
  • Facilitate Drupal 8 adoption while making development and interaction more efficient and enjoyable. 
  • Allow individuals and teams to develop smarter and faster on Drupal 8.
  • Help developers to understand Drupal 8 with the "--learning" flag.
  • Fully multilingual and translatable, just like Drupal 8 itself.
Links and resources Tagged with Comments
Categories: Drupal

FFW Agency: Great Examples Of Distributed Content Management In The Pharmaceutical Industry

Planet Drupal - 20 April 2016 - 5:00pm
Great Examples Of Distributed Content Management In The Pharmaceutical Industry hank.vanzile Thu, 04/21/2016 - 00:00

This is the third post in my series on Distributed Content Management.  In my first post I defined the term and used a few examples while doing so.  My second post, Great Examples of Distributed Content Management In Higher Education, expanded on the first example of a large university.  In today’s post we’ll explore the second example - a global pharmaceutical company - and once again discuss some great use cases for Distributed Content Management.

 

Setting The Scene

Pharmaceutical companies, more than companies in many other industries, must carefully consider all elements of their content lifecycle. Providing correct, approved content to both healthcare professionals and consumers is of utmost importance and, as such, web content in the pharmaceutical industry must undergo stringent regulatory review and control.  This requires consistent management across all digital properties and, for larger companies, that can be hundreds, or potentially even thousands, of websites and channels globally.

 

Use Case 1: Efficient Regulatory Review With Content Publishing Workflows

At first, the idea of Distributed Content Management may seem somewhat counterintuitive to how pharmaceutical companies work.  (In previous posts we’ve used it to explore empowering content creators and overcoming bottlenecks to content publishing - challenging concepts to tout for such a regulated industry.)  However, I’ve also opined that content approval and publishing workflows must be tailored to the specific use case.  

Consider a web publishing workflow that allows medical-legal reviews to take place within a Content Management System.  In some web systems this requires a multi-tiered platform wherein a “staging” version of the website - an exact copy of the real (“production”) website on which content changes have been staged - is made available for regulatory approval before the content is made available to the public.  While this is certainly more efficient than sharing offline documents, a deeper consideration of the technologies used can increase the efficiency and further control its risks.  

Some Content Management Systems, such as Drupal, allow content approval to take place on the production website, controlling the visibility and publishing of content through user authentication and roles instead of requiring  separate “staging” websites.  By mapping the appropriate roles to regulatory affairs, pharmaceutical companies using this approach can save costly and timely deployments of new content to the production site and free up the resources required to manage multiple copies of each website.

 

Use Case 2: Controlled, Single-Source Content Deployment

For some pharmaceutical content, decentralized content publishing may not be an appropriately-sized solution.  Some content is not only highly-regulated but also highly reused wherever products are marketed and is therefore best suited to be updated, approved, and disseminated from a central source.  Important Safety Information and Indications, for example, are types of content that a pharmaceutical company may choose to publish only through a centralized content repository.  

By establishing policies that all content editing must occur in the content repository, with individual websites disallowed from making changes locally, companies may avoid the need to have regulatory approval workflows on each of those sites and ensure that important information is updated in a timely and error-free way across numerous sites.  Content syndication is a fascinating opportunity for organizations considering Distributed Content Management and I’ll explore some of the available technologies, such as Acquia Content Hub, in later posts.

 

Use Case 3: Multichannel Brand Content

Single-source content syndication also provides an opportunity for pharmaceutical companies looking to promote their consumer products across multiple channels.  Let’s use e-commerce as an example.  Many companies choose to employ standalone, all-in-one e-commerce systems such as BigCommerce, Demandware and Magento rather than integrate e-commerce stores into each of their individual brand websites.  This makes a tremendous amount of sense: these systems can provide a number of compelling features such as gift cards, coupons, centralized inventory management, and opportunities for cross-selling other products among the company’s brands.  However, because these stores are independent of the main brand website, they too need to display content such as product descriptions, use and dosing information, ingredients, etc.  

By programmatically providing that content from a content repository to the e-commerce system, pharmaceutical companies can eliminate the risk of entering information directly into the store and potentially make use of the streamlined regulatory control processes they’ve already set up for the brand sites.

 

Use Case 4: Content Delivery To Validated Audiences

In addition to marketing content, pharmaceutical companies maintain large amounts of HCP content - information intended for healthcare professionals.  What content is available to these professionals, how they’ll access it, and how to validate the identity of a user seeking that information

is another key consideration for a pharma  company’s Distributed Content Management strategy.  A common approach is to segregate HCP content into regional “portals” - websites that require medical professionals to create accounts and login to see the information for their country or part of the world.  To overcome the challenge of validating these accounts, companies often integrate with an Identity Provider (IdP) such as DocCheck or Cegedim that specializes in maintaining national registries of healthcare professionals.  

However, having a number of disparate system integrations dependant on which country a website is intended to serve introduces both the overhead of managing multiple bundles of code - sometimes written in entirely different programming languages - and the opportunity for error in integrating the wrong code for the intended region.  Because of this, some global pharmaceutical companies may choose to build a more centralized approach to validation and registration using an integration platform such as Mulesoft Anypoint Platform to amalgamate the different Identity Provider code bundles and provide simultaneous access them all through a dedicated Identity Management system such as Janrain.

 

What’s Next?

We will continue exploring use cases for distributed content management for the next few posts before moving on to discussing some prerequisites for companies looking to implement Distributed Content Management.  Thoughts or questions?  Reach out in the comments below or tweet them to me at @HankVanZile.

 

 

Tagged with Comments
Categories: Drupal

Aten Design Group: Adding CSS Classes to Blocks in Drupal 8

Planet Drupal - 20 April 2016 - 3:25pm

This is an update to a previous post I wrote on adding classes to blocks in Drupal 7

As I've stated before, I'm a big fan of Modular CSS which requires the ability to easily manage classes on your markup. This was often a struggle in previous versions of Drupal. However, Drupal 8 makes this significantly easier to manage thanks to a number of improvements to the front-end developer experience (DX). In this post we'll look at how two of these DX improvements, the Twig template language and hook_theme_suggestions_HOOK_alter, and how they make adding classes to blocks much easier to manage.

Twig allows us to easily open up a template file and add our classes where we need them. There are two main approaches to adding classes to a template file. The first is simple: open the file, add the class directly to the tag, save the file and move on with your life.

block.html.twig <div class="block block--fancy"> {{ title_prefix }} {% if label %} <h2 class="block__title block__title--fancy">{{ label }}</h2> {% endif %} {{ title_suffix }} {% block content %} {{ content }} {% endblock %} </div>

This works in a lot of cases, but may not be flexible enough. The second approach utilizes the new attributes object – the successor to Drupal 7's attributes array. The attribute object encapsulates all the attributes for a given tag. It also includes a number of methods which enable you to add, remove and alter those attributes before printing. For now we'll just focus on the attributes.addClass() method. You can learn more about available methods in the official Drupal 8 documentation.

block.html.twig {% set classes = [ 'block', 'block--fancy' ] %}   {% set title_classes = [ 'block__title', 'block__title--fancy' ] %}   <div{{ attributes.addClass(classes) }}> {{ title_prefix }} {% if label %} <h2{{ title_attributes.addClass(title_classes) }}>{{ label }}</h2> {% endif %} {{ title_suffix }} {% block content %} {{ content }} {% endblock %} </div>

Alternatively, we can add our class directly to the class attribute with the existing classes from the attribute.class then print the remaining attributes. To prevent the class attribute from printing twice, we exclude it using the without Twig filter. Either way works.

block.html.twig <div class="block--fancy {{ attributes.class }}"{{attributes|without('class') }}> {{ title_prefix }} {% if label %} <h2 class="block--fancy {{ title_attributes.class }}" {{title_attributes|without('class') }}>{{ label }}</h2> {% endif %} {{ title_suffix }} {% block content %} {{ content }} {% endblock %} </div>

In any case, all our blocks on the site now look fancy as hell (assuming we've styled .block--fancy as such)

Template Suggestions

The above examples work. In reality if all our blocks look fancy, no blocks will look fancy. We need to apply this class only to our special blocks that truly deserve to be fancy. This introduces my second favorite DX improvement to Drupal 8 – hook_theme_suggestions_HOOK_alter.

If you wanted to make a custom template available for use to a certain block In Drupal 7, you had to do so in a preprocess function. Altering theme hook suggestions (the list of possible templates) in the Drupal 8 is delegated to its very own hook. The concept is pretty straight forward. Before Drupal renders an element, it looks at an array of possible template file names (a.k.a. suggestions) one-by-one. For each template file, it looks in the file system to see if that file exists in our theme, its base theme or core themes. Once it finds a match, it stops looking and renders the element using the matching template.

We'll use this hook to add our new template file to the list of suggestions. In the case of blocks, the function we'll define is hook_theme_suggestions_block_alter. It takes two arguments, the first is the array of suggestions which are passed by reference (by prefixing the parameter with a & so we can alter them directly. The second is the variables from our element that we can use to determine which templates we want to include.

Lets assume we renamed one of our templates above to block--fancy.html.twig and saved it to our theme. We then add the following function to my_theme.theme where "my_theme" is the name of our theme.

my_theme.theme <?php   /** * Implements hook_theme_suggestions_HOOK_alter() for block templates. */ function my_theme_theme_suggestions_block_alter(array &$suggestions, array $variables) { $block_id = $variables['elements']['#id'];   /* Uncomment the line below to see variables you can use to target a block */ // print $block_id . '<br/>';   /* Add classes based on the block id. */ switch ($block_id) { /* Account Menu block */ case 'account_menu': $suggestions[] = 'block__fancy'; break; } }

Now the account menu block on our site will use block--fancy.html.twig as we can see from the output of twig debug

This is just one example of the improvements in D8 theming. I'm really excited for the clarity that the new Twig templates bring to Drupal 8 and the simplicity of managing template suggestions through hook_theme_suggestions_HOOK_alter.

Categories: Drupal
Syndicate content


Google+
about seo