Third & Grove: Theming form elements in Drupal 8

Planet Drupal - Tue, 2016/11/29 - 5:03pm
Theming form elements in Drupal 8 ross Tue, 11/29/2016 - 11:03
Categories:

Xeno Media: Top Thirteen Drupal Twig Helper Modules

Planet Drupal - Tue, 2016/11/29 - 4:29pm

We have been loving learning Drupal 8’s theming system over the last year.  Drupal 8 core now uses the Twig template engine, which is a fast, flexible, and secure system that allows use to create the markup needed for the modern web.

What you can do with Drupal core’s Twig is pretty great, but the Drupal community always brings so much more to the table after real world use.  We don’t use them all, all of the time, but have used many as our design and development needed.  Here are our favorite modules to help build out your Drupal themes.

Twig tweak

The Twig Tweak Drupal module gives Drupal 8 themers additional commonly needed functions and filters to use in templating:

  • drupal_view: Pass arguments to views.
  • drupal_block: Include a Drupal block.
  • drupal_entity: Include a Drupal entity.
  • drupal_field: Renders a field from a specific entity.
  • drupal_token: Use token API to deliver data to your templates.
  • drupal_config: Access and print configuration.
  • token_replace: Place multiple tokens.
  • preg_replace: The easiest way to alter their output.
  • image_style: Provide either path or URI to original image.

It also allows for you to turn PHP filter back on, which isn't recommended, and is off by default.

Twig Field Value

The Twig Field Value Drupal module allows Drupal 8 themers to get partial data from field render arrays.  If you want to have control of the markup on your field’s label and/or value, you can.  If you want to choose the field’s text format, you can.  This great utility module gives us the following filters:

  • field_label: Returns the field label value.
  • field_value: Returns the render array of the field value(s) without the field wrappers.
  • field_raw: Returns raw field properties value(s).
  • field_target_entity: Returns the referenced entity object(s) of an entity reference field.
Twig Extensions

This handy Drupal 8 module adds support for the Twig Extensions library.  The library adds additional filters to Twig itself, and this module allows us to use them in Drupal.

  • Text: Provides useful filters for text manipulation.
  • I18n: Adds internationalization support via the gettext library.
  • Intl: Adds a filter for localization of DateTime objects.
  • Array: Provides useful filters for array manipulation.
  • Date: Adds a filter for rendering the difference between dates.
Twig Extender

The Twig Extender Drupal module adds a plugin system to add new twig extensions.  It includes one filter (truncate), and one function (user_is_logged_in), and promises more in the future.  Looks very promising.

Themable forms

This simple, and extremely helpful Drupal 8 module adds theme suggestions for form elements.

  • form-element--[form-id]--[element-type].html.twig
  • form-element--form-id--[form-id].html.twig
  • form-element--type--[element-type].html.twig
  • form-element.html.twig
Twig Renderable

The Twig Renderable Drupal module is another module that adds Twig functions and filters, this time that work specifically with render arrays.

Function

  • will_have_output('path', 'to', 'render', 'array')

Filters

  • add_class(string|array $class)
  • merge_attributes(array|\Drupal\Core\Template\Attribute $attributes)
Transliterate Twig Filter

This module adds a single Twig filter for transliterating diacritic strings. Transliteration is the conversion of a text from one script to another, and this module converts diacritic characters, those that have accents in them, to their normal counterparts.

The included example shows how it works:

{{ 'Hällo' | transliterate() }} becomes => Hallo

Responsive SVG

The Responsive SVG Drupal module that adds a Twig filter, with quite a few options for SVG Stacks.  SVG Stacks are like image sprites, where you have multiple images in one file, though these images are Scalable Vector Graphics.  Support for regular SVGs forthcoming.

Twig Xdebug

The Twig Xdebug Drupal module adds the ability to use Xdebug within Twig templates.  Add {{ breakpoint() }} into the template where you want to debug, and when the Xdebug processor reaches it, a separate file will open so you can inspect the variables up to that breakpoint. The key values you'll see at the breakpoint are:

  • $context: Variables available to use in the template.
  • $environment: Info about the Twig environment, including available functions.
  • $arguments: You can also add arguments like {{ breakpoint(fields) }}.
Twig Clean Debug

This simple and handy module adds a Twig filter that removes the Twig debugging output, those informative HTML comments that let you know which templates are available, but they can also get in the way of what you are working on!

Update your template to use {{ content.field_image|clean_debug|raw }} when you are developing.  Remember to remove it before pushing to production though, it will error our if twig debug is not on!

Twig Link Attributes

The Twig Link Attribute Drupal module adds a Twig filter that allows you to add attributes to links, which also merges them with existing attributes.  Works well with the Menu Link Attributes module, but safely keeps some attributes in code, while Site builders and administrators can manage attributes in the UI.

Themers Little Helper

Similar to Twig Tweak, the Themers Little Helper (TLH) Drupal module adds a bunch of Twig filters and functions, and promises more!  The current release includes:

  • base_url: the Base URl of the site.
  • Wrap filter: {{ content.title_field|wrap('h3') }} for wrapping markup around fields.
  • drupal_view: Embed a view direct in your template.
  • drupal_block: Embed a block direct in your template.
  • dump(variable): Support for the Vardumper module, which is faster than kint.
Component Libraries

