Planet Drupal

Subscribe to Planet Drupal feed
Drupal.org - aggregated feeds in category Planet Drupal
Updated: 34 min 28 sec ago

Mediacurrent: Communicating Design to Clients

Tue, 29/11/2016 - 22:06

What makes a good designer? Well, of course you have to be creative, understand how to solve problems in unconventional ways, and do it all within budget. But wait, there's more to it than being super creative and solving problems. You must be able to make others understand how your design vision solves their problems.

Categories: Elsewhere

Lullabot: Pull Content From a Remote Drupal 8 Site Using Migrate and JSON API

Tue, 29/11/2016 - 21:02

I wanted to find a way to pull data from one Drupal 8 site to another, using JSON API to expose data on one site, and Drupal’s Migrate with a JSON source on another site to consume it. Much of what I wanted to do was undocumented and confusing, but it worked well, once I figured it out. Nevertheless, it took me several days to get everything working, so I thought I’d write up an article to explain how I solved the problem. Hopefully, this will save someone a lot of time in the future.

I ended up using the JSON API module, along with the REST modules in Drupal Core on the source site. On the target site, I used Migrate from  Drupal Core 8.2.3 along with Migrate Plus and Migrate Tools.

Why JSON API?

Drupal 8 Core ships with two ways to export JSON data. You can access data from any entity by appending ?_format=json to its path, but that means you have to know the path ahead of time, and you’d be pulling in one entity at a time, which is not efficient.

You could also use Views to create a JSON endpoint, but it might be difficult to configure it to include all the required data, especially all the data from related content, like images, authors, and related nodes. And you’d have to create a View for every possible collection of data that you want to make available. To further complicate things, there's an outstanding bug using GET with Views REST endpoints.

JSON API provides another solution. It puts the power in the hands of the data consumer. You don’t need to know the path of every individual entity, just the general path for a entity type, and bundle. For example: /api/node/article. From that one path, the consumer can select exactly what they want to retrieve just by altering the URL. For example, you can sort and filter the articles, limit the fields that are returned to a subset, and bring along any or all related entities in the same query. Because of all that flexibility, that is the solution I decided to use for my example. (The Drupal community plans to add JSON API to Core in the future.)

There’s a series of short videos on YouTube that demonstrate many of the configuration options and parameters that are available in Drupal’s JSON API.

Prepare the Source Site

There is not much preparation needed for the source because of JSON API’s flexibility. My example is a simple Drupal 8 site with an article content type that has a body and field_image image field, the kind of thing core provides out of the box.

First, download and install the JSON API module. Then, create YAML configuration to “turn on” the JSON API. This could be done by creating a simple module that has YAML file(s) in /MODULE/config/optional. For instance, if you created a module called custom_jsonapi, a file that would expose node data might look like:

filename: /MODULE/config/optional/rest.resource.entity.node.yml: id: entity.node plugin_id: 'entity:node' granularity: method configuration: GET: supported_formats: - json supported_auth: - basic_auth - cookie dependency: enforced: module: - custom_jsonapi

To expose users or taxonomy terms or comments, copy the above file, and change the name and id as necessary, like this:

filename: /MODULE/config/optional/rest.resource.entity.taxonomy_term.yml: id: entity.taxonomy_term plugin_id: 'entity:taxonomy_term' granularity: method configuration: GET: supported_formats: - json supported_auth: - basic_auth - cookie dependency: enforced: module: - custom_jsonapi

That will support GET, or read-only access. If you wanted to update or post content you’d add POST or PATCH information. You could also switch out the authentication to something like OAuth, but for this article we’ll stick with the built-in basic and cookie authentication methods. If using basic authentication and the Basic Auth module isn’t already enabled, enable it.

Navigate to a URL like http://sourcesite.com/api/node/article?_format=api_json and confirm that JSON is being output at that URL.

That's it for the source.

Prepare the Target Site

The target site should be running Drupal 8.2.3 or higher. There are changes to the way file imports work that won't work in earlier versions. It should already have a matching article content type and field_image field ready to accept the articles from the other site.

Enable the core Migrate module. Download and enable the Migrate Plus and Migrate Tools modules. Make sure to get the versions that are appropriate for the current version of core. Migrate Plus had 8.0 and 8.1 branches that only work with outdated versions of core, so currently you need version 8.2 of Migrate Plus.

To make it easier, and so I don’t forget how I got this working, I created a migration example as the Import Drupal module on Github. Download this module into your module repository. Edit the YAML files in the /config/optional  directory of that module to alter the JSON source URL so it points to the domain for the source site created in the earlier step.

It is important to note that if you alter the YAML files after you first install the module, you'll have to uninstall and then reinstall the module to get Migrate to see the YAML changes.

Tweaking the Feed Using JSON API

