Drupal Feeds

Roy Scholten: 17

Feeds from Drupal.org - Mon, 2018-01-15 21:34
15 Jan 2018 17 ||||| ||||| ||||| |¡

Drupal is 17 years old today. Quite an achievement for a web software to stay around, let alone stay relevant for such a long time.

I’ve been around for 12 years. Quite a stretch as well. Getting involved in this open source project as a designer has taught and brought me a lot. I put quite a bit into it as well.

I get a lot of benefits from things I learned in Drupal that I can apply in other contexts.

  • Provide rationale for design decisions. So much typing in issue queue comments!
  • Help people see the other’s point of view and then come to a shared decision.
  • Or agree to disagree, then still make a choice.
  • An appreciation and at least a “gist of things” knowledge of the complexity of software development. It helps with clarifying scope, finding a good place to start, and understanding what is difficult and what can be relatively straight forward.
  • Pragmaticism over purism
  • Edge cases are important
  • There’s a difference between patience and stubborness
  • Accessibility, multilingual, extensibility, modularity are hard but worth it
  • If you can’t imagine why somebody would want do do X, it’s always from a lack of imagination from your part
  • There’s always so much more to do
  • There’s only so much you can do
  • When you start taking things personal it’s probably time to take a break
  • It’s amazing what people can get done when driven by a passion for doing a good thing and doing it well.

… and many returns!

Tags drupal drupalplanet open source
Categories: Straight From Drupal

Doug Vann: Adding regular text into the Drupal Date Format field

Planet Drupal - Mon, 2018-01-15 16:31

Q: "Can you add simple text to a Date Format value in Drupal?" A: YES! [This was news to me]
Preamble:
I was teaching a Drupal 8 class last week and a student asked if we could enter regular text [like the word "date"] into the Date Formate field. I tried it and, of course, some of the letters were translated into PHP Date elements rather than showing all the letters for the word "date."
Ex: "date : M-d-y" became "15am31America/Indiana/Indianapolis : Jan-15-2018" but what we wanted was "date : Jan-15-2018"

It was at this point that I got the bright idea to ESCAPE the letters by adding a BackSlash "\" infront of each letter. SURE ENOUGH!! Now I could see each letter instead of the date translation that each letter stood for.
So... I made this quick video to share with the world just incase someone else can benefit from this discovery!

p.s. I'm quite sure MANY have been using this "trick" for years. But I was excited to discover it on my own after a student brought the idea up! :-)

Link to video http://www.youtube.com/watch?v=gJO0t-KkjX0

VideosDrupal Planet

View the discussion thread.

Doug Vann: Adding regular text into the Drupal Date Format field

Feeds from Drupal.org - Mon, 2018-01-15 16:31

Q: "Can you add simple text to a Date Format value in Drupal?" A: YES! [This was news to me]
Preamble:
I was teaching a Drupal 8 class last week and a student asked if we could enter regular text [like the word "date"] into the Date Formate field. I tried it and, of course, some of the letters were translated into PHP Date elements rather than showing all the letters for the word "date."
Ex: "date : M-d-y" became "15am31America/Indiana/Indianapolis : Jan-15-2018" but what we wanted was "date : Jan-15-2018"

It was at this point that I got the bright idea to ESCAPE the letters by adding a BackSlash "\" infront of each letter. SURE ENOUGH!! Now I could see each letter instead of the date translation that each letter stood for.
So... I made this quick video to share with the world just incase someone else can benefit from this discovery!

p.s. I'm quite sure MANY have been using this "trick" for years. But I was excited to discover it on my own after a student brought the idea up! :-)

Link to video http://www.youtube.com/watch?v=gJO0t-KkjX0

VideosDrupal Planet

View the discussion thread.

Categories: Straight From Drupal

Personalize Location Context

Latest Drupal Modules - Mon, 2018-01-15 16:02
INTRODUCTION

This module provides personalize contexts based on location data loaded
Smart IP module. There are two available contexts for now:

  • Country
  • City

Based on options for each of those contexts it is possible to setup
showing personalized content. Learn more about personalize README.txt
and project page of personalize module.

REQUIREMENTS

This module requires the following module(s):