Finally, the Components Libraries Drupal module allows you to register “component libraries” defined by your theme or module as Twig namespaces.  This means that you can specify a different directory, rather than a folder called “templates” for your Twig files.  This is lays the foundation for being able to use component based theming, where each aspect of the design is an individual piece, or component, and allowing integrating the external tools like Pattern Lab and KSS Node, which would also use this Twig templates for living style guides.

Happy theming!

Categories:

Acquia Developer Center Blog: Learn Drupal 8 for Free: Special Two-hour Version of FFW’s Drupal 8 Site Building Class

Planet Drupal - Tue, 2016/11/29 - 4:09pm

FFW, the mega digital agency, is offering a free, two-hour course for business technology and marketing decision makers who want a compressed intro to Drupal with the added benefit of a live instructor.

The class focuses on Drupal’s core concepts so organizations can get the most out of the platform and avoid common mistakes. It’s designed to help smooth Drupal adoption by companies and organizations.

It's coming up on Thursday, December 08, 2016, from 1 PM to 3 PM EST.

Tags: acquia drupal planet
Categories:

ComputerMinds.co.uk: Replacing a vocabulary listing

Planet Drupal - Tue, 2016/11/29 - 2:00pm

In a recent Drupal 8 project, one of the site's vocabularies had several thousand terms in it (representing airports), which caused its admin listing page to run out of memory before it could render. I wanted to solve this without affecting any other vocabularies on the site, and improve the listing itself along the way to be more useful, with filters to make searching it much easier. The original listing is not a view, and loads much more than it needs to. Here's the customised page for airports that I wanted to head towards:

Categories:

Agiledrop.com Blog: AGILEDROP: Drupal Camps in South America

Planet Drupal - Tue, 2016/11/29 - 7:21am
Famous beach Copacabana and football are the most frequent associations when we think of South America. Well, there are plenty more things there, that's for sure. Drupal Camps are one of those. In our world tour we already touched continents like Europe, North America, Asia and Africa. In the exact same sequence are continents listed from one with the most Drupal Camps (Europe) to the one with the least Drupal Camps (Africa). We expected to find South America between Asia and Africa, but for the first time, we were wrong. Our assumptions were so wrong, that it was difficult to process… READ MORE
Categories:

blog.studio.gd: Drupal 8 Views Plugins (Part 2) : The display extender plugin

Planet Drupal - Tue, 2016/11/29 - 3:36am
Let's see how and why to use a views display extender plugin.
Categories:

blog.studio.gd: Views Plugins (Part 1) : Simple area handler plugin

Planet Drupal - Tue, 2016/11/29 - 3:36am
In this series I will show you how to make use of the new Drupal 8 Plugin system, we begin with a simple example : the views area handler plugins.
Categories:

blog.studio.gd: Overview of CMI in Drupal 8

Planet Drupal - Tue, 2016/11/29 - 3:36am
Some notes about the new Configuration management system in Drupal 8
Categories:

blog.studio.gd: Migrate to Drupal 8 from a custom site

Planet Drupal - Tue, 2016/11/29 - 3:36am
Migrate is now included in the Drupal core for making the upgrade path from 6.x and 7.x versions to Drupal 8.

In this article will see how to use the Drupal migration framework to migrate custom sites to drupal 8.
Categories:

blog.studio.gd: Inline Entity Display

Planet Drupal - Tue, 2016/11/29 - 3:36am
Handle referenced entity fields directly in the parent entity
Categories:

Aten Design Group: Restricting Access to Drupal 8 Controllers

Planet Drupal - Tue, 2016/11/29 - 12:53am

Controllers in Drupal 8 are the equivalent of hook_menu in Drupal 7. A controller lets you define a URL and what content or data should appear at that URL. If you’re like me, limiting access to my controllers is sometimes an afterthought. Limiting access is important because it defines who can and can’t see a page.

Controllers are defined in a YAML file called module_name.routing.yml. Access and permission rules are defined in the the module_name.routing.yml under _requirements. Most of the code examples will be from a module_name.routing.yml file added to my_module in the top level.

Note: There is a lot of existing documentation on how to create controllers in Drupal 8, so I won’t focus on that here.

I’ve outlined some of the most useful approaches for limiting access below. You can jump straight to the most relevant section using the following links: limit by permission, limit by role, limit by one-off custom code, limit by custom access service.

Limit by permission

In this case, a permission from the Drupal permissions page is given. Permissions can be found at /admin/people/permissions. Finding the exact permission name can be tricky. Look for module.permissions.yml files in the module providing the permission.

my_module.dashboard: path: 'dashboard' defaults: _controller: '\Drupal\my_module\Controller\DashboardController::content' _title: 'Dashboard' requirements: _permission: 'access content'

Key YAML definition:

_permission: 'THE PERMISSION NAME'

Limit by role

You can also limit access by role. This would be useful in cases where users of a specific role will be the only ones needing access to your controller. You can define user roles at /admin/people/roles.

my_module.dashboard: path: 'dashboard' defaults: _controller: '\Drupal\my_module\Controller\DashboardController::content' _title: 'Dashboard' requirements: _role: 'administrator'

Key YAML definition:

_role: 'THE ROLE NAME'

You can specify multiple roles using "," for AND and "+" for OR logic.

Limit by one-off custom code

In cases where you have custom access requirements, adding an access method to your controller might make sense. In this example, the page should not be viewed before a specified date.

