The Flexibility of Drupal drupalnights.org/events/2015/michael-miles-flexibility-drupal BioRAFT Drupal Nights
A presentation at BioRAFT Drupal Nights in January 2016 in Cambridge, MA, USA by Michael Miles
The Flexibility of Drupal drupalnights.org/events/2015/michael-miles-flexibility-drupal BioRAFT Drupal Nights
Michael Miles From: Boston, MA USA Work: Genuine @WeAreGenuine(.com) Exp: Working with Drupal since 2008. Acquia Grand Master. Acquia MVP. Twitter: @mikemiles86 Drupal.org: mikemiles86 All the Places: mikemiles86 mikemiles.com
Flexibility? Many manipulation methods Supports different skillsets Do what works for you
Focus of this Session 8 methods of manipulation Change title, destination & display of menu tabs Menus are universal
Session Environment A standard Drupal 8.0.1 install Bartik subtheme with Slate color Not live. (blame Murphy)
Environment starting point. A boring gray Drupal 8.0.1 site, with 8 menu tabs.
Environment end point. Colorful menu tabs, each on altered using a different method
#1. Core Admin UI Change data by clicking buttons. “Easy” to use No dev skills needed Capabilities are limited
Login as admin. Go to Structure, Menus and edit the main menu. Then edit the first menu link. Able to change the title and destination using Admin interface.
Have changed the title and destination of first menu link. Was not able to change the display with Admin UI.
#2. Modules Change data by extending Drupal core. Many options available Can build your own Require long term maintence
Want to extend core to change display of second menu link. Find, download and install the Menu Link Attributes module from drupal.org. Use Drupal Admin as in last method to alter menu tab. Module extends the form to allow adding HTML attributes such as inline styles.
Used a module to extend Drupal to change the text and background colors of second menu tab.
#3. Templates Change data by controling rendered HTML. Almost everything is templated Change HTML/Twig code Requires a custom theme
Want to change third menu tab using an overriden template.
Can use development configuration to debug theme and template data for main menu.
Use theme debug info for main menu. Tells the template used (line 5) and where to locate it (line 7). Provides template suggestion on how to override for just the main menu (line 4).
Copy the menu twig template from classy theme. Save as menumain.html.twig in templates directory of custom “subBartik” theme.
{% macro menu_links(items, attributes, menu_level) %} {# … #} {% for item in items %} {# … #} <li{{ item.attributes.addClass(classes) }}> {% if item.title == ‘Templates’ %} <a href=”node/9” style=”color:#F00;background:#0F0”>TEMPLATES ALT</a> {% else %} {{ link(item.title, item.url) }} {% endif %} {% if item.below %} {{ menus.menu_links(item.below, attributes, menu_level + 1) }} {% endif %} </li> {% endfor %} {# … #} {% endmacro %} themes/SubBartik/templates/menu—main.html.twig Alter markup in template override. For menu list item markup (lines 5 14). If ‘Templates’ is the title of the current menu item (line 6), then use a hardcoded HTML link (line 7).
Clear the Drupal cache to see the changes. When rendering, Drupal uses template override for main menu. Custom logic alters the ‘Templates’ tab to displays a different styled link.
#4. Custom CSS Change data by controlling display. Target specific elements Control inclusion with a library Requires custom theme or module
Can alter a menu tab using custom CSS, by adding css to a library in a custom theme.
menu-alter: version: VERSION css: css/menu_alter.css: {} themes/SubBartik/subbartik.libraries.yml Modules/Themes define libraries in a [name].libraries.yml file. Defining a library named ‘menualter’ (line 1) and the css files it includes (lines 2 3)..
.menu—main .menu li a[data-drupal-link-system-path=”node/4”] { background: #0000FF; themes/SubBartik/css/menu_alter.css CSS selector chains can become complicated. Targeting a link item in the main menu list, based on data attribute value. Anything that matches will have background color changed.
name: Sub Bartik type: theme base theme: bartik description: ‘A sub-theme of Bartik’ version: VERSION core: 8.x libraries: - subbartik/menu-alter themes/SubBartik/subbartik.info.yml Themes can include libraries globally by adding to *.info.yml file. Including ‘menualter’ library globally for subtheme (lines 7 8).
Site is using custom theme so it includes the library, which includes the custom css. The selectors target the ‘Custom CSS’ tab and changes the background color.
menu-alter: version: VERSION css: css/menu_alter.css: {} menu-alter-main: version: VERSION css: css/menu_alter_main.css: {} themes/SubBartik/subbartik.libraries.yml A *.libraries.yml file, can include many libraries. Each library has a unique name and included files. Add a new ‘menualtermain’ library (line 5 7).
.menu—main .menu li:nth-child(4) a { color: #FFF; } themes/SubBartik/css/menu_alter_main.css A simplier selector chain for targeting the link of the fourth main menu list item.
{{ attach_library(‘subbartik/menu-alter-main’) }} {% import _self as menus %} {{ menus.menu_links(items, attributes, 0) }} {% macro menu_links(items, attributes, menu_level) %} {% import _self as menus %} {% if items %} {% if menu_level == 0 %} <ul{{ attributes.addClass(‘menu’) }}> {% else %} <ul class=”menu”> {% endif %} {% for item in items %} {# … #} themes/SubBartik/templates/menu—main.html.twig Include libraries for specific templates by using the ‘attach_library’ Twig function. Include the ‘menu altermain’ library will only when rendering the main menu.
Drupal renders main menu using template override. Template includes function to attach library (and css) on the page. Custom CSS causes the text in the tab to display as white.
#5. Custom JavaScript Change data by manipulating DOM elements. Change based on actions Control inclusion with a library Dependent on client browser
Can alter a menu tab using custom JavaScript, by including it in a library in a custom module.
Like themes, modules need to define libraries in a *.libraries.yml file. Will add a library to custom “drupalflex” module to include custom JavaScript.
menu-alter: css: css/menu_alter.css: {} js: js/menu_alter.js: {} dependencies: - core/jquery - core/jquery.once - core/drupal modules/drupalflex/drupalflex.libraries.yml A library can contain many files as well as, depend on other libraries. Library contains css files (lines 2 3), javascript files (lines 4 5) and dependencies on other libraries (lines 6 9).
(function ($, Drupal) { “use strict”; Drupal.behaviors.drupalFlexMenuAlter = { attach: function (context) { $(‘.menu—main ul.menu li a’).each(function(){ if ($(this).attr(‘href’) == ‘/node/5’) { $(this).addClass(‘yellow-menu’); $(this).attr(‘style’, ‘color:#000;’); $(this).attr(‘target’, ‘_blank’); $(this).attr(‘href’, ‘/node/9’); $(this).text($(this).text() + Drupal.t(’ Alt’)); } }); } } })(jQuery, Drupal); modules/drupalflex/js/menu_alter.js Drupal behaviors are like jQuery document ready events. Drupal executes them when DOM loads. Create a custom behavior (line 3). Loop through each link item in the main menu (line 5). If link points to node/5 (line 6) alter display and destination (lines 7 11).
When Drupal loads the page it will invoke the hook instance in the “drupalflex” module. This will tell Drupal to include the library the contains the custom JavaScript. After DOM loads, JavaScript gets executed and alters the menu tab.
#6. Hooks Change data by interacting with core code. Provided by core and modules Requires custom theme or module Requires PHP skillset
Can alter a menu tab by using a hook in a custom theme or module.
Theme debug information gives a suggestion of what “theme” hook to implement (line 2).
// Implements hook_preprocess_HOOK(). function subbartik_preprocess_menu__main(&$variables) { // Loop through all menu tabs. foreach ($variables[‘items’] as &$menu_tab) { // Current tab pointing to node/6 ? if ($menu_tab[‘url’]->toString() == ‘/node/6’) { // Change location. $menu_tab[‘url’]->setRouteParameter(‘node’, ‘9’); // Existing attributes? if (!$attributes = $menu_tab[‘url’]->getOption(‘attributes’)) { $attributes = array(‘style’ => ”); } elseif (!isset($attributes[‘style’])) { $attributes[‘style’] = ”; } // Add custom styling. $attributes[‘style’] .= ‘color:#FFF;background:#00F;’; // Add back modified attributes. $menu_tab[‘url’]->setOption(‘attributes’, $attributes); } } } themes/SubBartik/subbartik.theme Themes place hooks in a *.theme file. Creating an instance of the preprocess_menu__main hook (line 4). Looping through all items in the main menu (line 6). If menu item points to node/6 (line 8), then alter the destination and styling (lines 10 21).
When building main menu, drupal invokes hook implementation. Logic alters menu item and changes text and background color.
Building of menus, drupal invokes hook implementation. Logic alters menu item and changes title and target.
#7. Services Change data by replacing core functionality. Control global tasks Requires OOP skillset Requires a custom module
Will change menu tab by overriding the Menu Service in a custom module.
namespace Drupal\drupalflex; use Drupal\Core\DependencyInjection\ServiceProviderBase; use Drupal\Core\DependencyInjection\ContainerBuilder; class DrupalflexServiceProvider extends ServiceProviderBase { /** * {@inheritdoc} */ public function alter(ContainerBuilder $container) { // Override menu_link_tree class with custom. $definition = $container->getDefinition(‘menu.link_tree’); $definition->setClass(‘Drupal\drupalflex\DrupalflexMenuLinkTree’); } } modules/drupalflex/src/DrupalflexServiceProvider.php To override a Service, modules need a *ServiceProvider.php file in an src directory. Service Provider class implements an alter method (line 10). Retrieves definition for menu link tree (line 12) and points it to a custom PHP class (line 13).
namespace Drupal\drupalflex; use Drupal\Core\Menu\MenuLinkTree; class DrupalflexMenuLinkTree extends MenuLinkTree { // Overrides \Drupal\Core\Menu\MenuLinkTree::build(). public function build(array $tree) { $build = parent::build($tree); if (isset($build[‘#items’]) && $build[‘#theme’] == ‘menu__main’) { foreach ($build[‘#items’] as &$item ) { if ($item[‘url’]->toString() == ‘/node/7’) { // Change Title, path and add styling. $item[‘title’] .= ’ Alt’; $item[‘url’]->setRouteParameter(‘node’, ‘9’); $item[‘url’]->setOption(‘attributes’, array( ‘style’ => ‘color:#00F;background:#00CEFD;’, )); } } } return $build; } } modules/drupalflex/src/DrupalflexMenuLinkTree.php Custom MenuLinkTree service class that extends the core base class (line 4). Override build method (line 6), which builds array of menu links. For only the main menu (line 8), loop through each menu item (line 9). If menu item points to node/7 (line 10) alter location and display (lines 11 16).
Drupal will use custom version of menu service to now build all menus. Will hit logic to change the ‘Services’ menu tab in the main menu.
#8. Combinations Change data by using multiple methods. Real world scenario Use multiple skillsets Most control over Drupal
Will alter a menu item using combination of multiple methods.
//… public function build(array $tree) { $build = parent::build($tree); if (isset($build[‘#items’]) && $build[‘#theme’] == ‘menu__main’) { foreach ($build[‘#items’] as &$item ) { // … if ($item[‘url’]->toString() == ‘/node/8’) { $item[‘title’] .=’ Alt’; } } } return $build; } modules/drupalflex/src/DrupalflexMenuLinkTree.php In custom menu service, Alter title for menu item pointing to node/8 (lines 7 9).
/** * Implements hook_preprocess_HOOK(). */ function subbartik_preprocess_menu__main(&$variables) { // Loop through all menu tabs. foreach ($variables[‘items’] as &$menu_tab) { // … $menu_tab[‘is_combo’] = ($menu_tab[‘title’] == ‘Combinations Alt’); } } themes/SubBartik/subbartik.theme Preprocess hook in custom theme, add new boolean attribute ‘is_combo’ to menu items (line 8).
.menu—main .menu li a.combo { color: #000; font-weight: 800; text-shadow: 0 0 #000 !important; background: red; /* not working, let’s see some red */ background: -moz-linear-gradient( top , rgba(255, 0, 0, 1) 0%, rgba(255, 255, 0, 1) 15%, rgba(0, 255, 0, 1) 30%, rgba(0, 255, 255, 1) 50%, rgba(0, 0, 255, 1) 65%, rgba(255, 0, 255, 1) 80%, rgba(255, 0, 0, 1) 100%); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(255, 0, 0, 1)), color-stop(15%, rgba(255, 255, 0, 1)), color-stop(30%, rgba(0, 255, 0, 1)), color-stop(50%, rgba(0, 255, 255, 1)), color-stop(65%, rgba(0, 0, 255, 1)), color-stop(80%, rgba(255, 0, 255, 1)), color-stop(100%, rgba(255, 0, 0, 1))); } themes/SubBartik/css/menu-alter.css Create css rule for links with class “combo” in main menu. Add to css file included in library that is included on all pages by custom theme.
(function ($, Drupal) { “use strict”; Drupal.behaviors.drupalFlexMenuAlter = { attach: function (context) { $(‘.menu—main ul.menu li a’).each(function(){ if ($(this).attr(‘href’) == ‘/node/5’) { // … } else if ($(this).attr(‘href’) == ‘/node/8’){ $(this).addClass(‘combo’); } }); } } })(jQuery, Drupal); modules/drupalflex/js/menu_later.js Add logic into javascript that is part of library defined by custom module. Logic adds ‘combo’ class to link item in main menu that points to node/8 (lines 9 11). .
Using a custom service, custom css, custom javascript, template override and hook instance together to alter last menu item.
Drupal is flexible! No “right” way. Only “Right for me” way.
Slides & Notes bit.ly/bioFlex This presentation bit.ly/bioFlexSlides Annotated slides on Slideshare. bit.ly/drupalREAD Blog post on how to select modules.
Thank You! Feedback/Questions? @mikemiles86 @BioRAFT_dev @WeAreGenuine Flexibility of Drupal / @mikemiles86