Categories: Straight From Drupal

Dries Buytaert: Happy seventeenth birthday Drupal

Planet Drupal - Mon, 2018-01-15 15:52

Seventeen years ago today, I open-sourced the software behind Drop.org and released Drupal 1.0.0. When Drupal was first founded, Google was in its infancy, the mobile web didn't exist, and JavaScript was a very unpopular word among developers.

Over the course of the past seventeen years, I've witnessed the nature of the web change and countless internet trends come and go. As we celebrate Drupal's birthday, I'm proud to say it's one of the few content management systems that has stayed relevant for this long.

While the course of my career has evolved, Drupal has always remained a constant. It's what inspires me every day, and the impact that Drupal continues to make energizes me. Millions of people around the globe depend on Drupal to deliver their business, mission and purpose. Looking at the Drupal users in the video below gives me goosebumps.

Drupal's success is not only marked by the organizations it supports, but also by our community that makes the project more than just the software. While there were hurdles in 2017, there were plenty of milestones, too:

  • At least 190,000 sites running Drupal 8, up from 105,000 sites in January 2016 (80% year over year growth)
  • 1,597 stable modules for Drupal 8, up from 810 in January 2016 (95% year over year growth)
  • 4,941 DrupalCon attendees in 2017
  • 41 DrupalCamps held in 16 different countries in the world
  • 7,240 individual code contributors, a 28% increase compared to 2016
  • 889 organizations that contributed code, a 26% increase compared to 2016
  • 13+ million visitors to Drupal.org in 2017
  • 76,374 instance hours for running automated tests (the equivalent of almost 9 years of continuous testing in one year)

Since Drupal 1.0.0 was released, our community's ability to challenge the status quo, embrace evolution and remain resilient has never faltered. 2018 will be a big year for Drupal as we will continue to tackle important initiatives that not only improve Drupal's ease of use and maintenance, but also to propel Drupal into new markets. No matter the challenge, I'm confident that the spirit and passion of our community will continue to grow Drupal for many birthdays to come.

Tonight, we're going to celebrate Drupal's birthday with a warm skillet chocolate chip cookie topped with vanilla ice cream. Drupal loves chocolate! ;-)

Note: The video was created by Acquia, but it is freely available for anyone to use when selling or promoting Drupal.

Dries Buytaert: Happy seventeenth birthday Drupal

Feeds from Drupal.org - Mon, 2018-01-15 15:52

Seventeen years ago today, I open-sourced the software behind Drop.org and released Drupal 1.0.0. When Drupal was first founded, Google was in its infancy, the mobile web didn't exist, and JavaScript was a very unpopular word among developers.

Over the course of the past seventeen years, I've witnessed the nature of the web change and countless internet trends come and go. As we celebrate Drupal's birthday, I'm proud to say it's one of the few content management systems that has stayed relevant for this long.

While the course of my career has evolved, Drupal has always remained a constant. It's what inspires me every day, and the impact that Drupal continues to make energizes me. Millions of people around the globe depend on Drupal to deliver their business, mission and purpose. Looking at the Drupal users in the video below gives me goosebumps.

Drupal's success is not only marked by the organizations it supports, but also by our community that makes the project more than just the software. While there were hurdles in 2017, there were plenty of milestones, too:

  • At least 190,000 sites running Drupal 8, up from 105,000 sites in January 2016 (80% year over year growth)
  • 1,597 stable modules for Drupal 8, up from 810 in January 2016 (95% year over year growth)
  • 4,941 DrupalCon attendees in 2017
  • 41 DrupalCamps held in 16 different countries in the world
  • 7,240 individual code contributors, a 28% increase compared to 2016
  • 889 organizations that contributed code, a 26% increase compared to 2016
  • 13+ million visitors to Drupal.org in 2017
  • 76,374 instance hours for running automated tests (the equivalent of almost 9 years of continuous testing in one year)

Since Drupal 1.0.0 was released, our community's ability to challenge the status quo, embrace evolution and remain resilient has never faltered. 2018 will be a big year for Drupal as we will continue to tackle important initiatives that not only improve Drupal's ease of use and maintenance, but also to propel Drupal into new markets. No matter the challenge, I'm confident that the spirit and passion of our community will continue to grow Drupal for many birthdays to come.

