Planet Drupal

Subscribe to Planet Drupal feed
Drupal.org - aggregated feeds in category Planet Drupal
Updated: 9 hours 49 min ago

Glassdimly tech Blog: 8: Programatically Filter Current Nid from Views Block Listing

25 August 2017 - 2:16pm

Views has a setting to exclude the current nid from the URL from the listing one is currently viewing. This is essential when you have, say, a list of related nodes that are are defined by a category that includes the current node. If you don't exclude the current node, your current node will be listed in the "related content" block on itself. Well, obviously one is related to oneself, one thinks.

First, I tired to accomplish this through the UI with these steps, below.

Categories: Drupal

Drupal core announcements: Proposal to adjust experimental modules process/requirements in response to user/developer feedback

25 August 2017 - 12:51pm

In order to respond to both site builder and developer feedback about core experimental modules in Drupal 8, the committer team is proposing the following changes starting with the Drupal 8.5.x branch (which is now open for development):

  1. Experimental modules that have alpha stability will only be committed to development branches of Drupal 8.
  2. If an experimental module has not achieved at least beta-level stability by the alpha1 release of the branch itself, its development will move to the next development branch and the module will not be included in the branch's alpha release. (Or, alternately, the module may be removed from core if there's no clear path to stability.)
  3. Once an experimental module reaches beta stability, we now require (a) upgrade paths, and (b) backwards compatibility (or a deprecated BC layer) for any API improvements.

For example, if an initiative team wanted to add a new experimental module to core for their desired feature, they could introduce a patch that met the requirements for an experimental module and it could be committed to 8.5.x as an alpha-stability experimental module. However, by 8.5.0-alpha1 (the week of January 17, 2018), either the module would need to be in "beta" level stability (which means its API and data model would be considered stable, with upgrade paths and API BC layers provided when needed), or it would be left in the 8.6.x branch, but removed from the 8.5.x branch before tagging the alpha. 8.5.0 would ship without this new functionality, but (if completed in time) it could be available in the 8.6.0 release.

These policy changes are intended to address a number of frustrations with the existing experimental module process and to better meet expectations for non-core site builders and developers.

For background on this decision or to provide your feedback, see the core policy issue that discusses this proposed change. The issue is open for community feedback until September 6, 2017. Thank you in advance!

Categories: Drupal

Elevated Third: POWDR’s Front End Architecture Build

25 August 2017 - 10:31am
POWDR’s Front End Architecture Build POWDR’s Front End Architecture Build root Fri, 08/25/2017 - 11:31

Powdr Resorts is one of the largest ski operators in North America. Since December, we've spun up nearly a dozen decoupled Drupal website for the holding company including websites for Boreal Mountain Resort, Copper Mountain, Camp Woodward, and more. 

The work was completed with our frontend partners at Hoorooh Digital and hosting partners at Acquia. It is cutting edge and worth diving into so we've put together an eBook style review of the project's parts. 

In prior posts, we've covered Hosting a Decoupled Drupal Site, Decoupled Drupal: A 10,000 ft View, and Decoupled Drupal Technologies and Techniques

In the final installment of our decoupled Drupal series our partner, Denny Cunningham, Lead Front End Developer at Hoorooh Digital, discusses the three main areas that needed to be addressed during the build of POWDR’s front end architecture: Routing & Syncing with the API, Component Driven Content, and the Build Process & Tools. Read the whole piece on Acquia's developer center, here

Categories: Drupal

Mediacurrent: The 3 C's + the 1 D of Drupal: Why Decoupled Matters

25 August 2017 - 6:06am

Whether you are a Digital Marketer looking to adopt Open Source and Drupal for the first time, or an Engineer, Strategist or Project Manager assigned to a Drupal project, it’s critical that you define your approach to the “3 C's" of Drupal: Core, Contrib and Custom.  This decision directly impacts the performance, scalability, and maintenance of the websites and/or other digital assets that you are powering with Drupal.

Categories: Drupal

Himanshu Dixit | Blog: Week 12 : Google Summer Of Code Final Week

25 August 2017 - 4:25am
Week 12 : Google Summer Of Code Final Week himanshu-dixit Fri, 08/25/2017 - 16:55
Categories: Drupal

Jeff Geerling's Blog: Apache, fastcgi, proxy_fcgi, and empty POST bodies with chunked transfer

24 August 2017 - 8:45pm