The primary path used for our migration is (where sourcesite.com is a valid site):

http(s)://sourcesite.com/api/node/article?_format=api_json

This will display a JSON feed of all articles. The articles have related entities. The field_image field points to related images, and the uid/author field points to related users. To view the related images, we can alter the path as follows:

http(s)://sourcesite.com/api/node/article?_format=api_json&include=field_image

That will add an included array to the feed that contains all the details about each of the related images. This way we won’t have to query again to get that information, it will all be available in the original feed. I created a gist with an example of what the JSON API output at this path would look like.

To include authors as well, the path would look like the following. In JSON API you can follow the related information down through as many levels as necessary:

http(s)://sourcesite.com/api/node/article?_format=api_json&include=field_image,uid/author

Swapping out the domain in the example module may be the only change needed to the example module, and it's a good place to start. Read the JSON API module documentation to explore other changes you might want to make to that configuration to limit the fields that are returned, or sort or filter the list.

Manually test the path you end up with in your browser or with a tool like Postman to make sure you get valid JSON at that path.

Migrating From JSON

I had a lot of trouble finding any documentation about how to migrate into Drupal 8 from a JSON source. I finally found some in the Migrate Plus module. The rest I figured out from my earlier work on the original JSON Source module (now deprecated) and by trial and error. Here’s the source section of the YAML I ended up with, when migrating from another Drupal 8 site that was using JSON API.

source: plugin: url data_fetcher_plugin: http data_parser_plugin: json urls: http://sourcesite.com/api/node/article?_format=api_json ids: nid: type: integer item_selector: data/ fields: - name: nid label: 'Nid' selector: /attributes/nid - name: vid label: 'Vid' selector: /attributes/vid - name: uuid label: 'Uuid' selector: /attributes/uuid - name: title label: 'Title' selector: /attributes/title - name: created label: 'Created' selector: /attributes/created - name: changed label: 'Changed' selector: /attributes/changed - name: status label: 'Status' selector: /attributes/status - name: sticky label: 'Sticky' selector: /attributes/sticky - name: promote label: 'Promote' selector: /attributes/promote - name: default_langcode label: 'Default Langcode' selector: /attributes/default_langcode - name: path label: 'Path' selector: /attributes/path - name: body label: 'Body' selector: /attributes/body - name: uid label: 'Uid' selector: /relationships/uid - name: field_image label: 'Field image' selector: /relationships/field_image


One by one, I’ll clarify some of the critical elements in the source configuration.

File-based imports, like JSON and XML use the same pattern now. The main variation is the parser, and for JSON and XML, the parser is in the Migrate Plus module:

source: plugin: url data_fetcher_plugin: http data_parser_plugin: json

The url is the place where the JSON is being served. There could be more than one URL, but in this case there is only one. Reading through multiple URLs is still pretty much untested, but I didn’t need that:

urls: http://sourcesite.com/api/node/article?_format=api_json

We need to identify the unique id in the feed. When pulling nodes from Drupal, it’s the nid:

ids: nid: type: integer

We have to tell Migrate where in the feed to look to find the data we want to read. A tool like Postman (mentioned above) helps figure out how the data is configured. When the source is using JSON API, it’s an array with a key of data:

item_selector: data/

We also need to tell Migrate what the fields are. In the JSON API, they are nested below the main item selector, so they are prefixed using an xpath pattern to find them. The following configuration lets us refer to them later by a simple name instead of the full path to the field. I think the label would only come into play if you were using a UI:

fields: - name: nid label: 'Nid' selector: /attributes/nid Setting up the Image Migration Process

For the simple example in the Github module we’ll just try to import nodes with their images. We’ll set the author to an existing author and ignore taxonomy. We’ll do this by creating two migrations against the JSON API endpoint, first one to pick up the related images, and then a second one to pick up the nodes.

Most fields in the image migration just need the same values they’re pulling in from the remote file, since they already have valid Drupal 8 values, but the uri value has a local URL that needs to be adjusted to point to the full path to the file source so the file can be downloaded or copied into the new Drupal site.

Recommendations for how best to migrate images have changed over time as Drupal 8 has matured. As of Drupal 8.2.3 there are two basic ways to process images, one for local images and a different one for remote images.  The process steps are different than in earlier examples I found. There is not a lot of documentation about this. I finally found a Drupal.org thread where the file import changes were added to Drupal core and did some trial and error on my migration to get it working.  

For remote images:

source: ... constants: source_base_path: 'http://sourcesite.com/' process: filename: filename filemime: filemime status: status created: timestamp changed: timestamp uid: uid uuid: id source_full_path: plugin: concat delimiter: / source: - 'constants/source_base_path' - url uri: plugin: download source: - '@source_full_path' - uri guzzle_options: base_uri: 'constants/source_base_path'