Tonight, we're going to celebrate Drupal's birthday with a warm skillet chocolate chip cookie topped with vanilla ice cream. Drupal loves chocolate! ;-)

Note: The video was created by Acquia, but it is freely available for anyone to use when selling or promoting Drupal.
Categories: Straight From Drupal

OSTraining: Create Charts in Drupal 8 with Views

Planet Drupal - Mon, 2018-01-15 14:50
Create Charts in Drupal 8 with Views

There are many ways to present data to your readers. One example would be a table or a list. Sometimes you would rather prefer to enhance such data with a graphical chart. 

It can ease understanding of large quantities of data. There is a way to make charts in Drupal with the help of the Charts module and Views.

In this tutorial, you will learn the basic usage of the module in combination with the Google Charts library. Let’s start!

OSTraining: Create Charts in Drupal 8 with Views

Feeds from Drupal.org - Mon, 2018-01-15 14:50
Create Charts in Drupal 8 with Views

There are many ways to present data to your readers. One example would be a table or a list. Sometimes you would rather prefer to enhance such data with a graphical chart. 

It can ease understanding of large quantities of data. There is a way to make charts in Drupal with the help of the Charts module and Views.

In this tutorial, you will learn the basic usage of the module in combination with the Google Charts library. Let’s start!

Categories: Straight From Drupal

Atenea tech blog: Agilizando el desarrollo Drupal con Lando: make local development great again!

Feeds from Drupal.org - Mon, 2018-01-15 14:43

En muchas ocasiones nos encontramos peculiaridades de cada entorno que pueden causar incidencias cuando el entorno cambia, por ejemplo cuando ponemos una web en producción o cuando implementamos ciertos cambios en una web que ya está en producción, las diferencias entre el entorno que se uso para desarrollar y el entorno de producción son causa de incertidumbre, y en ocasiones pueden ser también causa de dolores de cabeza y de tiempo invertido innecesariamente. Versiones de php, motores de base de datos, apache, nginx, varnish, etc. pueden convertirse en una gran molestia si no lo tenemos en cuenta desde el principio y si no disponemos de un entorno adaptado a las peculiaridades de cada proyecto.

Para minimizar esta incertidumbre, una buena práctica consiste en usar un entorno de desarrollo que sea lo más parecido posible al entorno donde va a estar publicado el proyecto, y en este sentido un sistema de virtualización por containers como docker resulta de gran ayuda. La contrapartida es que añade un punto de complejidad técnica para el que no siempre tenemos tiempo. No todos tenemos los conocimientos o la disponibilidad para pelearnos con docker, y en este sentido una capa de abstracción como Lando puede ser justo lo que necesitamos. Queremos un asistente que nos permita tener nuestro container listo de inmediato para poder empezar a trabajar en el proyecto, y queremos poder cambiar cualquier cosa del setup en cualquier momento sin perder tiempo.

Lando es el heredero de kalabox, una aplicación con interfaz gráfica y de consola para ayudar en el desarrollo local contra pantheon. Debido a la complejidad técnica y la limitación del alcance de la aplicación, sus desarrolladores decidieron abandonarla y emplear la experiencia adquirida en crear Lando, que a diferencia de su predecesor cuenta únicamente con interfaz de consola, pero esta es mucho más potente y estable, y sus usos tienen un alcance que va mucho más allá de pantheon, aunque en el caso de pantheon cuenta con algunas características extra realmente jugosas de las que hablaremos más adelante. Lando permite crear entornos de desarrollo local personalizados para proyectos drupal, wordpress, php, java, python, ruby, node... y muchos otros tipos de proyectos web.

  Instalando Lando

La documentación de Lando es bastante explicativa, pero aquí vamos a cubrir la instalación en Linux.

1. Instalando docker comunity edition

Si ya tienes docker instalado en tu equipo, omite este paso

cd /tmp wget -O get-docker.sh https://get.docker.com/ chmod +x get-docker.sh ./get-docker.sh 2. Instalando lando

Descargamos e instalamos el paquete .deb o .rpm de la última versión de Lando que encontraremos en el éste enlace

  Primeros pasos con Lando