I've been working on building a reproducible configuration for Drupal Photo Gallery, a project born out of this year's Acquia Build Hackathon.

We originally built the site on an Acquia Cloud CD environment, and this environment uses a pretty traditional LAMP stack. We didn't encounter any difficulty using AWS Lambda to post image data back to the Drupal site via Drupal's RESTful Web Services API.

The POST request is built in Node.js using:

Categories: Drupal

Palantir: Yale University Art Gallery

24 August 2017 - 1:17pm
Yale University Art Gallery brandt Thu, 08/24/2017 - 15:17 Enhancing the Visitor Experience of an Online Collection

Using Drupal to simplify complex publishing needs.

Highlights
  • Increased accuracy and reduced speed of nightly collection imports with updated use of Migrate module

  • Rich search experience provided by Search API module and Facet API module

  • Enhanced event calendar functionality

We want to make your project a success.

Let's Chat. Our Client

The mission of the Yale University Art Gallery is to encourage appreciation and understanding of art and its role in society through direct engagement with original works of art. The gallery’s online collection contains more than 160,000 works, spanning more than 4,000 years of human history. Many of the images in the collection are available for use as part of the University’s Open Access Policy for public domain works.

Goals and Direction

Having launched their new website in Drupal 7, the Gallery was looking to improve its functionality by making the site easier to use and by simplifying their nightly collection synchronization.

The primary high-level goals for the project were to:

  • Streamline collection imports. Provide reliable synchronization from TMS source data to Drupal content nodes
  • Present a searchable collection. Provide end-users with relevant search results across content types and within collections based content
  • Implement faceted search. Provide end-users the ability to refine search results based on key facets which describe the search data
  • Include sortable results. Provide end-users the ability to sort search results when searching collection objects
  • Implement predictive autocomplete for collections search. Provide end-users the ability to see a set of auto-complete options of artist names when searching collection objects
  • Update the event calendar. Provide end-users with the ability to use the site calendar and event system to find relevant upcoming events
Collection Handling

Like many museums, the Gallery strives to put its extensive collection online. At the time of this writing, the Gallery had only 3,800 works on view to the public, with another 160,000 either in storage or available only by appointment. With the collection online, visitors, artists, and researchers can take a deeper dive into the entire catalogue.

For its collection management, the Gallery uses The Museum System (TMS), a Windows desktop application used by more than 800 institutions worldwide. TMS is a proprietary software system that provides its own bespoke web publishing system, and the Gallery wanted a greater level of presentation control than afforded by that system. In particular, the categories used internally at the Gallery needed to be altered when used on the public website.

When Palantir first engaged with the Gallery in September 2014, they were exporting the entire TMS collection nightly and importing it into the Drupal site using the Migrate module. The process was lengthy and error-prone, so our first task was to make the data import more scalable by having the nightly import only respond to records changed in the TMS system since the last import.

The Migrate module supports this feature with the concept of highwater marks. Highwater marks map the imported data to a sortable key in the source data -- typically the last updated date -- and instructs Drupal to only return content that has been changed since the last import. Doing so cut the speed and increased the accuracy of the nightly import, which formed the basis for all further site improvements.

Search

To search the collection, the Gallery installed an Apache SOLR instance, creating search repositories for site content and for the collected works. This dual approach allowed the creation of two distinct search experiences. Overall site search returns collection objects, events, and other content, while the collection search returns a faceted list of collection objects.

Using the Search API module as a base enhanced by the Facet API module, we can provide a rich search experience similar to what one might use on Amazon.com, where search results can be further narrowed by selecting checkboxes that limit the search range. For the Gallery, a search can be filtered by six distinct filters: Department, Classification, Date Made, Culture, Image Available, and Availability in the gallery.

Using the Facet API Slider module, we constructed a custom date widget that allows the user to select a start and end date using a doubled-handled slider.

To create predictive search results, we had to create a custom autocomplete callback to handle the requirement that searches should default to pulling back artist records. (Technical note: since the search field is targeted to the SOLR full text index, the Search API Autocomplete module turned out not to work for this use-case.)

Events

The Gallery hosts numerous public exhibitions and events throughout the year. They play host to a number of traveling exhibitions and need to keep an overall calendar that includes events syndicated from Yale’s central calendar service.

Like the collection search, the calendar includes facets to help visitors narrow the list of results.

The site also tracks upcoming and past exhibitions, serving as a showcase of the breadth of the collection.

The Results