For local images change it slightly:

source: ... constants: source_base_path: 'http://sourcesite.com/' process: filename: filename filemime: filemime status: status created: timestamp changed: timestamp uid: uid uuid: id source_full_path: plugin: concat delimiter: / source: - 'constants/source_base_path' - url uri: plugin: file_copy source: - '@source_full_path' - uri

The above configuration works because the Drupal 8 source uri value is already in the Drupal 8 format, http://public:image.jpg. If migrating from a pre-Drupal 7 or non-Drupal source, that uri won’t exist in the source. In that case you would need to adjust the process for the uri value to something more like this:

source: constants: is_public: true ... process: ... source_full_path: - plugin: concat delimiter: / source: - 'constants/source_base_path' - url - plugin: urlencode destination_full_path: plugin: file_uri source: - url - file_directory_path - temp_directory_path - 'constants/is_public' uri: plugin: file_copy source: - '@source_full_path' - '@destination_full_path' Run the Migration

Once you have the right information in the YAML files, enable the module. On the command line, type this:

drush migrate-status

You should see two migrations available to run.  The YAML files include migration dependencies and that will force them to run in the right order. To run them, type:

drush mi --all

The first migration is import_drupal_images. This has to be run before import_drupal_articles, because field_image on each article is a reference to an image file. This image migration uses the path that includes the related image details, and just ignores the primary feed information.

The second migration is import_drupal_articles. This pulls in the article information using the same url, this time without the included images. When each article is pulled in, it is matched to the image that was pulled in previously.

You can run one migration at a time, or even just one item at a time, while testing this out:

drush migrate-import import_drupal_images --limit=1

You can rollback and try again.

drush migrate-rollback import_drupal_images

If all goes as it should, you should be able to navigate to the content list on your new site and see the content that Migrate pulled in, complete with image fields. There is more information about the Migrate API on Drupal.org.

What Next?

There are lots of other things you could do to build on this. A Drupal 8 to Drupal 8 migration is easier than many other things, since the source data is generally already in the right format for the target. If you want to migrate in users or taxonomy terms along with the nodes, you would create separate migrations for each of them that would run before the node migration. In each of them, you’d adjust the include value in the JSON API path to pull the relevant information into the feed, then update the YAML file with the necessary steps to process the related entities.

You could also try pulling content from older versions of Drupal into a Drupal 8 site. If you want to pull everything from one Drupal 6 site into a new Drupal 8 site you would just use the built in Drupal to Drupal migration capabilities, but if you want to selectively pull some items from an earlier version of Drupal into a new Drupal 8 site this technique might be useful. The JSON API module won’t work on older Drupal versions, so the source data would have to be processed differently, depending on what you use to set up the older site to serve JSON. You might need to dig into the migration code built into Drupal core for Drupal to Drupal migrations to see how Drupal 6 or Drupal 7 data had to be massaged to get it into the right format for Drupal 8.

Finally, you can adapt the above techniques to pull any kind of non-Drupal JSON data into a Drupal 8 site. You’ll just have to adjust the selectors to match the format of the data source, and do more work in the process steps to massage the values into the format that Drupal 8 expects.

The Drupal 8 Migrate module and its contributed helpers are getting more and more polished, and figuring out how to pull in content from JSON sources could be a huge benefit for many sites. If you want to help move the Migrate effort forward, you can dig into the Migrate in core initiative and issues on Drupal.org.

Categories: Elsewhere

Drupal Association News: Drupal Association Financial Statements for Q3 2016

Tue, 29/11/2016 - 20:43

We normally share  our financial statements in posts about public board meetings, since that is the time when board members approve the statements. However, I wanted to give this quarter’s update its own blog post. We’ve made many changes to improve our sustainability over the last few months and I am fully embracing our value of communicating with transparency by giving insight into our progress.

First, a word of thanks

We are truly thankful for all the contributions that our community makes to help Drupal thrive. Your contribution comes in the form of time, talent, and treasure and all are equally important. Just as contributing code or running a camp is critical, so is financial contribution.

The Drupal Association is able to achieve its mission to unite the community to build and promote Drupal thanks to those who buy DrupalCon tickets and sponsor the event, our Supporters and Members, Drupal.org sponsors, and talent recruiters who post jobs on Drupal Jobs.

We use these funds to maintain Drupal.org and it’s tooling so the community can build and release the software and so technical evaluators can learn why Drupal is right for them through our new marketing content. It also funds DrupalCon production so we can bring the community together to level up skills, accelerate contribution, drive Drupal business, and build stronger bonds within our community. Plus, it funds Community Cultivation Grants and DrupalCon scholarships, removing financial blockers for those who want to do more for Drupal. And of course, these funds pay staff salaries so we have the right people on board to do all of this mission work.