Lando cuenta con una serie de recetas enfocadas al desarrollo web, esto es containers preconfigurados y parametrizados para acelerar nuestro desarrollo local. La interfaz de consola de Lando nos ayuda en el proceso de creación de estas recetas que al final se gestionan mediante un fichero de configuración .lando.yml situado en la carpeta raíz de nuestro proyecto.

Por ejemplo, imaginemos que queremos el típico entorno LAMP (Linux + Apache + Mysql + PHP):

mkdir lamp-example cd lamp-example/ lando init

Y comenzará el asistente:

? What recipe do you want to use? drupal8 joomla laravel ❯ lamp lemp mean pantheon (Move up and down to reveal more choices)

Seleccionamos la receta que queremos usar y continuamos

? What recipe do you want to use? lamp ? Where is your webroot relative to the init destination? . ? What do you want to call this app? lamp-example NOW WE'RE COOKING WITH FIRE!!! Your app has been initialized! Go to the directory where your app was initialized and run `lando start` to get rolling. Check the LOCATION printed below if you are unsure where to go. Here are some vitals: NAME lamp-example LOCATION /var/www/lamp-example RECIPE lamp DOCS https://docs.devwithlando.io/tutorials/lamp.html

El asistente se explica por sí solo, pero lo hemos reflejado aquí para que se vea la sencillez y agilidad que nos aporta Lando. El asistente lo que ha hecho es crearnos el fichero .lando.yml que comentábamos antes.

cat .lando.yml name: lamp-example recipe: lamp config: webroot: .

el efecto sería el mismo si lo creásemos a mano. Ahora sólo tenemos que inicializar la receta.

lando start landoproxyhyperion5000gandalfedition_proxy_1 is up-to-date Creating network "lampexample_default" with the default driver Creating volume "lampexample_appserver" with default driver Creating volume "lampexample_data" with default driver Creating volume "lampexample_data_database" with default driver Creating lampexample_appserver_1 ... Creating lampexample_database_1 ... Creating lampexample_database_1 Creating lampexample_appserver_1 ... done BOOMSHAKALAKA!!! Your app has started up correctly. Here are some vitals: NAME lamp-example LOCATION /var/www/lamp-example SERVICES appserver, database APPSERVER URLS https://localhost:32794 http://localhost:32795 http://lamp-example.lndo.site:8000 https://lamp-example.lndo.site

Y listo! ya tenemos un entorno lamp plenamente funcional, con urls para sus versiones http y https.

Ahora veamos que version de php tenemos.

lando php -v PHP 7.1.13 (cli) (built: Jan 9 2018 00:41:00) ( NTS ) Copyright (c) 1997-2017 The PHP Group Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies with Zend OPcache v7.1.13, Copyright (c) 1999-2017, by Zend Technologies with Xdebug v2.5.5, Copyright (c) 2002-2017, by Derick Rethans

Como podemos ver tenemos instalado php 7.1 en nuestro container. Supongamos que estamos trabajando en un proyecto cuyo servidor de producción utiliza php 5.6. Si hacemos uso de nuevas características de php7 fallarán al instalar el proyecto en un hosting con php 5.6, asi que vamos adecuar el entorno de desarrollo a las necesidades del proyecto. Editamos el fichero .lando.yml, añadiendo el apartado php: 5.6, dentro del apartado config del yml, quedando el fichero como siguie:

vim .lando.yml name: lamp-example recipe: lamp config: webroot: . php: 5.6

...reconstruímos el container con el comando rebuild:

lando rebuild

y comprobamos:

lando php -v PHP 5.6.33 (cli) (built: Jan 9 2018 02:55:39) Copyright (c) 1997-2016 The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies with Xdebug v2.5.5, Copyright (c) 2002-2017, by Derick Rethans   Lando y drupal

Lando cuenta con recetas específicas para drupal. Podemos seleccionar drupal7 o drupal8 en la lista de recetas al hacer lando init o podemos omitir ese primer paso especificando la receta mediante el parámetro opcional --recipe. Veamos un ejemplo

cd /var/www mkdir d8-example cd d8-example/ lando init --recipe=drupal8 lando start cat .lando.yml name: d8-example recipe: drupal8 config: webroot: .