Like many organizations, the Gallery has complex publishing needs and a small staff. A major outcome of our work has been to streamline the production of the site so that it can be automated based on work already being done in external systems. Collections, exhibits, and artist information all flow through the TMS migration, allowing curators to do their work once and not spend extra time managing the website directly.

Streamlined updates aside, the primary result has been the improved experience for Gallery patrons. By improving the search and calendar functionality, visitors are now able to engage easier with the original artwork provided by the Gallery, both online and in-person at events.

We want to make your project a success.

Let's Chat. Drupal Fine Arts Museums of San Francisco artgallery.yale.edu
Categories: Drupal

Lullabot: Contenta - An API First Decoupled Drupal Distribution

24 August 2017 - 1:00pm
Matt and Mike are joined by the creators of Contenta, which is an API first Drupal distribution for decoupling your site's front-end from Drupal.
Categories: Drupal

Elevated Third: Agile With a Lowercase ‘a’: The Art of Collaborative Project Management

24 August 2017 - 12:18pm
Agile With a Lowercase ‘a’: The Art of Collaborative Project Management Agile With a Lowercase ‘a’: The Art of Collaborative Project Management Kylie Forcinito Thu, 08/24/2017 - 13:18

The discovery phase has ended. Your client is excited. The estimate is finalized. Your team is ready to take on the project with an unstoppable ferocity. And then it happens. The lull, the drag, and the ever infamous post discovery hangover. You have the budget, you have the idea, but what next? How do you get the wheels turning to put the machine into motion? How do you keep your work unified?

 

 

Our approach to battle this ever daunting feeling is to implement a system that, once in motion, is an unstoppable, self-maintaining machine. Our goal for each project is to create a unified approach. We implement projects that satisfy client contract and budget needs while keeping collaboration a priority.

This approach is not like most agile processes. We coin it agile* *with a lowercase ‘a,’ because we use the most basic concepts of the agile manifesto as a guide without creating a rigid system. The core of the process is the same but it is more scalable and adaptable to each project and project team.

Our goal is to grab the best parts of agile and modify it to fit the needs of the project, team, and client partners.

Not every project, client, or internal team is the same, so we don’t expect success out of a one size fits all process.

The Players

Collaborative project management. Think Moneyball. You don’t need a superstar in any single role, you just need to know the positions you need to fill and help your team to play off one another’s strengths. Each team member needs to understand their role, responsibility, expectations, and how to make an impact on the project.

 

 

“The best architectures, requirements and designs emerge from self-organizing teams.” -The Twelve Principles of Agile Software

The Recipe

How do you set-up teams to self-manage? That’s where the beauty of the agile framework lends stability to the process. Our approach is to take the values of agile development and bend them to fit our process.

Below is our approach to a successful implementation phase based on our interpretation of the Agile Manifesto.

Meetings and communication

Individuals and interactions over processes and tools.

1. Find tools that support your workflow versus hinder your production. Predictability is a good thing when it comes to communication. You don’t want to waste 5 minutes of a 15 minute standup figuring out what the call in number is. Communication tool consistency enables communication efficiency.

2. Support your remote team members and keep consistency with your communication tools. At Elevated Third, we leverage Slack for quick communication between team members. We also use Slack call and screen share features when working with remote teams. Communication is direct and streamlined.

3. Prioritize straight talk and develop a shared understanding of expectations with the project team.

4. Only include necessary team members in the right conversations. Plan focused, short meetings with only the relevant team members maximize the effectiveness of the meeting. We use 15 minute standups to discuss what each team member is working on that day. Each team member is allowed 2 minutes, and anything outside of the 2 minutes is addressed in a separate conversation with the necessary individuals. This method keeps one issue from monopolizing the standup time and keeps the project moving forward.

5. Share a live demo of the work to keep the full team involved with the project progress. It is crucial that the team is on the same page before the client demo.

 

 

6. Review with your client team to keep them actively involved throughout the project. This gives them the opportunity to share priority level of features during each phase of the project versus all at once at the very end (which could impact the budget).

Planning and Scoping

Customer collaboration over contract negotiation.

1. Coach your clients to be a partner. It’s important to involve clients in sprint planning and feature prioritization process from the very beginning. It helps them understand how to be a partner in the project and what the expectations are from the onset.

2. Align on project feature priorities and budget with stakeholders. Internal and client teams should be aligned on feature priorities and budget before the implementation begins. Set the team and project up for success by starting on the same page with the same expectations. Don’t set sail when the boat isn’t built.

 

 

3. Use project management tools to aid in efficiency. Efficient, simple task/budget management is invaluable. The project management tools should assist in budget and sprint management. At Elevated Third, we use Mavenlink for budget and hours tracking and Asana to keep our sprints and tasks planned during implementation.  

Documentation

Working software over comprehensive documentation.

1. Find the right balance of shared understanding and documentation for the project. Not every project will need the same type of documentation - especially when it comes to designs. Find the level of documentation needed to keep the project moving forward.

2. Prioritize living documents that are maintained and useful over throw away deliverables. At Elevated Third, we have a set of requirements that we consistently use and scale for each project.

  • User Stories - prioritize functionality

  • Risk Mitigation - document possible impacts to budget/timeline

  • Build Spec - Provide accessible content architecture plan

  • Features Estimate - Show a full list of features with estimated ranges

  • Wireframes and Styleguide/Designs - Demonstrate look and feel

  Balance the Big Picture and the Details

Responding to change over following a plan.

1. Keep your plan fluid, and don’t be discourage by or afraid of change. Embrace the change and focus on creating solutions that bring the team together for a better outcome. Projects evolve, and successful projects adapt.

2. Set aside time to take on specific problems. Project management is a balancing act. We are required to keep everyone moving while continuously working through blockers. When a potential blocker arises, address it with the key members and stakeholders as quickly as possible so the project can keep moving forward and stay on track.

Testing

Don’t bring an opinion to a data fight.

1. When implementation is complete, it’s critical to set aside time for testing. Take the time to ensure the system works together as intended for each user.

2. For successful testing make sure the client team and the project team are testing from the same documentation and that the testing only pertains to the functionality that was prioritized for the project.  

Keep Up the Momentum

Don’t fizzle out after the site has launched.

1. Be a strategic partner post launch by tracking analytics and making recommendations based on the original project and business goals.

 

 

2. Keep track of features that were out of scope for the initial phase of the project, and prioritize them for future phases.

3. Create a maintenance release cycle to iteratively improve the website or product that was built.

 

The “highest priority is to satisfy the customer through early and continuous delivery of valuable software.” - The Twelve Principles of Agile Software

This blog post was adapted from a presentation at DrupalCon Baltimore 2017. You can watch the full talk here

Categories: Drupal

Chiranjeeb Mahanta | Blog: GSoC’17 Coding period | Week #12 | Uc Wishlist

24 August 2017 - 12:08pm
GSoC’17 Coding period | Week #12 | Uc Wishlist chiranjeeb2410 Thu, 08/24/2017 - 15:08
Categories: Drupal

Acquia Developer Center Blog: Grab Your Space in the Fall Session of the Drupal 8 Immersion Online Course

24 August 2017 - 11:55am

Here in Acquia Learning Services we just completed our first session of the Drupal 8 Developer Immersion Course w/ Certification prep – it was a great success!

Led by teacher Dallas Ramsden, 15 brave souls dug into D8 all summer with project-based learning and weekly virtual classrooms. The course just wrapped and students are already passing the D8 Developer exam.

We're kicking off the next session the week of September 5th: Reserve your space by this weekend to save $400.

Tags: acquia drupal planet
Categories: Drupal

Texas Creative: Impressions of Drupal 8 as a New Developer

24 August 2017 - 9:26am

I started in web development about a year ago. When I was hired on at Texas Creative in early October of 2016, I still only knew the bare minimum but was eager to learn more to further my career path. Here at Texas Creative, we use Drupal, a CMS I had no prior experience in. The idea of that seemed daunting, but I’ve certainly learned a lot and have grown to love Drupal. 

Read More
Categories: Drupal

Evolving Web: Migrating Aliases and Redirects to Drupal 8

24 August 2017 - 7:00am

When content URLs change during migrations, it is always a good idea to do something to handle the old URLs to prevent them from suddenly starting to throw 404s which are bad for SEO. In this article, we'll discuss how to migrate URL aliases provided by the path module (part of D8 core) and URL redirects provided by the redirect module.

The Problem

Say we have two CSV files (given to us by the client):

The project requirement is to:

  • Migrate the contents of article.csv as article nodes.
  • Migrate the contents of category.csv as terms of a category terms.
  • Make the articles accessible at the path blog/{{ category-slug }}/{{ article-slug }}.
  • Make blog/{{ slug }}.php redirect to article/{{ article-slug }}.

Here, the term slug refers to a unique URL-friendly and SEO-friendly string.

Before We Start Migrate Node and Category Data

This part consists of two simple migrations:

The article data migration depends on the category data migration to associate each node to a specific category like:

# Migration processes process: ... field_category: plugin: 'migration_lookup' source: 'category' migration: 'example_category_data' no_stub: true ...

So, if we execute this migration, we will have all categories created as category terms and 50 squeaky new nodes belonging to those categories. Here's how it should look if we run the migrations using drush:

$ drush migrate-import example_article_data,example_category_data Processed 5 items (5 created, 0 updated, 0 failed, 0 ignored) - done with 'example_category_data' Processed 50 items (50 created, 0 updated, 0 failed, 0 ignored) - done with 'example_article_data'

Additionally, we will be able to access a list of articles in each category at the URL blog/{{ category-slug }}. This is because of the path parameter we set in the category data migration. The path parameter is processed by the path module to create URL aliases during certain migrations. We can also use the path parameter while creating nodes to generate URL aliases for those nodes. However, in this example, we will generate the URL aliases in a stand-alone migration.

Generate URL Aliases with Migrations

The next task will be to make the articles available at URLs like /blog/{{ category-slug }}/{{ article-slug }}. We use the example_article_alias migration to generate these additional URL aliases. Important sections of the migration are discussed below.

Source source: plugin: 'csv' path: 'article.csv' ... constants: slash: '/' source_prefix: '/node/' alias_prefix: '/blog/' und: 'und'

We use the article.csv file as our source data to iterate over articles. Also, we use source/constants to define certain data which we want to use in the migration, but we do not have in the CSV document.

Destination destination: plugin: 'url_alias'

Since we want to create URL aliases, we need to use the destination plugin url_alias provided by the path module. Reading documentation or taking a quick look at the plugin source at Drupal\path\Plugin\migrate\destination\UrlAlias::fields(), we can figure out the fields and configuration supported by this plugin.

Process ... temp_nid: plugin: 'migration_lookup' source: 'slug' migration: 'example_article_data' ... temp_category_slug: # First, retrieve the ID of the taxonomy term created during the "category_data" migration. - plugin: 'migration_lookup' source: 'category' migration: 'example_category_data' # Use a custom callback to get the category name. - plugin: 'callback' callable: '_migrate_example_paths_load_taxonomy_term_name' # Prepare a url-friendly version for the category. - plugin: 'machine_name'

Since we need to point the URL aliases to the nodes we created during the article data migration, we use use the migration_lookup plugin (formerly migration) to read the ID of the relevant node created during the article data migration. We store the node id in temp_nid. I added the prefix temp_ to the property name because we just need it temporarily for calculating another property and not for using it directly.

Similarly, we need to prepare a slug for the category to which the node belongs. We will use this slug to generate the alias property.

source: plugin: 'concat' source: - 'constants/source_prefix' - '@temp_nid'

Next, we generate the source, which is the path to which the alias will point. We do that by simply concatenating '/nid/' and '@temp_nid' using the concat plugin.

alias: plugin: 'concat' source: - 'constants/alias_prefix' - '@temp_category_slug' - 'constants/slash' - 'slug'

And finally, we generate the entire alias by concatenating '/article/', '@temp_category_slug', a '/' and the article's '@slug'. After running this migration like drush migrate-import example_article_alias, all the nodes should be accessible at /article/{{ category-slug }}/{{ article-slug }}.

Generate URL Redirects with Migrations

For the last requirement, we need to generate redirects, which takes us to the redirect module. So, we create another migration named example_article_redirect to generate redirects from /blog/{{ slug }}.php to the relevant nodes. Now, let's discuss some important lines of this migration.

Source constants: # The source path is not supposed to start with a "/". source_prefix: 'blog/' source_suffix: '.php' redirect_prefix: 'internal:/node/' uid_admin: 1 status_code: 301

We use source/constants to define certain data which we want to use in the migration, but we do not have in the CSV document.

Destination destination: plugin: 'entity:redirect'

In Drupal 8, every redirect rule is an entity. Hence, we use the entity plugin for the destination.

Process redirect_source: plugin: 'concat' source: - 'constants/source_prefix' - 'slug' - 'constants/source_suffix'

First, we determine the path to be redirected. This will be the path as in the old website, example, blog/{{ slug }}.php without a / in the front.

redirect_redirect: plugin: 'concat' source: - 'constants/redirect_prefix' - '@temp_nid'

Just like we did for generating aliases, we read node IDs from the article data migration and use them to generate URIs to which the user should be redirected when they visit one of the /blog/{{ slug }}.php paths. These destination URIs should be in the form internal:/node/{{ nid }}. The redirect module will intelligently use these URIs to determine the URL alias for those paths and redirect the user to the path /article/{{ slug }} instead of sending them to /node/{{ nid }}. This way, the redirects will not break even if we change the URL alias for a particular node after running the migrations.

# We want to generate 301 permanent redirects as opposed to 302 temporary redirects. status_code: 'constants/status_code'

We also specify a status_code and set it to 301. This will create 301 permanent redirects as opposed to 302 temporary redirects. Having done so and having run this third migration as well, we are all set!

Migration dependencies migration_dependencies: required: - 'example_article_data'

Since the migration of aliases and the migration of redirects both require access to the ID of the node which was generated during the article data migration, we need to add the above lines to define a migration_dependency. It will ensure that the example_article_data migration is executed before the alias and the redirect migrations. So if we run all the migrations of this example, we should see them executing in the correct order like:

$ drush mi --tag=example_article Processed 5 items (5 created, 0 updated, 0 failed, 0 ignored) - done with 'example_category_data' Processed 50 items (50 created, 0 updated, 0 failed, 0 ignored) - done with 'example_article_data' Processed 50 items (50 created, 0 updated, 0 failed, 0 ignored) - done with 'example_article_alias' Processed 50 items (50 created, 0 updated, 0 failed, 0 ignored) - done with 'example_article_redirect'Next steps + more awesome articles by Evolving Web
Categories: Drupal

Acquia Developer Center Blog: Decoupled Drupal: POWDR’s Front End Architecture Build

24 August 2017 - 6:46am

In this article we’ll discuss the three main areas that needed to be addressed during the build of POWDR’s front end architecture: Routing & Syncing with the API, Component Driven Content, and the Build Process & Tools.

Tags: acquia drupal planet
Categories: Drupal

Chromatic: Announcing our Drupal Coding Standards Series on Drupalize.me!

24 August 2017 - 6:30am

The folks at Drupalize.me provide the best Drupal training materials on the web, so we were more than happy to oblige them when they asked if they could release our Coding Standards guide as a free series on their platform.

Categories: Drupal

Agiledrop.com Blog: AGILEDROP: Web Accessibility in Drupal 8 – part 2

24 August 2017 - 2:48am
This blog post is the second part of the session Web accessibility in Drupal 8 from our Development director Bostjan Kovac. We will look at the most common mistakes developers make, Drupal Contrib modules and other tools that will help you out when it comes to web accessibility. If you have missed the first part, you can read it here. Most common mistakes developers make Simple markup: And then there is a classy theme: The Ignorant theme (Bostjan called it that way) with no HTML elements, no roles for each element, nothing the screen readers should help themselves with. That means that… READ MORE
Categories: Drupal

Amazee Labs: Extending GraphQL: Part 2 - Types and Interfaces

24 August 2017 - 1:27am
Extending GraphQL: Part 2 - Types and Interfaces

After successfully creating a field with arguments and context, we are going to have a look at types and interfaces in GraphQL and how they help to build complex, yet self-documenting and type safe schemas.

Philipp Melab Thu, 08/24/2017 - 10:27

The last blog post in this series culminated in the epic achievement of adding a "page title" field to every URL object in our schema. Now we can request the page title for every internal URL. But menus and link fields can also store external addresses.

Wouldn't it be cool if we can request their page title's just the same way?

Overriding a field

Let's try it and ask questions later:

query { route(path: "http://www.drupal.org") { pageTitle } }

Unfortunately, this doesn't work out. The route field checks if the provided path is a Drupal route and if the user has access to it, and will return null if either of the two doesn't apply. So, the first thing we will do is extend the route field so it also can handle external URLs.

Note: At the time of writing there is a pending pull request that adds exactly this enhancement. If you are reading this in a couple of weeks from now (my now, not yours - unless you own a DeLorean), there's a chance that this already works for you. But since this is a nice example of overriding a field, we stick with it. If you don't just want to read but really play through this tutorial, make sure you work based on the 8.x-3.0-alpha3 version of the GraphQL module.

We create a new field called ExampleRoute in our graphql_example module. If you are not yet proud owner of one, please refer to the last blog post. This new field simply extends the existing Route field and even copies its annotation.