I also want to thank our board members who serve on the Finance Committee, Tiffany Farris (Treasurer), Dries Buytaert, Jeff Walpole, and Donna Benjamin. They provide financial oversight for the organization, making sure we are the best stewards possible for the funds the community gives to us. I also want to thank Jamie Nau of Summit CPA, our new CFO firm. Summit prepares our financial statements and forecasts and is advising us on long term sustainability.

Q3 Financial Statements

A financial statement is a formal record of the financial activities of the Drupal Association. The financial statements present information in a structured way that should make it easy to understand what is happening with the organization's finances.

Once staff closes the books each month, Summit CPA prepares the financial statement, which the finance committee reviews and approves. Finally, the full Drupal Association Board approves the financial statements. This process takes time, which is why Q3 financials are released in Q4.

You can find the Q3 financial statements here. They explain how The Association used its money in July, August, and September of this year. It takes a little financial background to understand them, so Summit CPA provides an executive summary and they set KPIs so it is clear how we are doing against important financial goals.

The latest executive summary is at the beginning of the September financial statement. In short, it says we are sustainable and on the right path to continue improving our financial health.

“We are working on building an adequate cash reserve balance. As of September a cash balance of $723K is 14% of twelve-months of revenue. Summit recommends a cash reserve of 15%-30% of estimated twelve-month revenue. Since Drupal’s revenue and expenditures drastically fluctuate from month to month [due to DrupalCon] a cash reserve goal closer to 30% is recommended.

Through August we have achieved a Net Income Margin of 4% and a Gross Profit Margin 33%. Our goal is to increase the Net Income Margin to over 10% during the next year.”
- Summit CPA

Improving our sustainability will continue to be an imperative through 2017, so the Association can serve its mission for generations to come. Financial health improvements will be achieved by the savings we gain over time from the staff reductions we did this summer. Another area of focus is improving our programs’ gross margins.

You can expect to see the Q4 2016 financials in Q1 2017. You can also expect to see our 2017 budget and operational focus. We are certainly excited (and thankful) for your support and we look forward to finding additional ways to serve this amazing community in 2017.

Categories: Elsewhere

Agaric Collective: Redirect users after login to the page they were viewing in Drupal 8

Tue, 29/11/2016 - 20:13

Have you ever been asked to log into a website while you are viewing a page? And after doing so you get redirected to some page other than the one you were reading? This is an obvious and rather common usability problem. When this happens people lose track of what they were doing and some might not even bother to go back. Let's find out how to solve this in Drupal 8.

In a recent project a client wisely requested exactly that: whenever a user logs into the site, redirect them to the page they were before clicking the login link. This seemed like a very common request so we looked for a contrib module that provided the functionality. Login Destination used to do it in Drupal 7. Sadly the Drupal 8 version of this module does not provide the functionality yet.

Other modules, and some combinations of them, were tested without success. Therefore, we built Login Return Page. It a very small module that just does one thing and it does it well: it appends destination=/current/page to all the links pointing to /user/login effectively redirecting users to the page they were viewing before login. The project is waiting to be approved before promoting it to full project.

Have you had a similar need? Are there other things you are requested to do after login? Please share them in the comments.

Categories: Elsewhere

Third & Grove: Theming form elements in Drupal 8

Tue, 29/11/2016 - 17:03
Theming form elements in Drupal 8 ross Tue, 11/29/2016 - 11:03
Categories: Elsewhere

Xeno Media: Top Thirteen Drupal Twig Helper Modules

Tue, 29/11/2016 - 16:29

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: Elsewhere

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

Tue, 29/11/2016 - 16:09

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: Elsewhere

ComputerMinds.co.uk: Replacing a vocabulary listing

Tue, 29/11/2016 - 14:00

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: Elsewhere

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

Tue, 29/11/2016 - 07:21
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: Elsewhere

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

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

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

Tue, 29/11/2016 - 03:36
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: Elsewhere

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

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

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

Tue, 29/11/2016 - 03:36
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: Elsewhere

blog.studio.gd: Inline Entity Display

Tue, 29/11/2016 - 03:36
Handle referenced entity fields directly in the parent entity
Categories: Elsewhere

Aten Design Group: Restricting Access to Drupal 8 Controllers

Tue, 29/11/2016 - 00:53

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: Elsewhere

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

Mon, 28/11/2016 - 21:30
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: Elsewhere

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

Mon, 28/11/2016 - 17:30
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: Elsewhere

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

Mon, 28/11/2016 - 14:51

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: Elsewhere

Nuvole: Configuration Split: first beta release at Drupal IronCamp

Mon, 28/11/2016 - 12:30
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: Elsewhere

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

Mon, 28/11/2016 - 11:26
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: Elsewhere

Pages