Esto nos creará un container con apache en su última vesión, drush y drupal console, mysql 5.7 y php 7.1 (en el momento en que se escribe este artículo). Supongamos que queremos tener nginx, mariadb y php 7.2, y que además queremos tener phpmyadmin. Editamos el fichero .lando.yml quedando como sigue:

vim .lando.yml name: d8-example recipe: drupal8 config: webroot: . php: 7.2 database: mariadb via: nginx services: pma: type: phpmyadmin proxy: pma: - pma.d8-example.lndo.site

y reconstruímos el container

lando rebuild   Lando y pantheon

Pantheon es un PAAS (Platform As A Service) orientado incialmente a alojar proyectos drupal, y que actualmente también soporta proyectos wordpress. Como decíamos anteriormente, el equipo que desarrolló Lando es el que desarrolló en su momento Kalabox, un servicio orientado exclusivamente a pantheon, del que Lando es su digno heredero. Y como tal, viene con una serie de características extra para pantheon:

 

lando init pantheon

Es una variante del lando init adaptado a pantheon. La primera vez que lo ejecutamos nos pedirá nuestro machine token de pantheon, y acto seguido nos mostrará una lista con los proyectos a los que tenemos acceso para que seleccionemos con cual de ellos queremos trabajar en local. El fichero .lando.yml generado contendrá el uuid del proyecto de pantheon.

 

lando pull

Este asistente nos preguntará de que entorno (dev, test o live)  nos queremos bajar código, base de datos y/o files. Sirve tanto para inicializar nuestro entorno local como para actualizarlo con los últimos contenidos de producción o de otro entorno.

 

lando push

Es el reverso del comando pull. Nos permite subir nuestra base de datos y ficheros de local a un entorno de pantheon. No obstante, este comando debe usarse con cautela, y en todo caso no utilizarlo para evitar exportar nuestras configuraciones, que deben estar siempre en git.

 

lando terminus

Permite ejecutar cualquier comando de terminus en el container. Términus es la interfaz de linea de comandos de pantheon, donde podemos hacer todo lo que hacemos desde el dashboard pero desde nuestro terminal (y algunas cosas más).

 

Esto es todo. Esperamos haber realizado una buena introducción a Lando y que más gente se anime a utilizar esta magnífica herramienta.

Categories: Straight From Drupal

People Data Form

Latest Drupal Modules - Mon, 2018-01-15 13:15

A form to accept user details and then display them back.
The form will be visible at: /people/myform

Made as a part of Google Code-in 2017.

Categories: Straight From Drupal

Amazee Labs: Don’t Push it: Using GraphQL in Twig

Planet Drupal - Mon, 2018-01-15 09:40
Don’t Push it: Using GraphQL in Twig

Using GraphQL in Drupal with Twig instead of React, Vue or the next month's javascript framework might sound like a crazy idea, but I assure you it’s worth thinking about.

Philipp Melab Mon, 01/15/2018 - 10:40 Twigs of grass. As in Twig the template language.

Decoupling is all the rage. Javascript frontends with entirely independent backends are state of the art for any self-respecting website right now. But sometimes it’s not worth the cost and the project simply does not justify the full Drupal + React technology stack.

Besides the technological benefits of a javascript based frontend like load times and responsiveness, there’s another reason why this approach is so popular: It moves control to the frontend, concept and design unit, which matches project workflows a lot better.

Status quo

Traditionally Drupal defines data structures that provide a “standard” rendered output, which then can be adopted by the so-called “theme developer” to meet the clients' requirements. Template overrides, preprocess functions, Display Suite, Panels, Layouts - there are myriads of ways how to do this, and twice as many opinions determining the right one. When taking over a project the first thing is to figure out how it was approached and where the rendered information actually comes from. Templates only have variables that are populated during processing or preprocessing and altered in modules or themes, which makes it very hard to reason with the data flow, if you were not the person that conceived it in the first place.

There are ideas to improve the situation, but regarding the success of decoupling, perhaps it’s time to approach the problem from a different angle.

Push versus Pull

The current push model used by Drupal scatters responsibilities across modules, preprocess functions and templates. The controller calls the view builder to prepare a “renderable” that is altered 101 times and results in a set of variables that might or might not be required by the current theme’s template.

If we would turn this around and let the template define it’s data requirements (as it happens in decoupled projects naturally), we could achieve a much clearer data flow and increase readability and maintainability significantly.

And that’s what the GraphQL Twig module is supposed to do. It allows us to add GraphQL queries to any Twig template, which will be picked up during rendering and used to populate the template with data.

A simple example node.html.twig:

{#graphql query($node: String!) { node:nodeById(id: $node) { title:entityLabel ... on NodeArticle { body { processed } } } } #} <h1>{{ graphql.data.node.title }}</h1> {% if graphql.data.node.body %} <div class="body">{{ graphql.data.node.body.processed }}</div> {% endif %}

 

This is already enough to pull the information we need and render it. Let’s have a look at what this does:

The graphql comment on top will be picked up by the module. When the template is rendered, it tries to match the queries input arguments to the current template variables, runs the GraphQL query and passes the result as a new graphql variable to the template. Simple as that, no preprocessing required. It works for every theme hook. Be it just one complex node type, an exceptional block or page.html.twig.

Imagine we use GraphQL Views to add a contextual GraphQL field similarArticles that uses SOLR to find similar articles for a given node. It could be used immediately like this:

{#graphql query($node: String!) { node:nodeById(id: $node) { title:entityLabel ... on NodeArticle { body { processed } similarArticles { title:entityLabel url:entityUrl { alias } } } } } #} <h1>{{ graphql.data.node.title }}</h1> {% if graphql.data.node.body %} <div class="body">{{ graphql.data.node.body.processed }}</div> {% endif %} {% if graphql.data.node.similarArticles %} <h2>Similar articles</h2> <ul> {% for article in graphql.data.node.similarArticles %} <li> <a href="https://www.amazeelabs.com/%7B%7B%20article.url.alias%20%7D%7D">{{article.title}}</a> </li> {% endfor %} </ul> {% endif %}

 

The module even scans included templates for query fragments, so the rendering of the “similar article” teaser could be moved to a separate component:

node.html.twig {#graphql query($node: String!) { node:nodeById(id: $node) { title:entityLabel ... on NodeArticle { body { processed } similarArticles { ... NodeTeaser } } } } #} <h1>{{ graphql.data.node.title }}</h1> {% if graphql.data.node.body %} <div class="body">{{ graphql.data.node.body.processed }}</div> {% endif %} {% if graphql.data.node.similarArticles %} <h2>Similar articles</h2> <ul> {% for article in graphql.data.node.similarArticles %} <li> {% include 'node-teaser.twig' with { node: article } %} </li> {% endfor %} </ul> {% endif %}

 

node-teaser.twig {#graphql fragment NodeTeaser on Node { title:entityLabel url:entityUrl { alias } } #} <a href="https://www.amazeelabs.com/%7B%7B%20node.url.alias%20%7D%7D">{{node.title}}</a>

 

No preprocessing, a clear path where data flows and true separation of concerns. The backend provides generic data sources (e.g. the similarArticles field) that can be used by the product development team at will. All without the cost of a fully decoupled setup. And the possibility to replace single theme hooks allows us to use existing Drupal rendering when it fits and switch to the pull-model wherever we would have to use complex layout modules or preprocessing functions to meet the requirements of the project.

Future development

There are some ideas for additional features, like mutation based forms and smarter scanning for query fragments, but first and foremost we would love to get feedback and opinions on this whole concept. So if you are interested, join on Slack or GitHub and let us know!

Amazee Labs: Don’t Push it: Using GraphQL in Twig

Feeds from Drupal.org - Mon, 2018-01-15 09:40
Don’t Push it: Using GraphQL in Twig

Using GraphQL in Drupal with Twig instead of React, Vue or the next month's javascript framework might sound like a crazy idea, but I assure you it’s worth thinking about.

Philipp Melab Mon, 01/15/2018 - 10:40 Twigs of grass. As in Twig the template language.

Decoupling is all the rage. Javascript frontends with entirely independent backends are state of the art for any self-respecting website right now. But sometimes it’s not worth the cost and the project simply does not justify the full Drupal + React technology stack.

Besides the technological benefits of a javascript based frontend like load times and responsiveness, there’s another reason why this approach is so popular: It moves control to the frontend, concept and design unit, which matches project workflows a lot better.

Status quo

Traditionally Drupal defines data structures that provide a “standard” rendered output, which then can be adopted by the so-called “theme developer” to meet the clients' requirements. Template overrides, preprocess functions, Display Suite, Panels, Layouts - there are myriads of ways how to do this, and twice as many opinions determining the right one. When taking over a project the first thing is to figure out how it was approached and where the rendered information actually comes from. Templates only have variables that are populated during processing or preprocessing and altered in modules or themes, which makes it very hard to reason with the data flow, if you were not the person that conceived it in the first place.

There are ideas to improve the situation, but regarding the success of decoupling, perhaps it’s time to approach the problem from a different angle.

Push versus Pull

The current push model used by Drupal scatters responsibilities across modules, preprocess functions and templates. The controller calls the view builder to prepare a “renderable” that is altered 101 times and results in a set of variables that might or might not be required by the current theme’s template.

If we would turn this around and let the template define it’s data requirements (as it happens in decoupled projects naturally), we could achieve a much clearer data flow and increase readability and maintainability significantly.

And that’s what the GraphQL Twig module is supposed to do. It allows us to add GraphQL queries to any Twig template, which will be picked up during rendering and used to populate the template with data.

A simple example node.html.twig:

{#graphql query($node: String!) { node:nodeById(id: $node) { title:entityLabel ... on NodeArticle { body { processed } } } } #} <h1>{{ graphql.data.node.title }}</h1> {% if graphql.data.node.body %} <div class="body">{{ graphql.data.node.body.processed }}</div> {% endif %}

 

This is already enough to pull the information we need and render it. Let’s have a look at what this does:

The graphql comment on top will be picked up by the module. When the template is rendered, it tries to match the queries input arguments to the current template variables, runs the GraphQL query and passes the result as a new graphql variable to the template. Simple as that, no preprocessing required. It works for every theme hook. Be it just one complex node type, an exceptional block or page.html.twig.

Imagine we use GraphQL Views to add a contextual GraphQL field similarArticles that uses SOLR to find similar articles for a given node. It could be used immediately like this:

{#graphql query($node: String!) { node:nodeById(id: $node) { title:entityLabel ... on NodeArticle { body { processed } similarArticles { title:entityLabel url:entityUrl { alias } } } } } #} <h1>{{ graphql.data.node.title }}</h1> {% if graphql.data.node.body %} <div class="body">{{ graphql.data.node.body.processed }}</div> {% endif %} {% if graphql.data.node.similarArticles %} <h2>Similar articles</h2> <ul> {% for article in graphql.data.node.similarArticles %} <li> <a href="https://www.amazeelabs.com/%7B%7B%20article.url.alias%20%7D%7D">{{article.title}}</a> </li> {% endfor %} </ul> {% endif %}

 

The module even scans included templates for query fragments, so the rendering of the “similar article” teaser could be moved to a separate component:

node.html.twig {#graphql query($node: String!) { node:nodeById(id: $node) { title:entityLabel ... on NodeArticle { body { processed } similarArticles { ... NodeTeaser } } } } #} <h1>{{ graphql.data.node.title }}</h1> {% if graphql.data.node.body %} <div class="body">{{ graphql.data.node.body.processed }}</div> {% endif %} {% if graphql.data.node.similarArticles %} <h2>Similar articles</h2> <ul> {% for article in graphql.data.node.similarArticles %} <li> {% include 'node-teaser.twig' with { node: article } %} </li> {% endfor %} </ul> {% endif %}

 

node-teaser.twig {#graphql fragment NodeTeaser on Node { title:entityLabel url:entityUrl { alias } } #} <a href="https://www.amazeelabs.com/%7B%7B%20node.url.alias%20%7D%7D">{{node.title}}</a>

 

No preprocessing, a clear path where data flows and true separation of concerns. The backend provides generic data sources (e.g. the similarArticles field) that can be used by the product development team at will. All without the cost of a fully decoupled setup. And the possibility to replace single theme hooks allows us to use existing Drupal rendering when it fits and switch to the pull-model wherever we would have to use complex layout modules or preprocessing functions to meet the requirements of the project.

Future development

There are some ideas for additional features, like mutation based forms and smarter scanning for query fragments, but first and foremost we would love to get feedback and opinions on this whole concept. So if you are interested, join on Slack or GitHub and let us know!

Categories: Straight From Drupal

Bing CSE

Latest Drupal Modules - Mon, 2018-01-15 09:21

Bing Custom Search Engine enables you to create your own custom web search engine. Setting-up a web search becomes easy, fast and enjoyable.

Categories: Straight From Drupal

field_formatters

Latest Drupal Modules - Mon, 2018-01-15 08:48

Define field formatters that can only be used on text
fields. These field formatters allow the site builder to choose
from one of several ways to manipulate the text field’s values before
outputting the text on the page.

FEATURES:
---------

1. Rot13 - The text field value should be printed with the ROT13 encoding
( https://en.wikipedia.org/wiki/ROT13 ). For example, “Lorem Ipsum” would become “Yberz
Vcfhz”.

Categories: Straight From Drupal

QuickSeedGCI

Latest Drupal Themes - Mon, 2018-01-15 05:47

QuickSeed is a Drupal 8 theme aims to serve on the web as fast as possible. Basically it is designed for Blogger or News websites keeping in mind of search engine friendly and mobile friendly features. There are dedicated blocks for Ad-senses and recommended content by third parties. it provides best reading experience to its users with appropriate font and background color. After All it is responsive, fully optimized and very fast.
Demo: https://quickguide.me/

Categories: Straight From Drupal

QuickSeed2017GCI

Latest Drupal Themes - Mon, 2018-01-15 05:25

QuickSeed is a Drupal 8 theme aims to serve on the web as fast as possible. Basically it is designed for Blogger or News websites keeping in mind of search engine friendly and mobile friendly features. There are dedicated blocks for Ad-senses and recommended content by third parties. it provides best reading experience to its users with appropriate font and background color. After All it is responsive, fully optimized and very fast.
Demo: https://quickguide.me/

Categories: Straight From Drupal

QuickSeedGCI2017

Latest Drupal Themes - Mon, 2018-01-15 04:46

QuickSeed is a Drupal 8 theme aims to serve on the web as fast as possible. Basically it is designed for Blogger or News websites keeping in mind of search engine friendly and mobile friendly features. There are dedicated blocks for Ad-senses and recommended content by third parties. it provides best reading experience to its users with appropriate font and background color. After All it is responsive, fully optimized and very fast.
Demo: https://quickguide.me/

Categories: Straight From Drupal

Agiledrop.com Blog: AGILEDROP: Our blog posts from December

Planet Drupal - Mon, 2018-01-15 00:42
You have already seen what Drupal blogs we trending in the previous month, and now it is time to look at all our blog post we wrote. Here are the blog topics we covered in December.   The first blog post in December was Why Drupal is the most secure CMS. It explains and shows the reasons why Drupal is a secure CMS even though many people doubt that due to being open source. The second was In the beginning, Drupal had an ambition. We talked about Dries keynote from DrupalCon Vienna and his statement that Drupal is for ambitious digital experiences. What are three critical ingredients for… READ MORE

Agiledrop.com Blog: AGILEDROP: Our blog posts from December

Feeds from Drupal.org - Mon, 2018-01-15 00:42
You have already seen what Drupal blogs we trending in the previous month, and now it is time to look at all our blog post we wrote. Here are the blog topics we covered in December.   The first blog post in December was Why Drupal is the most secure CMS. It explains and shows the reasons why Drupal is a secure CMS even though many people doubt that due to being open source. The second was In the beginning, Drupal had an ambition. We talked about Dries keynote from DrupalCon Vienna and his statement that Drupal is for ambitious digital experiences. What are three critical ingredients for… READ MORE
Categories: Straight From Drupal

Entity Digest

Latest Drupal Modules - Sun, 2018-01-14 17:23
Categories: Straight From Drupal

Pages

Subscribe to My Drupal aggregator