With one difference: We add a new property called weight which we set to "1". It's quite simple. When the schema builder assembles all field plugins for a given type and stumbles upon two with the same name, the higher weight takes precedence. That's how we tell GraphQL to use our custom implementation of a field.

The resolveValues method checks if the path is an external Url. In this case, it just constructs a Url object, else it will pass down to the parent implementation.

The result is still not satisfying. The route field now returns an Url object, but our page title field can only retrieve internal page titles.

So let's modify the PageTitle field. First, we check if the current value is a routed URL. In this case, we still leave it to the title resolver. Otherwise, we fire up Drupal's http_client (aka Guzzle), fetch the content behind the address, load it into an XML document, search for the title element and yield its contents. I am aware that this is not the most performant solution, but I'm trying to keep these examples short and concise.

It worked. Our query for an external page title yields the correct result.

{ "data": { "route": { "pageTitle": "Drupal - Open Source CMS | Drupal.org" } } }

The result is correct, but it doesn't feel right. Internal and external URLs are fundamentally different. The page title might make sense on both, but the similarities end there. External URLs won't route to an entity or provide any other information specific to Drupal. These fields won't break and will just return NULL instead, but that doesn't seem very elegant.

Diff: Page title of external URLs

Interfaces and Types

We have already met the Url type, and we know that it connects a certain value with a list of fields that can be executed on it. A GraphQL interface is in some ways similar to interfaces in an object oriented language. It gives a group of types with shared fields a common name.
Right now we've got the Url type provided by the GraphQL module, representing internal URLs (not 100% true, but for the sake of simplicity we leave it there). And we have our external URL which is emitted by the same route field, but operates differently. So what we need to do now:

  1. Create a GraphQL interface called GenericUrl
  2. Change the route field to return this interface instead.
  3. Attach our pageTitle field to this interface.
  4. Add a ExternalUrl GraphQL type that implements this interface.
Creating the interface

GraphQL interfaces live in their own plugin namespace Plugin\GraphQL\Interfaces where the schema builder will pick them up.

The plugin annotation for interfaces is quite simple. In most cases, it consists of the plugin id and a name to be used within the schema. The base class for interfaces contains an abstract method: resolveType. This method will receive a runtime value and has to select the appropriate GraphQL type for it. In our case, it checks if the URL is external or not and uses the schema manager service to return an instance of either Url or ExternalUrl.

Using the interface

This won't have any effect as long as we don't use this interface type somewhere. So we change the pageTitle field to attach it to the GenericUrl instead of Url and adapt our override of the route field to return a GenericUrl.

Creating the new type

The new type we need is rather simple. It's an empty class, extending TypePluginBase. The most important part is the annotation that defines a list of interfaces. Just the GenericUrl interface in our case.

GraphQL type source

Diff: Generic Url interfaces

Now our query still works. But there is a new problem. Internal URLs don't work anymore but emit an error message instead:

Type "Url" does not implement "GenericUrl"

We need to adapt the of the Url type, which is defined in another module. Sounds like a job for the hero we don't deserve, but we need right now. You can't say Drupal without screaming hook_alter from the top of your lungs!

Altering plugins

There's an alter hook for each plugin type in GraphQL. So, all we need is to implement hook_graphql_types_alter and add the GenericUrl interface to the Url types interface list.
Note that the types are indexed by their plugin-ID.

Diff: Altering existing plugins

Great! Now we are able to fetch page titles from both internal and external urls.

query { admin:route(path: "/admin") { pageTitle } drupal:route(path: "http://www.drupal.org") { pageTitle } }

Will return:

{ "data": { "admin": { "pageTitle": "Administration" }, "drupal": { "pageTitle": "Drupal - Open Source CMS | Drupal.org" } } }

But you will notice that we lost all the other fields attached to the Url type. Thats because they are not attached to the GenericUrl type, but to the Url type. And that makes sense, since you can't request for example an entity or the current user context for an external path.

Query composition and fragment selection

And this brings us to the most important and powerful aspect of interfaces and types. We are able to apply different query fragments and fetch different information based on the result type.

Assume the following scenario: Our Article type has a Links field that can contain links to either other articles or external URLs, as well as a Description field. Additionally, we extended our ExternalUrl type with an additional meta field that pulls meta tags out of the XML tree (Bonus objective: implement that yourself). Now we could do this:

query { route(path: "/node/1") { ... on Url { nodeContext { ... on NodeArticle { fieldLinks { url { pageTitle ...InternalLink ...ExternalLink } } } } } } } fragment InternalLink on Url { nodeContext { ... on NodeArticle { description:fieldDescription } } } fragment ExternalLink on ExternalUrl { description:meta(property: "og:description") }

The first part simply routes to the article with id 1 and fetches it's Links field, which will emit a list of URLs that might be internal or external. There we first pull the common page title and then include two fragments that apply on either type of URL and invoke different fields based on that information. So elegant!

The finish line

We've reached the (preliminary) end of our streak of practical GraphQL blog posts. Next up will be a peek into the future of the GraphQL module with planned features and possible use cases. But if you are interested in more advanced topics like performance optimisation, caching or deeper integration with Drupal subsystems (fields, views, contexts ...) ping me @pmelab and I'll see what I can do.

Categories: Drupal

Enzolutions: The Drupal Console Journey

23 August 2017 - 5:00pm

Before the existence of the Drupal Console as a project, it all began with an idea to make Drupal 8 better. Every great invention/innovation begins with an idea, and the Drupal transition from 7 to 8 came with massive changes to the fundamental operating procedures of yesterday. Symfony components were making a splash into Drupal Core. Jesus and David, the initiators of Drupal Console project, came up with the idea of including the symfony console into the Drupal core. The same way that other symfony components were being included into the Drupal core.

Powering Though Frustration

As helpful as the Drupal Console project is nowadays, it wasn’t very widely accepted into the drupal community initially. In fact, it turned out to be a huge challenge to get anyone to listen to the idea. For Jesus and David, the primary objective to include the Symfony Console in Drupal was to have the option to have code generators, in the same way, the Symfony community does. Who wouldn’t want that? A way to automate the annoying redundancies that plague developers everywhere. So they decided to propose the idea to the Drupal core maintainers via the issue queue. That idea was however quickly dismissed.

After few attempts to request the inclusion and trying to collaborate into different drupal projects, it dawned on Jesus and David that inclusion and collaboration was not going to happen. They needed to regroup and find a better approach.

While at lunch at Drupalcamp Costa Rica, Jesus and David were casually discussing the frustrations they had encountered trying to bring innovation to Drupal and related projects, and Larry Garfield chimed in “someone needs to create a separate project that includes Symfony Console and code generation”. That sentence gave birth to the Drupal Console project as you know it today.

Building A Community

Jesus stacked up his calendar with almost every Drupal event in the U.S. The goal was to talk about the project in sessions at all Drupal community gatherings he could physically attend, or at minimum, present the idea at BOFs where sessions were not possible. The code sprints helped him interact with developers and users forming a critical source of feedback.

Along the way, he convinced me to join the project as a maintainer. I also embarked on his outreach campaign to help spread the word. Only, my campaign was global because it was important to reach non-english speakers because they often feel left out of major open source projects. Currently, the Drupal Console project is available, with some variations, in the 18 languages listed below.

  • English
  • Spanish
  • Catalán
  • French
  • Korean
  • Hindi
  • Hungarian
  • Indonesian
  • Japanese
  • Marathi
  • Punjabi
  • Brazilian Portuguese
  • Romanian
  • Russian
  • Tagalog
  • Vietnamese
  • Chinese Simplified
  • Chinese Traditional
One Million Downloads!

After four years of development in July 2017, we reached our first million downloads across different releases. This achievement is thanks to our more that 250 contributors across the globe.

This brought a great sense of validation for deciding to stick to our guns, do the right thing and most importantly... be globally inclusive.

Categories: Drupal

Larry Garfield: Best practices are contextual

23 August 2017 - 3:51pm
Best practices are contextual

Articles, blog posts, and Twitter debates around "best practices" abound. You can't swing a dead cat without bumping into some article espousing the benefits of designing and building software a certain way. (Side note: What kind of sick person are you that you're swinging a dead cat around? Stop that! You're desecrating the dead!)

Larry 23 August 2017 - 6:51pm
Categories: Drupal

Glassdimly tech Blog: Drupal 8: How to Get Image Style Tokens for Metatags

23 August 2017 - 3:15pm

It turns out that image style tokens are an easter egg of the regular Token module, ported in from the Imagecache Token module on this ticket.

Image style tokens don't show up in the media browser, and so you sort of have to guess at how to use them. I figured it out by studying the merged commit that added the functionality.

Categories: Drupal

Pages