my_module.dashboard: path: 'dashboard' defaults: _controller: '\Drupal\my_module\Controller\DashboardController::content' _title: 'Dashboard' requirements: _custom_access: '\Drupal\my_module\Controller\DashboardController::access

Key YAML definition:

_custom_access: '\Drupal\my_module\Controller\DashboardController::access

The access method in my controller would look like:

<?php namespace Drupal\my_module\Controller;   use Drupal\Core\Access\AccessResult; use Drupal\Core\Controller\ControllerBase;   /** * Defines the Dashboard controller. */ class DashboardController extends ControllerBase { {   /** * Returns content for this controller. */ public function content() { $build = []; return $build; }   /** * Checks access for this controller. */ public function access() { // Don’t allow access before Friday, November 25, 2016. $today = date("Y-m-d H:i:s"); $date = "2016-11-25 00:00:00"; if ($date < $today) { // Return 403 Access Denied page. return AccessResult::forbidden(); } return AccessResult::allowed(); } }

Limit by custom access service

This is similar to having an access method in your controller, but allows the code to be reused across many controllers. This is ideal when you are doing the same access check across many controllers.

my_module.dashboard: path: 'dashboard' defaults: _controller: '\Drupal\my_module\Controller\DashboardController::content' _title: 'Dashboard' requirements: _custom_access_check: 'TRUE'

Key YAML definition:

_custom_access_check: 'TRUE'

Proving the _custom_access_check service requires creating two files in my_module.

my_module/my_module.services.yml (defines the Access service and where to find our Access class)

services: my_module.custom_access_check: class: Drupal\my_module\Access\CustomAccessCheck arguments: ['@current_user'] tags: - { name: access_check, applies_to: _custom_access_check }

my_module/src/Access/CustomAccessCheck.php

<?php namespace Drupal\my_module\Access;   use Drupal\Core\Access\AccessResult; use Drupal\Core\Routing\Access\AccessInterface; use Drupal\Core\Session\AccountInterface;   /** * Class CustomAccessCheck. * * @package Drupal\my_module\Access */ class CustomAccessCheck implements AccessInterface {   /** * A custom access check. * * @param \Drupal\Core\Session\AccountInterface $account * Run access checks for the logged in user. */ public function access(AccountInterface $account) { // User has a profile field defining their favorite color. if ($account->field_color->hasField() && !$account->field_color->isEmpty() && $account->field_color->getString() === 'blue') { // If the user's favorite color is blue, give them access. return AccessResult::allowed(); } return AccessResult::forbidden(); }   }

While the above covers some of the most useful ways to restrict access to a controller, there are additional options. Drupal.org has a couple of good resources including Structure of Routes and Access Checking on Routes.

Categories:

Drupal Console: Add DrupalConsole to a project using Acquia Lightning distribution

Planet Drupal - Mon, 2016/11/28 - 9:30pm
Lightning is a base distribution maintained by Acquia. In this short blog post you will learn how to fix the dependency conflicts when trying to add DrupalConsole to a project using the Lightning distribution.
Categories:

Kris Vanderwater: A response to Maxime: On Drupal and Drupal Commerce

Planet Drupal - Mon, 2016/11/28 - 5:30pm
A response to Maxime: On Drupal and Drupal Commerce by Kris Vanderwater -- 28 November 2016

This blog was originally intended as a comment on Maxime's medium post. It got long, and I am loath to create content for mega-sites. As such, I responded with a post of my own, which is exactly what Maxime did to Robert Douglass' original Facebook post... I guess we all have our competing standards ;-)

Categories:

OSTraining: What's Happening With Drupal Commerce in Drupal 8?

Planet Drupal - Mon, 2016/11/28 - 2:51pm

In the last few weeks, there's been some controversy in the Drupal community. Acquia launched a major partnership with Magento, which has left some people wondering about the support for Drupal Commerce. There had already been some nervousness, because Drupal Commerce 2 has been slow to arrive in Drupal 8.

So, what's happening with Drupal Commerce?

First, I would recommend you read Dries' post on Acquia's plans for e-commerce.

Next, I'd highly recommend that you watch this video from Ryan Szarma, one of the lead developers of Drupal Commerce. This video was recorded at Drupal 8 Day. Ryan covers the history, architecture, and features of Drupal Commerce 2 on Drupal 8. There was a lot of interest in Ryan's presentation, with over 30 minutes of questions afterwards.

Categories:

Nuvole: Configuration Split: first beta release at Drupal IronCamp

Planet Drupal - Mon, 2016/11/28 - 12:30pm
Solving one of Drupal 8 core's development and deployment work-flow issues.

One of the nice things that happened during Drupal Ironcamp in Prague last week was the first beta release of the Configuration Split that I started developing a few months ago.

As explained in the previous blog post about Configuration Split, the typical use case of Configuration Split is to be able to maintain a "development" configuration and a "production" configuration, where some of the modules or settings you use in development are not copied to production upon configuration export/import.

A typical use case

We assume that you have a production and development version of the same site and that they are aligned.

Step 1: Enable anything you need in development and work normally

In the development environment we enable Devel and UI modules enabled and we can create new content types, add fields and do all things we like to do while developing a Drupal site. Some of this configuration work is meant to go to the production site and some (e.g., the fact that Devel is enabled and related configuration) is not. We thus need to split our configuration.

Step 2: Create a split definition

Choose a name for your "local" configuration and select all the configuration you don't want to have on the live site (even though, if you wish, you can still share it with colleagues). This can include modules you would not want to be enabled or configuration that is for development only. The path here is a folder next to the normal config sync directory outside of the web root. In the example above, we are splitting out to a configuration set named "Development" the Devel, Fields UI, Views UI modules and the system.menu.devel configuration.

Step 3: Export your configuration with config_split

$ drush config-split-export

In the most basic use case we just replace config-export with config-split-export in our workflow. This exports the elements we selected above to ../config/dev and the rest (the configuration we want to deplay) to our "standard" configuration folder, in this case ../config/sync.

Step 4: Import the "clean" configuration in production

On all environments we use the configuration import of config_split:

$ drush config-split-import

So in our usual workflow we replace config-import with config-split-import

In order not to have different workflows for development and production we simply deactivate the split on production by overriding the configuration in settings.php on production: $config['config_split.config_split.development']['status'] = FALSE;

This will result in the split definition to be deactivated. And consequently the import will have the configuration blacklisted in the split removed and development modules deactivated.

What's new in the beta version

The following features are new or changed in the beta release:

  • The drush command works and has some text to warn users to which directories configuration will be written to.
  • The drupal console command is disabled, but there is a patch/branch you can use or help to make it functional again.
  • Split entities now have a status and the default command only uses the active splits. Of course you can override that in settings.php as with almost all configuration.
  • You can switch out the default config.storage.sync service in your services.yml file so that the default configuration sync UI uses the split import. Details are in the README.txt file.
More information and acknowledgments

On Friday I gave a presentation about my favorite topic in Drupal: Configuration Management, attached here are the slides.

I wish to thank IronCamp participants and especially Swentel and mr.baileys who worked on patches, and I'd like to thank IronCamp organizers for a very well organized event where I met a lot of old and new friends. Swentel also took care of documenting more advanced use cases of Configuration Split on his blog.

For any further information see the module page and its issue queue.

Tags: Drupal PlanetDrupal 8Code Driven DevelopmentAttachments:  Configuration Management - slides Ironcamp Prague
Categories:

qed42.com: REST API Explorations in Drupal 8 - Primer

Planet Drupal - Mon, 2016/11/28 - 11:26am
REST API Explorations in Drupal 8 - Primer Body

This article assumes you are familiar with what RESTful is & what do we mean when we use the term REST API. Some of you might have already worked with RESTful Web Services module in D7, it exposes all entity types as web services using REST architecture. Drupal 8 out of the box is RESTful with core support. All entities (provided by core + ones created using Entity API) are RESTful resources.

To explore the RESTful nature of Drupal 8, we will need to enable the following modules:

In Core
  • HAL - Serializes entities using Hypertext Application Language.
  • HTTP Basic Authentication - Provides the HTTP Basic authentication provider.
  • RESTful Web Services - Exposes entities and other resources as RESTful web API
  • Serialization - Provides a service for (de)serializing data to/from formats such as JSON and XML.
Contributed
  • REST UI - Provides a user interface to manage REST resources.
RESTful Resources

Every entity in D8 is a resource, which has an end point. Since, its RESTful, the same end-point is used for CRUD (Create, Read, Update, Delete) operations with different HTTP verbs. Postman is an excellent tool to explore / test RESTful services.  Drupal 8 allows you to selectively choose & enable a REST API. e.g., we can choose to expose only nodes via a REST API & not other entities like users, taxonomy, comments etc.

After enabling REST_UI module we can see list of all RESTful resources at /admin/config/services/rest. In addition to ability to choose the entity one can enable, we can also choose the authentication method per resource & enable specific CRUD operations per resource.

Let us take a look at what the REST APIs for User entity would be after we save the configuration in the above screenshot.

User

POST

http://domain.com/entity/user?_format=hal_json {  "_links": {    "type": {      "href": "http://domain.com/rest/type/user/user"    }  },  "name": {    "value":"testuser"  },  "mail":{    "value":"testuser@mailserver.com"  },  "pass":{    "value":"testpass"  },  "status": {    "value": 1  } }

Header

X-CSRF-Token: Get from http://domain.com/rest/session/token Content-Type: application/hal+json Accept: application/hal+json Authorization: Basic (hashed username and password)

Note: Drupal 8 doesn't allow anonymous user to send a POST on user resource. It is already fixed in 8.3.x branch but for now we can pass the credentials of the user who have permission to create users. If you are interested in taking a deeper look at the issue, you can follow https://www.drupal.org/node/2291055.

Response: You will get a user object with "200 OK" response code

 

PATCH

http://domain.com/user/{uid}?_format=hal_json {  "_links": {    "type": {      "href": "http://domain.com/rest/type/user/user"    }  },  "pass":[{"existing":"testpass"}],  "mail":{    "value":"updatedtestuser@mailserver.com"  } }

Note: Now as user have permission to update his own profile so we can pass current user's credentials in authentication header.

Response: You will get "204 No Content" in response code.

 

GET

http://domain.com/user/{uid}?_format=hal_json

Response: You will get a user object with "200 OK" response code.

 

DELETE

http://domain.com/user/{uid}?_format=hal_json

Response: You will get "204 No Content" in response code.

RESTful Views and Authentication

Drupal 8 also allows us to export views as a REST service. It allows you to use all the available authentication mechanism in views itself.

JSON API Module

JSON API module provides a new format called "api_json" which is soon becoming the de-facto standard for Javascript Frontend frameworks, If you plan to use completely de-coupled Drupal with frontend framework like Angular / React / Ember then its worth a look. To read more about JSON API you can visit the site.

SUMIT MADAN Mon, 11/28/2016 - 15:56
Categories:

Kristof De Jaeger: Configuration split: deploy subsets of configuration in Drupal 8

Planet Drupal - Mon, 2016/11/28 - 11:01am
Written on November 28, 2016 - 11:01

From the Configuration split project page: "The Drupal 8 configuration management works best when importing and exporting the whole set of the sites configuration. However, sometimes developers like to opt out of the robustness of CMI and have a super-set of configuration active on their development machine and deploy only a subset. The canonical example for this is to have the devel module installed or having a few block placements or views in the development environment and then not export them into the set of configuration to be deployed, yet still being able to share the development configuration with colleagues."

This small utility module for Drupal 8 allows you to exactly achieve this use case (and many others). I will cover two common scenarios, explaining how to configure your site and which commands you need to run:

  1. Have (development/ui) modules installed on your dev environment, uninstalled on production
  2. Have modules installed on your production environment, but not on development

I've also recorded a screencast in which I configure and run all the commands explained underneath. The best way in the end is to play around with the module itself of course.

Configuration split 101

Configuration split exposes a configuration entity which controls what you want to split off. Currently you can

  • blacklist modules: any configuration that this module owns will automatically be blacklisted too.
  • blacklist configuration: settings or configuration entities. These will be removed from the active sync directory.
  • graylist configuration: settings or configuration entities. These will not be removed if they are in the active sync directory, but also not exported if they are not there yet. I won't cover this functionality in this article post, that will be for another time.

After you configured one or more configurations split entities, you can use the drush commands to export and import configuration, based on one or more of those config entities. When it comes to exporting configuration, you can not use the existing drush core command (config-export / cex). Using drush config-import (cim) or the UI to import may still be used, but this depends on your setup. Drupal Console commands are under revision.

Each config split entity defines the directory in which the splitted configuration will live in case there are some. Not all modules define configuration, so there's a possibility that this directory is empty after you do an export.

An important technical aspect is that the module does not interfere with the active configuration but instead filters on the import/export pipeline. What simple happens is this: just before the actual writing, it will check the configuration and remove any entries that you don't want to be there. Then your active configuration is written away. Config that doesn't belong into the active configuration will be moved to separate directory. On import, the opposite happens: it will merge settings back in and set modules to the installed state just before core configuration then starts importing.

Last, but not least: you can swap the config.storage.sync service so that the synchronize screen will use the config split config entities for importing. More information is in the README file and in the video.

Scenario 1: modules installed on dev, not on production

Step 1

After you installed the module, go to 'admin/config/development/configuration/config-split' and click on 'Add configuration split'. Naming is important, so we'll enter 'Dev split' as the name for this configuration. We'll also create a directory called 'sync-dev-split'. Now toggle the modules that you don't want to have installed on production. In this case, we're going to blacklist Devel, Devel Kint, Field UI, Views UI and database logging. Additionally, also toggle system.menu.devel. This configuration is owned by the system module, so there's no dependency on the devel module. There's no problem having this config on your production site though, so it's not required to blacklist it.

Optionally, you can also blacklist the configuration split module because it doesn't necessarily have to be installed on production. We're not doing that here, because in the second scenario, we're building further on this one and we want to have it installed on the production environment as well.

Step 2

Go to your command line interface and run following command:

swentel@dev:/home/drupal/drupal-core$ drush csex --split=dev_split

The split option is not required, but when starting to work with the module, it helps you to know which config split will be used for this command. It's possible to override the status of any config split config entity so that eventually, you can omit the split option. Sadly enough, you don't get any feedback (yet), but after the command has run you should see various files in your sync-dev-split directory:

swentel@dev:/home/drupal/drupal-core$ ls sync-dev-split/
dblog.settings.yml  devel.settings.yml  field_ui.settings.yml  system.menu.devel.yml

Step 3

You can now commit your active sync and go to production. You don't necessarily have to put the sync-dev-live directory in your version control because production doesn't need to know about these files at all. Once you have pulled on production, go to the synchronize screen to verify what is staged. You will see that the setting files will be removed and core.extension will be changed uninstalling the development modules and installing configuration split. Since we only have one config split configuration, you can hit 'Import all' here or run drush config-import, (which is the drush core command). Note that if you don't use the UI, you can blacklist the configuration manager module as well.

You might wonder why we don't use the 'config-split-import' command from the module itself: this would import the active sync directory and also include the modules and settings again that we have blacklisted. And that's not what we want. This seems confusing at first, but ultimately, if this is your setup, you just keep on using the core / drush commands to import your staged configuration on production.

# This command can be used now, but not anymore further on when we will add scenario 2.
swentel@live:/home/drupal/drupal-core$ drush cim Scenario 2: modules installed on production, not on dev

Step 1

This scenario builds further on the first one. Config split is now installed on our live website. Create a new config split configuration called 'Live split'. You will need a new directory for this second config split, so make sure it's there. On production we still want to log events and for that we're going to use the syslog module. Install the module, so that we can now blacklist it for the live split configuration.

Step 2

Go to your command line interface and run following commands:

swentel@live:/home/drupal/drupal-core$ drush csex --split=live_split

Again, no feedback here, but after the command has run you should see the syslog settings file in your sync-live-split directory:

swentel@live:/home/drupal/drupal-core$ ls sync-live-split/
syslog.settings.yml Doing exports and imports on dev or live

From now on, if you want to import new settings whether it's on your dev or live environment, you can not use the drush core commands anymore. Use following commands:

# to export on your dev environment
swentel@dev:/home/drupal/drupal-core$ drush csex --split=dev_split
# to import on your dev environment
swentel@dev:/home/drupal/drupal-core$ drush csim --split=dev_split
# to export on your live environment
swentel@live:/home/drupal/drupal-core$ drush csex --split=live_split
# to import on your live environment
swentel@live:/home/drupal/drupal-core$ drush csim --split=live_split The future

Please join us in the issue queue because there's still some work:

  • Optimize the user interface and allow wildcards
  • Add confirmation and feedback in the drush commands

Ultimately, this functionality should live in core. A core issue to discuss this is at https://www.drupal.org/node/2830300.

Categories:

ADCI Solutions: Drush

Planet Drupal - Mon, 2016/11/28 - 8:44am

Summary

Drush is a command line utility for Drupal that allows to avoid or at least to speed up many kinds of routine tasks. Usually a developer deals with these Drush parts: Drush make, adding the extra Drush commands and tuning Drush and Drupal via configuration files. In this article we listed the main Drush commands, thoroughly described the Drupal website configuration process with the help of Drush, told about shell and Drupal site aliases and learned how working with Drush has changed in Drupal 8. We supplemented each description of working with a particular Drush part with code samples: please feel free to use these examples in your development workflow.

Preface

Drush (The Drupal Shell) is a command line utility for Drupal, which provides many commands to interact with Drupal, its modules, themes, etc. Drush is a great developer’s helper and it allows to avoid or at least to speed up many kinds of routine tasks.

There are many articles telling about different Drush commands and how they helpful are, so I'd like to focus on Drush configuration possibilities and do a quick overview on Drush commands and Drush make. When you use Drush all the interactions with a Drupal site happen by executing commands, but there are some other Drush parts you may deal with:

  • Drush make which is combination of a special definition stored in the (make) file and a few specific commands to build a Drupal site codebase;
  • possibilities to add your own Drush commands by writing code in the files called in a special way and placed properly;
  • tuning Drush and Drupal via configuration files and more.

Drush processes described below are not necessarily should be implemented together. Since it’s not an algorithm of working with Drush, but a descriptive compilation, you may refer to the any article’s part when needed.

Drush commands

As you already know,  an interaction with a Drupal site happens via Drush commands. The Drush core provides many commands for many different purposes, but I believe the most used Drush commands are:

  • drush pm-download (dl) - download one or several projects (the Drupal core, module, theme, distribution), so you don't have to visit drupal.org to download and then unpack projects one by one;

  • drush pm-enable (en) - enable (install, if wasn't enabled before) one or several modules or themes;
  • drush cache-clear (cc) - clear cache (routing, theme, all, Drush, etc. cache).

With Drush you also can:

  • make a full site backup;
  • update the Drupal core, contrib modules and themes;
  • run cron jobs;
  • execute SQL query;
  • block user account(s);
  • change Drupal settings;

and other.

Drush make

Drush make allows to create a ready-to-use Drupal site codebase including the Drupal core, modules, themes, etc., (but without installation) from a definition stored in the just one file. Drush make does the work for you:

  • downloads the Drupal core, modules, themes;
  • fetches code from Git, SVN repositories;
  • downloads and applies patches;
  • downloads .tar.gz and .zip archives in general;
  • downloads libraries in particular.

The Drush make file can be written in 2 formats: YAML and the older Drupal .info INI format similar to modules' .info. YAML is recommended though, since Drupal is switched to YAML for configurations (since Drupal 8).

There are 2 main commands to work with Drush make:

  • drush make example.make.yml docroot - make a Drupal codebase using the definition stored in the example.make.yml file;
  • drush make-generate example.make.yml - generate the make file from a current Drupal site.

In case you develop Drupal distributions with following publishing at drupal.org, you have to deal with Drush make anyway.

Drush make file example (in YAML):

core: 7.x api: 2 projects: drupal: type: core admin_menu: subdir: contrib ctools: version: "1.7" tao: type: theme download: url: "git://github.com/developmentseed/tao.git"Extending the list of Drush commands

New commands can be easily added to Drush, and many contrib modules provide their own Drush commands: there is the modulename.drush.inc file in the module containing Drush integration code in this case. For example:

  • drush fn-hook (Devel module) - shows a list of implementations for the particular hook;
  • drush generate-content (Devel module) - generates dummy content;
  • drush features-revert-all (Features module) - reverts all the configurations exported into modules via the Features module to the code state;
  • drush views-list (Views module) - lists all the views on the site.

It's also possible to add Drush commands outside of modules, for example, to perform some specific actions for deployment, so you don't have to create and install a module on the site just to be able to invoke these Drush commands.

Drush configuration

Drush as well as a Drupal site can be configured in the context of running Drush commands. Needed configurations are defined in the drushrc.php file (DrushRC = Drush Runtime Config). For example, it's possible to force some global options for the Drush commands like always answering "yes" to all the confirmation prompts, force some of the command-specific options, change some of the Drupal settings (like an emails handler class and so on).

Drush looks for the drushrc.php file in the following directories, one by one as listed below. The order is basically the same when Drush looks for the files containing additional Drush commands (if the commands aren't related to the particular module):

  • sites/{default|example.com}/drushrc.php - a site specific directory;
  • Drupal /drush and sites/all/drush directories;
  • /drush directory 1 level above the Drupal root;
  • as specified by --config (-c) option when running a Drush command;
  • User's .drush folder (~/.drush/drushrc.php);
  • /etc/drush/drushrc.php;
  • the Drush installation folder.

Let's see some examples (see the code comments for more info on what each setting means):

/** * Drush commands configuration. */ // Force verbose mode for all commands. $options['v'] = 1; // Answer "yes" to all confirmation prompts. $options['y'] = 1; // Force --notes option for pm-update command. $command_specific['pm-update'] = ['notes' => TRUE]; // Use admin/admin as superuser credentials when installing Drupal site. $command_specific['site-install'] = [ 'account-name' => 'admin', 'account-pass' => 'admin', ]; /** * Site configuration. */ // Change site name. $options['variables']['site_name'] = 'My Drupal site'; // Use different theme. $options['variables']['theme_default'] = 'minnelli'; // Disable clean URLs. $options['variables']['clean_url'] = 0; // Use different directory for temporary. $options['variables']['file_temporary_path'] = '/home/vagrant/tmp'; /** * SQL dump and structure tables. */ // List of tables to export structure only without data on dump. $options['structure-tables']['common'] = [ 'cache', 'cache_*', 'history', 'search_*', 'sessions', ]; // Force "common" structure tables list by default on sql-dump command. $command_specific['sql-dump'] = [ 'structure-tables-key' => 'common', ]; Shell aliases

Drush also allows to define short aliases for a command or a number of commands, potentially used with a number of set options, via drushrc.php file, and this is not limited by Drush commands only.

// drush wipe $options['shell-aliases']['wipe'] = 'cache-clear all'; // drush pulldb $options['shell-aliases']['pulldb'] = '!git pull && drush updatedb'; // drush offline $options['shell-aliases']['offline'] = 'variable-set -y --exact maintenance_mode 1'; // drush online $options['shell-aliases']['online'] = 'variable-delete -y --exact maintenance_mode'; // drush unsuck $options['shell-aliases']['unsuck'] = 'pm-disable -y overlay, dashboard'; The lines starting with ! are not Drush commands, the lines without ! - are supposed to be Drush commands and the leading drush word is not needed in this case.

As it was shown, Drush allows to shorten the entered commands (executed at the command line) via different configurations, and to properly configure a Drupal site when you interact with it via Drush. All of these decrease an amount of routine actions and speed up the process of dealing with Drupal as a result.

Drush site aliases

Let’s expand on an interaction with Drupal via Drush. Usually, the interaction and an execution of some commands require that you have to navigate to the Drupal root directory first. If it’s a Drupal multi-site you need to navigate deeper to the site directory (sites/site-name), or explicitly set --uri (a site address when the site is opened in a browser) and --root (a path to the Drupal root directory) options when executing a Drush command. With the help of Drush site aliases all of these can be shortened to drush @example.com status with no difference from where the command is executed.

Drush site aliases can be defined in the file similar to drushrc.php, and Drush looks for this file in the same places it looks for drushrc.php. To define the site alias you just need to set uri and root properties.

// drush @example status $aliases['example'] = [ 'root' => '/var/www/example.dev/docroot', 'uri' => 'http://dev.example.com', ];

There are 3 ways to name the file where the site aliases are defined:

  • ALIASNAME.alias.drushrc.php - commands are executed like drush @ALIASNAME status;
  • aliases.drushrc.php - commands are executed like drush @ALIASNAME status;
  • GROUPNAME.aliases.drushrc.php - commands are executed like drush @GROUPNAME.ALIASNAME status.

The 3rd way is convenient for defining several instances / environments of the same site:

/** * @file * example.aliases.drushrc.php */ // drush @example.dev status $aliases['dev'] = [ 'root' => '/var/www/example.dev/docroot', 'uri' => 'http://dev.example.com', ]; // drush @example.stage status $aliases['stage'] = [ 'root' => '/var/www/example.stage/docroot', 'uri' => 'http://stage.example.com', ];

It's also possible to execute a command for all sites in a group simultaneously:

drush @example status

Actually, Drush allows to interact via the site aliases not with local sites only, but also with remote sites. In this case, you need to set a few more properties, at least remote-host and remote-user (but there are more options available).

$aliases['example.stage'] = [ 'remote-host' => 'server.example.com', 'remote-user' => 'www-admin', 'root' => '/var/www/example.stage/docroot', 'uri' => 'http://stage.example.com', ];

When you deal with the remote sites, you definitely want to avoid any mistakes: this can be done by adding a validation via Drush command hooks:

/** * @file * policy.drush.inc */ /** * Implements drush_hook_COMMAND_validate(). */ function drush_policy_sql_sync_validate($source = NULL, $destination = NULL) { // Deny sync to prod/production. if (preg_match("/^@.*prod/i", $destination)) { return drush_set_error('POLICY_DENY', dt('Nope.')); } }

Basically this is the same way how new Drush commands are added, so file naming is the same. In this particular case there is a convention to call this "Policy".

Drush contains a number of special commands for usage with the remote sites and the sites aliases.

drush core-rsync @site.remote:db.sql @site.local:backup/ drush core-rsync @site.remote:%files/ @site.local:%files/

- to rsync the Drupal tree to/from another server using ssh. %files is a special token pointing to a public file uploads directory, but there are more tokens available and custom ones may be defined via path-aliases site alias property.

drush sql-sync @site.remote @site.local

- to copy the database content from a source site to a target site, a database dump is transferred via rsync.

To connect to the Drupal site's server via SSH for an interactive session:

drush @site.remote site-ssh

or to run a shell command:

drush @site.remote site-ssh ls -la drush @site.remote core-execute ls -la drush @site.local core-execute ls -la Drush and Drupal 8

There are many changes in Drupal 8 in comparison with the previous version. When it comes to Drush, there are no big difference in dealing with a Drupal site. Probably the most noticeable change is that there is no more drush cache-clear all to flush all the caches. There is drush cache-rebuild instead. The another kinds of caches can still be cleared via drush cache-clear. An interaction with Drupal 8 via Drush requires Drush 8 version and newer.

Also there is few new Drush commands to interact with things specific to Drupal 8:

config-edit (cedit) config-export (cex) config-get (cget) ...

- to deal with configurations;

state-get (sget) state-set (sset) ...

- to deal with states.

Conclusion

Drush is a great tool which can help you with a Drupal site building, development and maintenance, and it noticeably speeds up these processes. The main part of  Drush is its commands, of course, but you can also tune Drush and Drupal (in context of interaction via Drush) for your own needs via configuration files, you can add custom commands like contrib modules often do, build a Drupal site codebase from a single file, deal with remote Drupal sites via Drush site aliases and more. Drush exists for a long time, but it's still a must-have: a very stable, well maintained and always evolving tool for Drupal. Stable and actively maintained Drush version for that moment is 8.x (you need this version or newer to deal with Drupal 8), Drush 9.x is in alpha and is being actively developed.

The observed Drush parts and processes are definitely going to cross your development and site-building path, so make sure to save and share this article with fellow Drupal developers. Good luck!

 

Categories:

PreviousNext: Presentation: At 16 years of age - does Drupal have an identity problem?

Planet Drupal - Mon, 2016/11/28 - 1:44am

At Drupal South 2016, I attempted to summarize some of my pain points with Drupal core.

The session 'At 16 years of age, does Drupal have an identity problem' is the result of this.

You can watch the recording, or download the slides below.

Categories:

DataSmith: Inconsistent nofollow handling in Drupal input formats

Planet Drupal - Sun, 2016/11/27 - 8:18pm
Inconsistent nofollow handling in Drupal input formats The Problem

Working on setting up commenting, which is highly suggested for sites who's content appears on Drupal Planet, I came across a bit of a confusing situation in regard to URLs in content. When using the "Limit allowed HTML tags and correct faulty HTML" filter, one of the option is to add rel="nofollow" attributes to anchor tags. However, in the default Plain Text format, the "Convert URLs into links" filter does not provide that option. So if a user types in an HTML anchor, nofollow gets added. But if they type in a plain URl, it gets converted to an HTML anchor without the nofollow.

To illustrate, if I allow anchor links to be entered as html and set the option to add rel=nofollow and I also enable the filter to convert URLs to links, if a user enters:

www.nytimes.com Another NY Times link

The output HTML in the comment is:

https://www.nytimes.com
Another NY Times link

For commenting, I really want to tighten permissions down as far as I can to avoid potential security risks, so the Plain Text format with the "Display any HTML as plain text" filter is the best choice1. However, for usability I do want URLs converted to links. But I also want those links set to nofollow for link fraud prevention2.

By playing with format filter configurations and ordering I was able to make a solution that works (albeit a little janky-ly), but it sure feels like this is an area where a core patch could improve the situation. If I have time one day maybe I'll work on that3.

Solution

The solution I came up with is to set the following filters on the input format (the order is significant):

  1. Display any HTML as plain text
  2. Convert URLs into links
  3. Convert line breaks into HTML (i.e.
    and

    )

  4. Limit allowed HTML tags and correct faulty HTML

Then for the allowed HTML tags, I allowed <a href hreflang> <p> <br> and checked the `Add rel="nofollow" to all links` option.

The result is that user entered HTML is rendered as plain text, then URLs and line brakes get converted to HTML, and finally the Limit allowed HTML filter double checks the markup and adds `rel="nofollow"` to anchor tags.  So given a user input comment like in the screen shot below, the resulting HTML is:

www.nytimes.com
<h2>This should not be displayed as an h2 element.</h2>
<a href="If" rel="nofollow">www.example.com">If this is a link to example.com and not www.nytimes.com, you've failed.</a>
Comment preview showing the user entered comment, the resulting comment, and the help text.

Now, this solution is not perfect. Mostly, it's hinky to set up and I hate that I have to allow any HTML, even if user input is first stripped to plain text. Secondly though, it's also a user experience problem. As you can see in the picture above, the help text says that no html is allowed and that the anchor, break, and paragraph tags are allowed.

Footnotes

1. using the core commenting facility at least. Add on tools like Disqus obviate the issue but I don't want to go that route. I also don't want to require (or even allow) users to register before commenting. And yes, I do require approval of comments before they are visible, but I don't want to have to remember to add rel=nofollow in links.

2. Yes. I want to eat my cake and have it too.

3. I was put on this earth to achieve certain things. At this point I'm so far behind I'll never die.

Barrett Sun, 11/27/2016 - 13:18 Tags Add new comment
Categories: