Get Hook-ed on Object-Oriented Programming

Planet Drupal - Wed, 2021/09/15 - 12:29pm

When writing a hook implementation, for example of hook_cron, there's often a tendency to write purely procedural code, like this:

function my_module_cron() { $entity_type_manager = \Drupal::entityTypeManager(); $node_storage = $entity_type_manager->getStorage('node'); // More code goes here. }

If you've got one or two easily understandable lines of code, fine, but frequently you'll end up with a little mini-application jammed into a hook implementation and it can be very easy to end up with something that's not particularly readable, let alone maintainable.

In several articles I've read they mention that you 'cannot' use Object-Oriented Programming code in a hook, and while sort of technically true, there's several easy ways to get back into the OOP world from a Drupal hook:

Static method

This is sort of one for people who simply don't feel right unless they are programming in a class because it doesn't bring all that many advantages over just writing your code in a function, but your hook implementation could look like this:

function my_module_cron() { \Drupal\my_module\Utility\MagicalCronApplication::run(); }

And then you'd have a simple class in src\Utility\MagicalCronApplication.php:

namespace Drupal\my_module\Utility; class MagicalCronApplication { public static function run() { $entity_type_manager = \Drupal::entityTypeManager(); $node_storage = $entity_type_manager->getStorage('node'); // More code goes here. } }

So that gets you into an OOP landscape, but it's a static method, so not all that different from the function implementing the hook, we can do better.

Create an instance

We could do a little refactor and make it so that our hook implementation instantiates a class and then calls a simple method on it, this would help our code look a little more familiar and indeed allow breaking up our little application into more methods to aid readability.

function my_module_cron() { $instance = new \Drupal\my_module\Utility\MagicalCronApplication(); $instance->runApplication(); }

And then you'd have a simple class in src\Utility\MagicalCronApplication.php:

namespace Drupal\my_module\Utility; class MagicalCronApplication { /** * The node storage instance. * * @var \Drupal\Core\Entity\EntityStorageInterface */ protected $nodeStorage; public function __construct() { $entity_type_manager = \Drupal::entityTypeManager(); $this->nodeStorage = $entity_type_manager->getStorage('node'); } public function runApplication() { // More code goes here. } }

We've got more code than ever before, but it's going to be simpler to split up our mini-application and tightly couple the methods together into a single class now.

We could also go a bit further and use the dependency injection pattern to get:

function my_module_cron() { $instance = new \Drupal\my_module\Utility\MagicalCronApplication(\Drupal::entityTypeManager()); $instance->runApplication(); }

And in src\Utility\MagicalCronApplication.php:

namespace Drupal\my_module\Utility; use Drupal\Core\Entity\EntityTypeManagerInterface; class MagicalCronApplication { /** * The node storage instance. * * @var \Drupal\Core\Entity\EntityStorageInterface */ protected $nodeStorage; public function __construct(EntityTypeManagerInterface $entity_type_manager) { $this->nodeStorage = $entity_type_manager->getStorage('node'); } public function runApplication() { // More code goes here. } } Class resolver

Dependency injection is a lovely programming pattern that allows nice things like easily passing in mocked objects and if nothing else explicitly listing out our code dependencies. But if you don't have a Dependency Injection Container around, it can make instantiating classes pretty tricky/verbose, thankfully Drupal does and it has also has a super nifty class that'll help us access services in the container too. (Technically this is dependency container injection into a factory method, but hey!)

So we can rework our code to be like this:

function my_module_cron() { \Drupal::service('class_resolver') ->getInstanceFromDefinition(\Drupal\my_module\Utility\MagicalCronApplication::class) ->runApplication(); }

And in src\Utility\MagicalCronApplication.php:

namespace Drupal\my_module\Utility; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Symfony\Component\DependencyInjection\ContainerInterface; class MagicalCronApplication implements ContainerInjectionInterface { /** * The node storage instance. * * @var \Drupal\Core\Entity\EntityStorageInterface */ protected $nodeStorage; public function __construct(EntityTypeManagerInterface $entity_type_manager) { $this->nodeStorage = $entity_type_manager->getStorage('node'); } public static function create(ContainerInterface $container) { return new static( $container->get('entity_type.manager') ); } public function runApplication() { // More code goes here. } }

Now we can write code that's much more familiar to the rest of Drupal and much more importantly we can copy/paste code from other classes as we need without having to think too much or doing various gymnastics to get the services we need, we can just add them nicely to the constructor and factory and we're away!

This approach also allows calling this code from multiple places much more easily, say if you want to provide a Drush command that calls this code or even a button in the web UI that runs the exact same code. These things are now super simple.

Bonus: If we happen to not actually need any services from the container, then we can actually drop the create factory method and the implements and the class resolver will basically call new for us, but the day we do want those things we can pop them back and we don't have to go around worrying that usages of our class will break.

We could stop there...and we probably should...but.

A service

We're now not actually that far away from creating a full-blown service, which essentially is only different from the last example in that the class is also made available in the dependency injection container for other code to use too.

For that we could declare our service in a file like so:

services: my_module.magical_cron_service: class: Drupal\my_module\Utility\MagicalCronApplication arguments: ['@entity_type.manager']

And then our hook becomes:

function my_module_cron() { \Drupal::service('my_module.magical_cron_service') ->runApplication(); }

We can then drop the factory static method from our class:

namespace Drupal\my_module\Utility; use Drupal\Core\Entity\EntityTypeManagerInterface; class MagicalCronApplication { /** * The node storage instance. * * @var \Drupal\Core\Entity\EntityStorageInterface */ protected $nodeStorage; public function __construct(EntityTypeManagerInterface $entity_type_manager) { $this->nodeStorage = $entity_type_manager->getStorage('node'); } public function runApplication() { // More code goes here. } }

Aside from probably now being really badly named, a service allows some other fun things, like other code could swap out the actual class instantiated when the service is requested. If you did really want to do something like that I'd argue that you can actually swap out the hook implementation itself using a module_implements_alter hook implementation instead, which is probably clearer as to what's going on (it's still not very clear, obviously).

If you are declaring a service you should probably also give the class an interface and because you are advertising to the world that they can call your code you should expect that to happen. You might now have to think about what issues you might cause if you change that code in the future. You might end up supporting an entire ecosystem of modules off of your service, that's a lot of potential code to break.

It's possible that a hybrid approach might be appropriate, whereby you declare some service that contains small, useful functions that other code from other modules might want to call, but that you keep your hook implementations either simply calling the methods on those simple services or where a little bit more logic is required: having a tightly coupled utility class, like in the 'Class resolver' example, that can do the work in a more OOP way.

Wrapping up

I'd argue that unless your hook implementation is no more than two or three lines, you might as well spin up a quick utility class and use the class resolver to instantiate the class. The future you will be grateful that you put in the extra minute to make your codebase more consistent, more copy/pasteable, and more flexible.

Additionally, if your utility class ends up with a lot of useful code in it I'd strongly consider refactoring it into a service so that other code can use your useful code too, but probably don't reach for the services.yml every time you need instantiate an object. But equally, you can use Object-Oriented Programming to implement a hook, almost.

Photo by James Harrison on Unsplash

Categories: Blog: 6 challenges of hybrid work and how to overcome them

Planet Drupal - Wed, 2021/09/15 - 10:25am

In this article, we address 6 main challenges to implementing hybrid work and offer solutions for them.


Innoraft Drupal Blogs: 7 Reasons Why Should You Choose Drupal for eCommerce Website

Planet Drupal - Wed, 2021/09/15 - 8:42am
7 Reasons Why Should You Choose Drupal for eCommerce Website Drupal CMS has hundreds of modules and themes that add magic to your online business. Read this article why to choose Drupal for eCommerce Website development. Tanjeet Wed, 09/15/2021 - 12:12 Drupal Development Drupal Planet Ecommerce Website Development Ecommerce Development

Lullabot: How to Plan a Successful Design Handoff

Planet Drupal - Tue, 2021/09/14 - 10:17pm

Too many design handoffs are treated like a relay race. The designers hand off the baton to the developers and then go home because they consider their part of the race done. This can create uncertainty, which means developers have to make assumptions about how things should work and look. 

Many of these assumptions will be inaccurate, leading to frustration, mismatched expectations, and wasted time. The bigger the project, the more these problems manifest.


OpenSense Labs: The State of Headless Architecture in 2021

Planet Drupal - Tue, 2021/09/14 - 4:17pm
The State of Headless Architecture in 2021 Gurpreet Kaur Tue, 09/14/2021 - 19:47

Every year the technology trends keep on changing and every year it keeps on astounding us. And I believe it is these technological advancements that keep the world moving, and standstill isn’t something that any of us would like or even prefer.    

Today, I want to talk about one such technological advancement that has appeased the web developers, marketers and stakeholders beyond their expectations. And that is the headless architecture for web development

So, what is headless architecture?

Traditionally, when a website is built using content management systems, it is entirely encompassed within that CMS. That one software is the entire world of the website, it controls the presentation layer and the UI as well as manages content at the backend, there isn’t anything else for it. However, the headless solution can offer a website the chance to dip its toes into newer and more modern technologies. 

With the headless approaches, a website essentially separates its frontend from the backend. While the backend functionality is dependent on the CMS at work, the frontend could be any technology available to the developer. JavaScript and Static Site Generators are what are often chosen, with React, Angular, Vue, Gatsby and Metalsmith amongst the frontrunners. 

So, how does the site function with this separation of powers?

An application programming interface or an API to be short helps in that. It transmits information to and from both the ends, kind of like a middleman in sales. Because of the API, the content can be distributed on multiple channels with ease, making content creators extremely happy, an advantage the monolithic architecture does not offer. 

The headless or decoupled architecture is known for the freedom it gives to the developers, making it a trend that has been increasingly gaining grounds and that is what we are going to be analysing today. The reasons, the statistics, the headless domains, the constraints and of course, we can’t ignore Drupal. Let’s see the headless architecture trends in 2021

Has headless architecture become the next big thing in web development?

For me, the answer to that question is a big fat yes. And I have three words to justify my stance and those are superior digital experiences. Headless architectures have the potential to create digital experiences that are far more superior than a standalone, monolithic approach could ever conceive to build. It might seem a little unfair to say that the monolithic architecture is inept at what it does, that is certainly not the case, it's just that the headless architecture has a lot more to offer. For further understanding, read more about headless architecture and monolithic architectures and when to move from monolithic to headless architecture.

Now, let’s take a closer look at the paramount reasons for the significant state the headless architecture has found itself to be in 2021. When you ask yourself ‘Are headless CMS worth it,’ it’s these reasons that would give you an answer.

Headless for limitless technologies and limitless possibilities 

The prime reason for the elevated position of headless architecture is owed to the limitless technologies it allows the adapter to adopt. Headless has become the synonym for technological advancement in web development. A traditional CMS in the monolithic sense would always come with boundations, there would come a point where its abilities can no longer be extended, however, in the headless setup that point is quite far-fetched. More on whether choosing a headless CMS is right or not here.

You can use any technology you want and any feature you may want can be added to your project. 

What is the result?

An enhanced digital experience for your users. Here is what the WP engine’s 2021 survey found out. 

Almost 92% of the survey respondents believed that the headless architecture led to an enhanced digital experience for the users because of its content experience it provided.

You cannot deny the advantage the use of other technologies can give you. 

  • You get the best content experience that is omnichannel, you can reuse it on multiple platforms without it being scattered on multiple siloes; 
  • You get better aesthetics, better accessibility and better user experience for your project; 
  • You get better security as the codebase is less bulky because of the separation of concerns; 
  • You get more productivity out of your developers because they are going to be using technologies that they like and are comfortable with; 
  • You get independent marketers who do not have to rely on developers for simple tasks like creating and updating landing pages: 
  • You get to future proof your project because you aren’t going to be relying on one software that has the chance of becoming obsolete after some time.

Apart from these, you do get plenty of other benefits too, faster performance, faster innovation, faster marketing and a faster and seamless connection between all your digital touchpoints. And you can achieve all of this using React or Angular or Vue or a static site generator, that is your choice completely.

Headless for keeping users satiated 

So far, we’ve gathered that headless architecture is equipped with an exponential amount of possibilities to be created from an exponential number of technological choices.

As a result, web experiences are being able to provide solutions that were never before achieved through the monolithic architecture. Consequently, organisations are able to achieve their strategic goals through headless and become utterly satiated with their developments. 

The leadership in an organisation has become more likely to choose a headless approach and recommend it to its tech providers in the hopes of capitalising on the many choices the approach comes with. This incidentally keeps everyone satiated, including the stakeholders, the development and marketing team and the targeted audience and consumers.

Headless for all the right reasons 

According to a report by Kentico Kontent, here is the perception of the headless architecture straight from its users. 

Source: Kentico Kontent

Majority of the users, including the developers and the marketers, consider the headless approach to provide a considerable number of benefits, which makes us believe that this is a trend that is only going to boom in the near future.

Headless for better investment 

2.6 million USD

That is a substantial amount and that is the average investment organisations are making on headless technologies. 

Is it a better investment choice?

The preceding three points would be a clear indication of an affirmation of this question. Yes, the investment can seem a bit daunting, but it comes with its fair share of benefits that account to one satisfying outcome and that is better ROIs.

Okay, you tell me; 

Would better performance not bring in more rewards?
Would an agile workflow not lead to more productivity and better solutions?
Would a robust digital experience not be equivalent to happier consumers?

If yes, then the headless architecture is truly the next big thing in the world of web development and any other architecture would seem a little pale compared to it.

What do the numbers say about headless architecture?

The numbers are in favour of technology today and they definitely favour the headless approach. 

According to OC&C Strategy Consultants

  • 55% of US households will own a smart device; 
  • And the IoT market is expected to be valued at 520 billion USD by this year.

This is proof that technology is going to boom in the near future. As for the headless trend, here is a projection that shows tremendous growth.

With a CAGR of 22.6%, the headless architecture is bound to have an illustrious future. 

Now, let’s take a look at the usage of headless architecture and the interest it has garnered by enterprise organisations in 2019 in comparison with 2021.

What is also important to note is that now organisations have started associating digital experiences with business success. And since we have established a direct relationship between enhanced digital experiences and headless technologies, you can probably guess what the path to business success will entail. 

Referring to the WP engine report again, 

A vast majority of organisations, 92% of them, believe digital experiences become more powerful with headless technologies.

Now, you tell me, don’t you think the headless approach is only going to advance in the future? If you ask me, I certainly do.

What technological aspects are being capitalised with the headless architecture?

We’ve talked about how the headless architecture is being perceived in the present and looked at statistics that only show a growing trend. Now, let’s look at the technologies that are being capitalised to make this approach reach its true potential; it’s important because it's these technologies that encompass the majority of the benefits of headless architecture. 

JavaScript and all its virtues 

You can’t talk about headless architecture and not mention JavaScript. Ever since its release in 1995, it has evolved a great deal and become frontend developers’ holy grail, with two-thirds of them swearing by it. 

Here is a graph showing the popularity of JS frameworks over the years. 

Source: State of JavaScript 2020

Can’t forget JAMstack 

The mention of JavaScript brings us to JAMstack, that is JavaScript, API and Markup. It is an architecture that stands on pre-rendering and decoupling. Websites built on it are considerably faster, more secure and more scalable. With JS in play, the frontend is bound to offer more to the developers, thus enhancing their productivity and workflow. 

Focus on individual components while development

Next technicality often seen in the headless world is pertinent to the development of individual components. There are two variations in this.

Micro-frontend architecture 

This is a solution that works marvelously with the monolithic structure by breaking it down into individual components that essentially become independent applications. Although they are separate, the codebase remains the same. 

Component-driven development architecture

This is somewhat similar to the previous one. However, it emphasises on the principle of modularity. This means that the developed components have the benefit of being reused and composed.

Both of these architectures come with similar advantages; 

  • The development takes place faster with team focusing on only one feature or component working simultaneously; 
  • The integration goes smoothly; 
  • The code can be maintained with much more ease; 
  • The task of scaling the project becomes pretty straightforward;
  • And the chances of errors reduce drastically, making testing and updates a breeze.

To know more, read about designing component-based systems, a quick look at the world of web components and the principles of atomic design methodology.

The new API solution: GraphQL 

Going headless mandates an API, and RESTful APIs were the only resort. However, now GraphQL is seen to be taking over. Being a query language, it enhances the data retrieval process to be much more accurate by reducing the number of requests sent to the server. 

  • GraphQL has smaller payloads; 
  • It has a single graph for retrieving queries; 
  • It can efficiently handle errors; 
  • And most importantly, it has a stringent type interface that magnifies performance.

Owing to these reasons, it is considered to be the superior sibling of RESTful API. And major brands like Facebook, Lyft and even Audi are leveraging it. More on different web services implementations available here.

Progressiveness in app development 

By progressiveness, I mean the Progressive Web Applications or PWAs. These are a cross-breed of mobile applications and traditional websites, meaning they leverage the browser APIs and its features as well as a conventional progressive enhancement strategy. The result is a project that performs impeccably well, loading in mere seconds, across multiple devices. Their reliance on HTTP protocols also make them pretty secure.

What is more intriguing about this trend is the fact that these PWAs perform even when there is poor or no connectivity. Thus, equipping businesses to target a demographic that was often overlooked.

The headless trend is growing, but not fast enough, why?

The image above mentions the percentage of people using and not using the headless architecture. And if I’m being honest the numbers are a bit disappointing when you look at the true potential of the approach. 

So, why is that the case?

Let’s find out. 

The marketers’ and content editors’ underwhelming experiences 

One of the promises that the headless architecture often makes is that it eases the work of both the marketers and the content editors. While that may be true to some degree, it isn’t the complete truth. 

The Kentico Kontent survey’s respondents gave the most precise answer that hit on point when they highlighted the demerits as below.

Source: Kentico Kontent

If we consider these findings, three out of the top four challenges stated there are related to just that. Dependency on web developers and lack of marketing capabilities are proof enough. 

So, why aren’t the marketers and content editors not satisfied?

The major problem is related to control. The marketers and content editors do not have enough control over the visual layer as the presentation and content workflows are built from scratch by the developers. The access to the editorial interface isn’t as streamlined as the traditional setup.

I truly wondered as to why this was a problem. 

The answer lies in the universal nature of the headless content. Let me explain it. For a website or a mobile application, features like in-place editing and the famous drag-and-drop layout work pretty well. However, when you consider a smartwatch or say a voice assistant, can the same features be a possibility? 

Hence, the marketers and the editors have to compromise a little for the greater good, there is just no way around it. More on when and how to use headless CMS here.

The overwhelming concerns that won’t leave us alone

The headless architecture is still a novel concept for many of us. And like anything else that is new, there is some apprehension associated with it. You can say that it is because you would be parting with the out-of-the-box features that the monolithic structure may offer.

Monitoring and reporting; 
And CRM; 

These are genuine concerns regarding the headless approach since it would be you and your front-end developers who would be responsible for them, and not your CMS or its community support. And that is as intimidating as it is overwhelming. You would entrust your site’s entire front-end to your developers, there is bound to be some risk, so trust me I get the apprehension.

Of course, you can hire an agency to help you out with the right security API so that there aren’t any flaws and only be overwhelmed with the impressiveness of your site. More on the right skills you need to successfully deliver a headless project here.

The perception of the stakeholders

Finally, it is time to discuss the stakeholders and the role they play in holding back the headless architecture. 

If you ask a stakeholder in an organisation to give his take on this approach, you would probably not get a straight answer. When we understand their perception, you can’t really blame them for their opinion. 

For one, that person relies on his website for his livelihood and he wouldn't want to risk it. Therefore, he might not want to adopt the headless architecture before others because he isn’t familiar with the territory. Secondly, the website may have all the necessary features that it needs to satisfy its consumer base, at least in the present, through the traditional setup. 

Yes, technology might change in the future, the consumer needs would too, but where is it written that only headless architecture can fulfil those needs. The headless approach does have a lot to offer, but so does the conventional CMS. So, why risk it?

Where does Drupal fit in the headless movement of 2021?

I couldn’t write a blog about the headless approach and not mention Headless Drupal architecture, that would not be ideal at all as I personally feel that Drupal is one of the best headless CMS in 2021. So, let’s understand the role of Drupal and all of its offerings in the headless realm.

Drupal has an impressive headless architecture that allows its users to work with the most advantageous technologies today. It offers three ways to approach the headless architecture.

  • You can choose to fully decouple Drupal, this would completely separate your frontend from the backend, you’ll be free to build your presentation layer outside of Drupal, while the CMS would only act as a content repository.
  • You can choose decoupled Drupal for static sites with JAMstack at work and static site generators. More on leveraging static site generators and CMS here.
  • Finally, you can opt for progressively decoupled Drupal, wherein you can use other frontend technologies without losing Drupal’s functionality on the same end, the backend would only be empowered by the CMS.

Choosing between the three and the monolithic architecture can be a tricky choice, here is what Dries Buytaert had to offer in easing the choice. 


To know more, read about the different options of decoupling CMS and best frontend technologies for your headless CMS development.

If you are familiar with Drupal, you may be familiar with all of what I have just mentioned. So, what is new? 

The answer is Decoupled Menus. The DrupalCon Global 2020 brought along the initiative of decoupled menus in Drupal

What is the Decoupled Menus Initiative about?

When you go the decoupled or headless route, you are going to be using JavaScript. Along with that you are going to have to create a custom code from scratch to make that feature using Drupal and JavaScript. 

The decoupled menus will come quite handy here. They are like pre-formed packages of JavaScript configurations that simply need to be implemented to make a headless feature work. These configurable menus can be placed in any JavaScript application and would be managed by Drupal with its community support.

You can also refer to them, if you do not want to use them as is, the documentation, packaging and security would be available to you for reference or implementation.

The decoupled menus are Drupal’s way of evolving itself and adapting into the headless world. It is evolving and making the headless architecture and Drupal combination seem less cumbersome. 

You may ask how? 

Aside from the obvious, there are a few reasons. Drupal architecture isn’t handling the work necessary for JavaScript packages, with decoupled menus, the bundling, testing and shipping via GitLab would be constantly updated. On top of this, the security issues pertaining to JS and the documentation for consumption of menus would be defined and updated. 

All of this means that a non-developer or content creator would get an intuitive UI that would allow him to configure the menus and turn them on or off with a few clicks and certainly without a developer. 

Here is a demo of the decoupled menus feature.

In essence, this is a feature that would lay the groundwork for code for JavaScript frameworks like React and Vue, so that the workload that comes with headless architecture is lessened. You will get a React based display link on your ecommerce site without having to do all the work to get it. 
To emphasize more upon the milestone which this initiative has achieved, take a look at the Decoupled Menus Initiative Keynote followed by an interesting Q & A session through the help of this video at DrupalCon North America 2021.

Concluding with the Future of Headless

Everything in this blog, the hesitation towards decoupled CMS aside, points to a clear and concise conclusion and that is the fact that the headless architecture will continue to expand in the coming years and may even overcome the resistance, making it future proof. 

New technologies would be looked into as part and parcel of the headless CMS, making the expectations seem rather high. Augmented reality, virtual reality, digital displays and kiosks, digital and voice assistants would not be a distant and rather tedious goal to achieve. 

According to the WP engine I’ve quoted a few times now, these advancements and inclination towards headless technologies would somehow vary depending upon geographic regions. Even the major tech hubs like the USA, the UK and Australia experience a variation in the expectation regarding headless. While e-commerce is a priority for the US and Australia, the UK focuses on websites and PWAs as their future expectations from the headless approach. 

Despite the differences, the world of headless is gaining traction and it is going to keep growing in the future as well, that is an irrefutable fact, if there was any. So, is headless CMS the future? It indeed is.

Let me end this blog with an interesting discussion on the state of headless through this YouTube video, enjoy!

blog banner blog image Headless Architecture Headless CMS Decoupled CMS Decoupled Drupal Headless Drupal Decoupled Menus Initiative Traditional CMS Blog Type Articles Is it a good read ? Off

Drupal Association blog: Drupal Association Board Elections, 2021

Planet Drupal - Tue, 2021/09/14 - 3:47pm

It is that time of year again where the Drupal Association Board looks to fill the At-Large member seat that becomes available every year.

This year, we send our thanks to Leslie Glynn, who will be stepping down as an At-Large board member after serving her two years. Last year, Pedro Cambra was elected to the board, who has one more year to serve - and we are sure will be happy to welcome the next person onto the board!

Important Dates

The canonical list of dates, including times, is detailed at “Election 2021: Dates and Candidates” but the next important dates are:

Self nominations open: NOW!!

Self nomination close: 27th September, 1900 UTC

What does the Drupal Association Board do?

The Board of Directors of the Drupal Association is responsible for financial oversight and setting the strategic direction for serving the Drupal Association’s mission, which we achieve through and DrupalCon. Our mission is to unite a global open source community to build, secure, and promote Drupal.

Who can run?

The only requirement for nominees is that you must be a member of the Drupal Association.

How do I run?

Candidates are highly encouraged to:

  1. Watch the latest Community Update Video

  2. Read about the board and elections, including the video about the elections this year
  3. Read the Board Member Agreement

Then visit the Election 2021: Dates & Candidates page to self-nominate. The first step is to fill in a form, nominating yourself. Drupal Association staff will create you a candidate page and make you the author so you can continue to add content here during the election and answer any question posed by the electorate as comments on the page.

Who can vote?

All individual members of the Drupal Association may vote in the election.

If you are not currently a member, please ensure you have renewed your membership before voting opens, on 4th October. The Drupal Association recognizes there should be no barrier to membership so a zero-cost option is available on the individual membership signup form.

How do I vote?

The Drupal Association Board Elections are moving to the free and open source Helios Voting service for 2020 and beyond. All Drupal Association individual members will receive their unique voting links via email, sent to the primary email address in their profile when voting opens. Follow the instructions in that email to vote.

Elected board member special responsibilities

As detailed in a previous blog post, the elected members of the Drupal Association Board have a further responsibility that makes their understanding of issues related to diversity & inclusion even more important; they provide a review panel for our Community Working Group. This is a huge important role in our global community.

What should I do now?

Self-nomination is open! Please do read further:

Then consider if the person who should be standing for election is you. (It probably is!)

To submit your nomination, fill out the nomination form.

On 4th October, get ready to read through the candidate profiles and prepare to cast your ballot!


Consensus Enterprises: Easy commit credits with migrations, part 6: Migrating data from a custom table

Planet Drupal - Tue, 2021/09/14 - 11:00am
How to migrate data out of a custom table in Drupal 7.

Mateu Aguiló: Progressive Decoupling Made Easy

Planet Drupal - Tue, 2021/09/14 - 2:00am
Decoupling separates the system that stores the content from how that content is displayed on other independent systems. This can come with many benefits but also some downsides and tradeoffs. With progressive decoupling, you can get some of the benefits of decoupling while avoiding some of the downsides.

Talking Drupal: Talking Drupal #311 - Measuring Website Success

Planet Drupal - Mon, 2021/09/13 - 4:22pm

Today we are talking about How to Measure Website Success with Chad Hester.

  • John - Wedding
  • Chad - Construction, someone shot Shelley with a pellet gun
  • Nic - Bronchitis
  • Wrench Turning
  • Defining success
  • Vanity Metrics
  • Key Performance Indicators (KPI)
  • Gathering KPIs
  • Informing design and continuous improvements
  • Challenges
  • When to act
  • Growth Driven Design

Start with Why The Lean Startup Growth-Driven Design Chad’s presentation about "Creating a Performance Measurement Framework"for your projects Startup way Hubspot Growth Driven Design

Guests Hosts

Nic Laflin - @nicxvan

John Picozzi - @johnpicozzi

Chad Hester - @chadkhester

Categories: How to reuse the same image for a thumbnail, hero and social sharing with Drupal

Planet Drupal - Mon, 2021/09/13 - 2:04pm

Combining the media module, image crop and metatag module you can create the perfect image management system for your Drupal content. You only have to upload one image which then can be used for multiple purposes.


Promet Source: Drupal vs. WordPress: Key Strengths of the Top CMSs

Planet Drupal - Fri, 2021/09/10 - 11:39pm
A frequent question in the Open Source CMS world is some variation of: “Which is better, Drupal or WordPress?”  Of course, there’s not a simple answer to the WordPress vs. Drupal question. Many have a strong bias towards one content management system or the other, but often, staunch opinions on the subject are based on a few cursory facts or outdated information.

Ben's SEO Blog: The Honeypot Module

Planet Drupal - Fri, 2021/09/10 - 9:03pm
The Honeypot Module The Honeypot Module combines the honeypot and timestamp methods of eliminating spam-bot submissions in your Drupal site's online webforms. Tracy Cooper Fri, 09/10/2021 - 14:03
Categories: Blog: 8 DrupalCon Europe 2021 sessions you won't want to miss

Planet Drupal - Fri, 2021/09/10 - 8:31am

We’ve compiled a list of 8 sessions you won’t want to miss if you’re attending the upcoming DrupalCon Europe 2021.


DrupalCon News: Calling all potential speakers for DrupalCon Portland 2022!

Planet Drupal - Thu, 2021/09/09 - 5:02pm

Whether you’re a first-time speaker or a bit more seasoned, we invite you to submit a session for our first in-person DrupalCon in 3 years! Our call for speakers is officially open now through 29 October.


Palantir: Making Your Open Source Community More Welcoming

Planet Drupal - Thu, 2021/09/09 - 2:00pm

What eight years of code conduct enforcement and conflict resolution has taught me

One of the things that’s remarkable about the open source movement is that it brings together people from all over the world to solve difficult and complex problems. 

While some level of conflict is to be expected - and can even be productive - effective collaboration requires that people treat each other with dignity and respect, even when they disagree. 

It’s why the vast majority of open source projects have adopted codes of conduct that set expectations for how people should interact with each other and what kind of behavior is unacceptable.

As one of the founding members of the Drupal Community Working Group, I learned many important lessons about community management and governance. Since stepping down from the group’s conflict resolution team at the beginning of this year, I’ve been discussing these issues alongside people from other open source projects who are equally as interested in fostering a more friendly, welcoming, and inclusive community for their contributors.

Lesson 1: Having a Code of Conduct is Not Enough*

In 2010, Drupal became one of the first major open source projects to adopt a code of conduct, but there were no structures in place to enforce it in a clear or consistent way. This meant incidents of harassment and abuse sometimes went unaddressed and valuable contributors left the community as a result.

Recognizing an open community need, project lead Dries Buytaert led a governance sprint in the summer of 2012 that resulted in the creation of several working groups, including the CWG, which was chartered in early 2013. During its first year, the CWG established the creation of a conflict resolution policy and process and mechanisms for community members to report incidents in a safe and confidential manner. Incorporating community input, we continued to evolve and refine our processes, documenting every step of the way.

Lesson 2: Understand the Scope of Your Community

Many open source projects are maintained by individual developers. Others are overseen by large technology companies like Google, Facebook, and Microsoft or nonprofit foundations like Linux, Apache, and Mozilla.

Conversely, Drupal is an independent project supported by a community of hundreds of companies and thousands of individuals who lend their time, talent, and treasure to support and maintain the project. Our large and broad community required clarity about what was and was not covered by our code of conduct.

Some of the CWG’s most challenging issues to address have involved questions of the extent to which actions that someone engages in outside of the project should impact their ability to participate in its community. Many codes of conduct only apply to actions that occur within designated community spaces and/or when someone is acting as an official representative of the project.

However, we agreed early on that the CWG needed to be able to address harassment of a member of our community by another member of our community, regardless of whether it occurred in a community space or outside of it. For example, we wanted to be able to address cases where someone was using their personal social media account to harass another community member, even if they were completely polite when interacting with that same individual in an issue queue.

Issues that fall outside the scope of our code of conduct include (but are not limited to) personal or workplace disputes between individuals that do not have a clear connection to the community, or situations that fall under the jurisdiction of law enforcement or other authorities and where no imminent or ongoing threat exists to members of our community.

Lesson 3: Leadership and Accountability Go Hand-in-Hand

One of the things that distinguishes large open source projects like Drupal is the number of leadership roles available to members of the community, which include maintaining a project, speaking at events, participating in working groups and committees, and assisting in the mentorship and onboarding of new contributors.

Those who serve in these roles act as representatives of the project and community and are responsible for the important task of fostering collaboration and ensuring the community remains a welcoming place. Being aware of and taking responsibility for their words, and actions, and the impact they have on others is paramount.

Remembering they are modeling behavior for others any time they interact with members of the community is vital.

The CWG created and adopted a Code of Ethics that outlines what you can expect of the group’s members and their responsibilities regarding confidentiality and conflicts of interest. This has not only helped people outside of our group feel more comfortable sharing reports with us, but has also ensured we hold ourselves more accountable.

In response to community feedback, we also modified our charter to institute term limits for members of the conflict resolution team and created a new review panel to provide oversight and act as a point of escalation and appeal. In order to provide both community accountability and perspective from outside of our project this panel consists of two community-elected Drupal Association board members and an outside representative appointed by the board as a whole.

Lesson 4: Accept That Some Questions Don't Have Clear Answers

No matter what you do to prepare, you will always run into situations that don’t have clear or obvious solutions. During my tenure on the CWG, we encountered several examples of these kinds of thorny issues:

  • How do we handle suspected incidents of harassment or abuse that we only have knowledge of third-hand or through whisper networks?
  • What can we do to help community members who are subjected to campaigns of anonymous harassment on social media when the platforms involved can’t (or won’t) take action?
  • How do we consistently and effectively enforce event bans across a broad, decentralized global community?
  • Is there a “path back” for those who have been banned from community spaces due to their past behavior? What does restorative justice look like within the context of an open source community?

Simply put: for these, and other challenging cases, a one-size-fits-all approach simply doesn’t work.

Join the Conversation

If you’re curious to learn more about how to help make your open source community a more welcoming place, you can view the session I presented at FOSS Backstage 2021, or see me speak at DrupalCon Europe (October 4-7) or All Things Open (October 17-19).


*This phrase comes from a 2014 article by Maggie Zhou, Alex Clemmer, and Lindsey Kuper

MacBook Air stickers - DrupalCon Dublin 2016 by Michael Cannon, licensed under CC BY-SA 2.0.

Community Culture Drupal Open Source People Strategy Support

Droptica: Analysis of the Drupal Code Security

Planet Drupal - Thu, 2021/09/09 - 11:33am

In the previous parts, we focused on Drupal configuration and the overview of modules and libraries. In the third part of the series on conducting a security audit, we'll focus on the overview of custom modules and themes. We'll perform an audit of the project repository, identify and analyze the elements worth paying attention to during the auditing process.

Overview of custom Drupal themes and modules

In custom Drupal themes and modules, attack vectors are most likely to appear. There's code there that isn't being widely used, unlike the code for contrib modules and themes. Therefore, it's not so well-tested in terms of security. In this article, I'll discuss a basic checklist used for auditing custom Drupal code. This list can be used as the basis for an audit of custom modules and themes.


We’ll start with the analysis of the parameters received from the user. Let's check out what is their type and how are they filtered. Drupal allows for using parameters in routings. These are dynamic values, incorrect processing of which may create attack vectors. If a query is created on the basis of a parameter and not filtered, this may cause a vector for SQL Injection attack, for example.

Next, we should look at the routing access configuration, specifically – the permissions that the user must have to get access. When declaring the routing, we need to define the requirements that the user must meet to gain access to the routing. We have to analyze the required permissions for every routing specified in our custom Drupal code and consider whether their level is appropriate. Specifying too low or incorrect level of required permissions will result in users having access to pages that they shouldn’t have access to. These can be both the pages listing the articles on your page and the pages listing all users along with all the data assigned to a given account. For this reason, the permissions audit is so important.


First, we'll analyze the correctness of the element types and check out if the correct type for a given field has been used. During the analysis of the types of fields used in the form, we may come across a field whose name and description suggest that it should be filled out with data of a specific type. However, the field's definition may allow the field to be filled out with other types of data. We should make sure that the definition of the type of elements corresponds with their purpose.

The next step will be to analyze the used methods of validating the field values in the form. Drupal allows for defining custom methods that validate the correctness of the entered data. We should test the correctness of the custom validation methods and make sure that only the valid data passes the validation.

The last thing will be to verify the presence and correct use of Form API provided by Drupal. We should analyze the way of using Form API, preferably using the documentation, and make sure that the forms are being created as directed.

The documentation specifies:

  • the cases where the use of a given field type is correct,
  • how to create the methods of validation,
  • how to use hook_form_alter,
  • how to create forms to be intuitive for the user.
SQL queries

Let's start with verifying the presence and correct use of the Database API provided by Drupal. It's equipped with methods providing security against attacks on the database. The correct use of API largely protects against attacks. We should particularly pay attention to whether input data filtering methods are used in the SQL queries. Drupal recommends using placeholders if there's a need to use input data, e.g., from a variable the value of which has been specified by the user in the form. Here's an example:

$foo = $this->getFormData(); $query = \Database::getConnection()->query(‘SELECT foo FROM {bar} b WHERE = ‘ . $foo[‘name’]);

In the code above, we can see that the value 'name' from the $foo array is being assigned to the query without filtering. In such cases, I recommend using placeholders.

$foo = $this->getFormData(); $query = \Database::getConnection()->query(‘SELECT foo FROM {bar} b WHERE = :name’, [‘:name’ => $foo[‘name’]]);

By creating queries in this way, we subject the variable $foo ['name'] to filtering, which will protect the query against SQL Injection attacks.

Filtering mechanisms

This means verifying the presence and correctness of the filtering data received from the user. We need to check that only TWIG is being used to render the variables in the templates, which by default filters the content of the variables and makes sure that they're safe. In the case of working with variables that are then used in translatable strings, we need to make sure that those variables are substituted for the appropriate placeholders. The plain text coming from the user should be filtered using the Html::escape() method if the user shouldn't be able to provide HTML tags in the text and the Xss::filterAdmin() function if they should be able to do so. If the user provides links, they should also be filtered.

Used for this purpose are the functions UrlHelper::stripDangerousProtocols() and UrlHelper::filterBadProtocol(). Filtering mechanisms are also applicable on the client's side. To clean up text in JavaScript, we should use the Drupal.checkPlain() function.

Sensitive data

We should check whether the code doesn't contain credentials or API keys. In some cases, we may come across the credentials left in the code of custom modules. Identifying them doesn't require much work.

Repository review

It's worth taking a look at the repository to search for sensitive information that may be stored in the files. The first step is to analyse the settings.php file and ensure that there are no credentials in it that would provide access to the database or other Drupal website components. Next, let's go over the environment variables' files and make sure there aren't any credentials in them. The credentials required by the environment shouldn't be part of the repository.

The next step is to check if there are no deeply hidden confidential files, for example – with SSL private keys or database copies or dumps. Sometimes the files that should never be in the repository get there by mistake. Some of them are, for example, database dumps or private keys. Identifying and removing them is recommended.

Analysis of the Drupal code – summary

In the third part of the series on performing a Drupal security audit, we've learned the ways of checking the code of custom modules and themes, we've audited the project's repository in order to make sure that no sensitive data was publicly available, and we've analyzed the elements that are worth paying attention to during the audit process.

Applying the tips I've posted in this article will make your application more secure. A code audit is a key element leading to better page security. It requires more time and knowledge than the update we covered in the first part and the correct configuration of Drupal we covered in the second part of the series, but the benefits of doing it are much more valuable than the time spent on it.

In the next part of this series of articles, we'll learn about external tools for automating the auditing process. It's the next step performed in a comprehensive security audit. Do you need help in performing such a task? Our Drupal support team has extensive experience in conducting audits.


Matt Glaman: How live streaming has funded my open source contributions this year

Planet Drupal - Thu, 2021/09/09 - 4:49am

Earlier this year, in early March, I started doing live development on my Twitch channel. I wanted to try a different way to maintain my own projects and contribute to others. I also wanted to explore live development streams to fund my open source contribution time while giving a way to provide a return on investment for any sponsorships. 

Earning revenue as a Twitch Affiliate

I was pretty excited that I hit Twitch Affiliate fairly quickly – 50 followers, 8 hours streamed, seven days, and an average of three viewers within a 30 day period. This allows me to earn a share of ad revenue from my streams. Although, to be honest, it isn't much. Most streamers earn money from their subscribers, and when folks spend bits to Cheer.

Let's take a look at my Twitch revenue since I started. You get a payout at a minimum of $100.


Evolving Web: Implementing Content Publication Workflows in Drupal

Planet Drupal - Wed, 2021/09/08 - 9:31pm

Producing relevant, up-to-date online content is a challenge for content managers everywhere. The bigger your content output and the more stakeholders you have involved in the process, the harder it is to keep track of whatever is being created, edited, and published. If this is your use case, what you need is a clear, easily manageable content publication workflow.

If your website is Drupal-based, you can create a content publication workflow by enabling a couple of modules that come out of the box, making life easier for your content team. In this article, we'll guide you through the most efficient ways to implement content publication workflows in Drupal.

What is a publication workflow? Why would you need one?

A publication workflow is a process many organizations adopt to create, review, edit, and publish content. It streamlines the process of getting input from different people in each stage of content publication. The main roles usually are:

  • Writers or Creators who amass information and write content;
  • Editors who review and edit content, request changes, and publish the content when it's ready for sharing.

This is how a simple content workflow looks like. In Drupal, you can add new publication states, the transitions between them, and roles for the stakeholders—which we’ll explain in more detail later.

You can also add specific roles for subject-matter experts who review the content for accuracy and more technical users who review the compliance of content from an accessibility or SEO standpoint.

A workflow determines the specific permissions for each role and how content will transition from one state to the next or move back to the previous one. For example, a Writer can send a content piece to the Editor for review, and the Editor, in turn, can send it back to the Writer for adjustments before publication.

You can also use the workflow to assign particular tasks to each role. For example, Editors can only create drafts, Reviewers can review and change the status, and only Publishers can make the content live. Besides, each content type can have its own workflow, since publication processes and checkpoints may vary from type to type. 

Establishing a content publication workflow has many goals, including:

  • Ensuring the content comprises only accurate, verified information
  • Preventing the publication of sensitive material or media that does not meet copyright guides
  • Efficiently avoiding "ROT" content, meaning redundant, outdated, and/or trivial
  • Assigning owners to each piece of content in its different states, reinforcing accountability
  • Avoiding content getting stuck in limbo, waiting for days or weeks to be edited
Creating publication workflows in Drupal

If you're working with Drupal, some modules can be of great help to establish and maintain your publication workflows. Let's look at some examples.

Workflows and Content Moderation

By default, Drupal offers very simple workflow features. You'll basically be able to toggle content between published to unpublished, and that's it.

If you feel that's enough for you, go for it. But if your publication processes are more complex and demand something extra, we definitely recommend combining the Workflows and Content Moderation modules, which come out of the box and are easy to enable.

The Workflows module provides an interface to create workflows with transitions between content states, while Content Moderation enables you to manage the roles and their permissions within these workflows. This is the easiest, most efficient way of implementing content publishing workflows for your Drupal website.

Here's what Workflows and Content Moderation allow you to create and manage:

  • New content states - Workflows and Content Moderation provide you with a defaulted workflow with three states: Draft, Published, and Archived. But you can add any states that suit your workflow, like Ready for Review or Needs Adjustment.
  • Drafts for live content - Workflows and Content Moderation allow you to create unpublished drafts of published content inside Drupal. Without this feature, you'd need an external tool like Word or Google Docs to create a new draft for any live content.
  • Various content roles - You can go beyond Writers and Editors, creating roles associated with different parts of the publication workflow, like Reviewer, Publisher, Legal Team, and more. Each one would have particular permissions, like moving content from Draft to Ready for Review.
  • Specific workflows for each content type - A simple blog post workflow could have fewer steps, while content types with more sensitive content, like press releases or publications, can demand more detailed and cautious processes.

Both Workflows and Content Moderation have been in Drupal core since version 8. To use them, go to 'Extend' in your Drupal admin toolbar, and on the core modules list, check Content Moderation and Workflows, and click 'Install.'

Setting up your workflow

Once the modules are installed, it's time to set up your publication workflow. First, go to Configuration > Workflow > Workflows, where you'll have the option of creating a new workflow or editing your default workflow.

Let's say that you want to edit the existing one to adapt it to your needs. In this case, once you click 'Edit,' it will take you to the workflow interface, which has four different sections:

States - Where you create or manage the node states. By default, you'll have Draft, Published, or Archived, but you can create as many states as you want.

Transitions - Where you manage the transitions between those states. By default, it gives you Create New Draft, Publish, Archive, Restore to Draft, and Restore. However, you can generate specific transitions, especially if you created any non-default states.

Applying the Workflow - Choose which content types your workflow will apply to. If you want a different workflow for one or more content types, you'll have to create a new workflow.

Default moderation page - Determine what state the new content will be assigned. Your best option is going with Draft, to ensure you won't publish any node before it's properly edited.

Setting up permissions

Now let's determine which kinds of permissions will be assigned to which roles within your content publishing workflow. To manage that, on the Drupal admin toolbar, go to People > Permissions > Content Moderation.

There, you'll see a list of permissions that can be checked under each role. For Editors, you may want to give permission to create a new draft, restore to draft, view unpublished content, and view the latest version. On the other hand, you may want to have o only Publishers publishing content, so you can deny Editors the ability to Archive or Publish.

Editing and publishing content within your workflow

Once you save the permissions, you're all ready to create and publish content within your new publication workflow.

Let's say you're a Publisher on the site and you have all permissions available. If you create or edit a piece of content, there will be a dropdown menu right below the text body showing all possible content states you could transition this piece to. All you have to do is update the content and choose a state from the dropdown before you save.

Note the dropdown menu with the Draft and Published state options.

However, if you're an Editor without permission to publish, you can edit the content, but the Published state will not show up on the dropdown. That means you can save a draft that is newer than the live content, but you'll need a Publisher to make the changes public.

On the View tab, you’ll also see the current moderation state and the states you can change the content to.

When you click on the Revisions tab, you see all the changes this content piece went through since it was created. There, you can set any previous version as the New Current Revision, meaning you'll restore it as the new valid draft for that content.

Finally, with the Workflows and the Content Moderation modules, you'll be able to see a Moderated content tab under your Content Overview, where you can view the moderation state of each node you ever created. There, you can also filter your content pieces according to their moderation state, be it Draft, Published, Archived, or any other.

Leveraging Drupal to the Max

Setting up a publication workflow is one of the most critical aspects of content management. Keeping track of your publication processes and improving them is vital to increase your website's content output efficiently and ensure you're serving relevant, helpful content to your audiences---saving you time to dedicate yourself to other strategic actions.

Now that you know how to implement content publication workflows in Drupal, how about learning how to use it to its fullest? Take a look at our Drupal Site Builder Track, in which you take 6 Evolving Web training courses and save 25% off the price of buying them individually.

Sign Up Now for the Site Builder Track

+ more awesome articles by Evolving Web

Promet Source: New Possibilities for High-Stakes Purpose

Planet Drupal - Wed, 2021/09/08 - 9:21pm
This week, September 5-11, 2021, has been set aside as National Suicide Prevention Week.  Suicide has reached epidemic proportions in the United States, with each year adding another dark chapter to the to rising trajectory.