Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough
Jun 15 2021
Jun 15

Imagine you created something and that something is a software. You wanted your creation to be used by as many people as possible, you wanted to make it universally accessible. So, you did just that, you made the software source code accessible so that anyone could inspect it, modify it and enhance its capabilities.

This is the scenario that makes an open source software what it is; a publicly accessible tool that is all for the community. It honours open exchanges, collaborations, transparency and perpetual development that is community-centric. These principles have made open source software become immensely popular today. And here is proof of that. 

The percentage of active public repositories that use OSS is shown through a graph.Source: Github

Many of the public repositories, like PHP, Java and .NET, use open source software and in heavy numbers. If we look at the revenue open source software is deriving, the numbers are again quite impressive.

The projected revenue of open source services can be seen in a graph.Source: Statista 

All these numbers speak volumes to the efficiency of open source software. However, if there is one aspect of open source software that needs some kind of assurance, I’d say it’s open source security. The reason is probably the fact that OSS is completely open for everyone, so it is assumed that something with this level of openness cannot be secure. 

In this blog, we’ll try to find an answer to the question, ‘what is open source security’ and see whether it is actually secure or not.

What Is Open Source Security?

Today, businesses try to leverage multiple software in their efforts to move forward in technology and open source is one software that is omnipresent in these efforts, be it just for its code. 

A graph shows an increase in the use of open source components per app.Source: Synopsys

The reasons for this elevated usage of open source components are plenty. 

The fact that you get to try the software before you buy it; 
The fact that support is free; 
The fact that there would be fewer bugs to deal with and faster fixes; 
The fact that software security would improve; 

To know more about the power of open source, read about the perks of being an open source contributor, leadership in open source, why are large enterprises investing in open source, why is open source recession-free, impact of open source during Covid-19 pandemic, and the significance of diversity, equity and inclusion in open source.

All of these account for open source to become a software that is quite pleasing to the eye. The last point that I mentioned may be the most pleasing factor of them all. But why? What is open source security? Is open source insecure? Let’s understand just that.

Like any other software out there, the OSS also goes through two main stages, the development and the production. And open source security works in both of them, managing and securing the OSS at all times by using certain tools and processes; all of this usually done through automation. 

Talking about the Software Development Lifecycle, open source security has three main responsibilities;  

  • It identifies open source dependencies in your applications; 
  • It provides critical versioning and usage information; 
  • And it detects and warns about any policy violations and its consequent risks. 

Moving on to the production phase, open source security continues to work diligently. Its main duties at this point are to focus on any and all open source vulnerabilities. It does so by; 

  • Monitoring vulnerability attacks; 
  • Blocking vulnerability attacks, if possible; 
  • And most importantly, alerting you for the same, thus making you ready to take action against them.

Be it a community driven open source or a commercial one, open source security works in much the same way. 

Delving a little deeper in open source security, is there an initiative or a body that is accountable for it. This was one question that I found myself asking while researching about this piece. And there is, it is The Open Source Security Foundation. It helps organisations relying on open source software to understand their responsibilities in terms of user and organisational security and verify it. 

The initiative focuses on aspects like vulnerability disclosure, security tooling and best practices, identification of threats and even digital identity attestation. All of these only aid in securing your projects, critical and otherwise, in a much better and efficient manner.

Is Open Source Good for Security?

The answer to the question ‘How does open source security work?’ is not a linear one. But if I had to answer it, I’d say open source security is nothing at all like Microsoft, which should provide a lot of clarity to you and instill a sense of faith in OSS.

According to Snyk’s The State of Open Source Security 2020 report, 

Open source ecosystems have expanded by a third in 2019; 
Open source security culture is focusing on shared responsibility; 
Open source vulnerabilities have reduced by a fifth.

A survey analysis is shown that depicts who the respondents thought was responsible for open source security.Source: Snyk

On top of this, the vulnerabilities that were found in open source as most reported weren’t high impact on software projects. 

These facts were enough for me to believe in the capability of open source security. However, for you, I am going to provide four more reasons.

Security that is transparent

The main benefit of open source security is that it is transparent. What I mean by transparent is that its source code is open. You can get information about the code base and potential bugs.

People can sift through the source code of any open source project and improve any imperfections, which would not have been possible if the source code wasn’t open. This further means that there won’t be any surprises as the chances of any malicious functionality would be quite slim with this level of scrutiny. 

Security that is reliable 

This advantage is relatable to the previous one. OSS openness has made it possible for its code to be continually tested. 

The online community, which is responsible for developing the code, is behind these tests, making the software more reliable and trusted. The software developed on such trust would most likely never crash and fail.

Security that provides quick catches and fixes 

After transparency and reliance comes the benefit of quick fixes. The open source community is again to be thanked for this. The many contributors of open source make it possible to detect any bugs and flaws and quickly patch and fix them, without any elongated downtime for your applications. 

Security that is sustainable 

Open source software isn’t going to go anywhere and would open source security become antiquated. The reason would be its growing community that would continue to expand indefinitely. Therefore, the platform would continue to improve and you would have the assurance of better security means as time continues to move ahead.

At the heart of every benefit of open source security is its openness and community. Is open source a security risk? Not really. Is it a full-proof solution? Again not really. Yes, open source security cannot provide you the guarantee of being full-proof at all times, but the fact that the open source security at least provides a better chance of being secure is enough to make it advantageous for us; after all, are there really any guarantees in life?

Are There Challenges That You Need To Overcome?

Moving on from the pretty picture of open source security, let’s focus on the dark side of the concept. Open source security isn’t always full of the joys of spring, there are certainly challenges that need to be overcome. Since open source has become prevalent in every business sector, so have the open source security vulnerabilities. 

The percentage of open source vulnerabilities in different business sectors are shown.Open source vulnerabilities by business sectors | Source: Synopsys

Ironically, most of the challenges coincide with the openness of an OSS, so the benefits become the drawbacks. Let’s take a look at them.

The openness isn’t without vulnerabilities

Much like any software out there, open source also comes with some vulnerabilities. Yes, the open source community aids in the remediation of these flaws, but they tend to widen the difference between open source safety and open source attacks.

A table elucidates OSS vulnerabilities.Vulnerabilities reported in OSS | Source: WhiteSource Software  

Yes, open source security issues come with their fair share of vulnerabilities, from XSS to information exposure, there is everything and these vulnerabilities keep on changing year after year. 

However, there is a silver lining in this challenge and that is the impact of these vulnerabilities. 

A graph reports open source vulnerabilities and the number of businesses they have impacted.Source: Snyk

XSS is one of the most reported vulnerabilities, however, it only impacts a low number of projects. This can be considered as a positive outcome of this particular challenge.

The openness lures attackers

The OSS code is open for everyone and so its vulnerabilities; and we certainly know that everyone includes people with malicious intent as well. So, open source vulnerabilities become an easy target for attackers.

The National Vulnerability Database, which is a platform providing information about the open source vulnerabilities that too publicly isn’t helping this challenge much. Don’t get me wrong, such platforms are indeed helpful in identifying the problems, but considering they are public and open, the attackers get their arsenal for the next target.

You may think that the known vulnerabilities should get fixed before the attackers are lured in by them. But that is easier said than done. The problem here is that the open source vulnerabilities are published at multiple platforms, thus tracking them becomes difficult. Even if they have been located, updating, patching or fixing can require some time and during that phase, you’d be at risk.

The openness might overlook quality 

There are a number of people who contribute to open source security and you cannot be sure that all of them would be security experts. Everyone in the community will not have the same level of skills and expertise. Therefore, the way they would create a piece of code would be different. This makes quality assurance a task that could almost be impossible to take on. Furthermore, the fact that there are no set standards for the quality of open source code makes it all more convenient to overlook quality.. 
 
All of this means that the quality might be overlooked and even compromised. The fact that only 8% of the WhiteSource survey respondents were concerned about the quality is a testament to this challenge.

The openness comes with licensing risks 

OSS may be free to use, but it does come with a number of licenses that need compliance; 110 licenses to be exact, according to the Open Source Initiative. These act as the guidelines for OSS source to be used.

With these many licenses, there is bound to be a risk of compatibility. Let’s understand this, some licenses are compatible, this means you can use them together. However, some aren’t, which means that using them together would put you at risk, like the Apache 2.0 and GPL v2 license.

What’s more is that, if you do not comply with the licensing guidelines of open source, you’d be making yourself open to a lawsuit. While I know this isn’t the kind of security concern we've been talking about so far, it is a security concern all the same.

Can You Overcome the Security Challenges?

The major challenge in open source security are the vulnerabilities. Detecting them and resolving them has to be the priority, if you want to overcome the challenges. Given the fact that open source vulnerabilities have risen in 2020, you need to be sure that you are not at an elevated level of risk.

A bar graph shows open source security vulnerabilities from 2009 to 2020.Source: WhiteSource Software 

Let’s see how these vulnerabilities can be caught in time, so that they do not affect your business by implementing some of these open source best practices.

Prioritising security, always 

The first part in overcoming open source vulnerabilities is to always prioritise security. This starts with the choice, whenever you choose an open source component to work with, security has to be one of the considerations in the choice. 

Usually, functionality comes as the main reason for choosing an OSS. However, just focusing on that can put you at a disadvantage. Think of it this way, an open source component that does not require any integrations with your codebase would remove any and all security risks, along with reducing the complexity of your source code.

Prioritising automation as a means to detect and monitor vulnerabilities 

Next comes the detection of the security vulnerabilities and automation comes quite handy here. Organisations, especially large ones, have a pretty massive codebase and going through it would be a mammoth task, if not automated. Detecting susceptibilities is already quite a lengthy process, even with automation.

You have to identify which packages are being used; 
You have to pinpoint the vulnerable functionality in your code; 
You have to map out the way that particular vulnerability is impacting; 
And then you have to work on rectifying the findings.

Such a process may only include four steps, however, it isn’t a trivial task.

One of the problems in overcoming the vulnerability challenge is that organisations, sometimes, have no clue that they are actually susceptible. The fact that the open source community has an extensive amount of data means that the vulnerabilities would be spread across that expansiveness. So, running automated scans for identifying vulnerabilities would never let them go unidentified.

Taking help of automation tools would not only help you get to the problem areas faster, but also keep doing it continuously. When you enforce automated tools to continually monitor security problems, you come closer to protecting your project and taking control over the open source components you are using.

Prioritising the involvement of the team in security

The last point to cover in order to overcome the open source challenges involves your team. There is a high likelihood that your developers would not be experts in security. And the people you may have in security would be lost in the developers’ realm. Since open source vulnerabilities require you to be efficient at both development and security, there has to be some training involved.

The ways to track open source dependencies are shown.Source: Snyk

Such a response for detecting open source dependencies is not ideal. So, aim for cross training your staff, the developers should be able to at least identify certain security vulnerabilities and the security team should have some understanding of the development process. 

If you think that isn’t a possibility, you can hire outside help to assist you in overcoming the challenges posed by the open source components. 

The Verdict 

OSS is on the rise and it will continue to grow in the future, there isn't any doubt about it. Along with that open source security will also strive to improve. Yes, there are issues that surround open source security, it isn’t perfect. I think that’s a good thing, because perfection cannot be improved upon and that means open source security has a lot of strides to make. 

Open source security operates on visibility and openness, and it also teaches its adoptive organisations to preach the same. Aiming for visibility in your source code would always keep you ahead of the vulnerabilities you might have. It would also provide you with knowledge of your dependencies and a clear understanding of your code. 

So, in that sense, open source software would be a great low cost addition to your project and open source security isn’t something that would ever hold you back. With the amount of open source security tools available today, that’s almost a guarantee.

Jun 15 2021
Jun 15

The digital landscape is continuously evolving. As a result, consumer expectations are dramatically increasing. Consumers now want highly-personalized, omni-channel, and interactive digital experiences. So, businesses need a web content management system (CMS) that can deliver it while successfully achieving KPIs and business goals.

Why Drupal?

With over a million users worldwide, Drupal is the CMS of choice for small to large business organizations. It is an open-source CMS platform with a plethora of features to create compelling websites of different kinds, some of which include:

  • Personal or corporate websites
  • eCommerce websites
  • Intranet
  • Community portals
  • Social networking sites
  • Forums
  • Resource directories
  • Blogs, portfolio, and multimedia sites
  • International multi-language websites

And the list goes on…

Wondering what makes Drupal such a versatile CMS? Let’s find out.

Benefits of Using Drupal as a CMS

There are many reasons why Drupal is preferred by various businesses, government agencies, and Fortune 500 companies. Let’s look at the most important ones in detail.

”web

Security
Security is the first priority for any official website. Drupal offers unshakable security, making it a popular choice among government and enterprise-level clients. Drupal’s security team is dedicated to identifying and analyzing potential risks in both Drupal core and contributed modules. Each contributed module undergoes strict review by the team before it goes public. Drupal also offers regular security patches to safeguard the website from exploits.

Flexibility
Drupal has a reputation for being one of the most flexible content management systems. It is easy to create and manage a wide variety of content types from videos to blogs, infographics, and podcasts on Drupal. Owing to its flexible design platform, it is perfect for creating content-rich websites for media and commerce. Drupal also has an elaborative script that allows infinite design possibilities along with better control over design element editing.

Performance & Scalability
More often than not, as the website grows, its speed starts to slow down. So, users have to constantly make adjustments. But, that is not the case with Drupal. Drupal is designed to grow exponentially. The website can extend from one to a hundred pages without changing anything. This scalability extends to website traffic as well. Drupal can handle sudden spikes in traffic better than most CMSs.

Customizability
Drupal is nearly 100% customizable. It boasts of over 40,000 modules and plug-ins to enhance the website’s functionality. To top it up, custom modules in Drupal give users the flexibility to create new features and/or tweak existing features to accommodate their business’s unique requirements. It also offers around 3000 themes that allow users to change the look and feel of their website.

Accessibility & Ability to Integrate Marketing Tools
Drupal is committed to accessibility to ensure an inclusive experience for all its users. All the features and functions of Drupal conform to WCAG, WAI-ARIA, and ADA guidelines. It offers various tools for content creation with WYSIWYG (What You See is What You Get) editor, flexible layouts, and multilingual functionality. It is also good with SEO and integrates well with popular marketing tools.

User Experience
Drupal is driven to offer customer-centric experiences. It has several content personalization modules that provide users with the right experience. Its enhanced caching capabilities help in page loading efficiency and speed. The layout tools allow easy creation of landing pages and reuse of content for different marketing campaigns. Overall, its UX is highly presentable, efficient, and inviting.

Dedicated Community
Drupal is an open-source CMS which means anyone is free to offer ideas, advice, and public documentation. Its community is highly active, approachable, and is steadily growing in the number of users. For every new Drupal release, the community contributes its time and expertise in reviewing, testing, and incorporating feedback to deliver the best experience possible.

Wrapping Up

With Drupal as your CMS, you are empowered to deliver impeccable performance and meet the demands of your consumers. Considering its various features, benefits, and constantly innovating ecosystem, opting/migrating your website to Drupal 9 would be a wise choice.

Ready to Start Your Drupal Journey? Contact Us!

Our web development wizards are dedicated to providing you complete assistance at every step of the way. To know more, send us an email at [email protected].

Jun 15 2021
Jun 15

We’re back with a recap of our favorite Drupal blog posts from last month. We hope you enjoy our selection for May!

Drupal 7 to 9 Migration Planning Guide

First off, we have a guide for planning Drupal 7 to 9 migrations shared by Anne Stefanyk of Kanopi Studios. With the end-of-life date for Drupal 8 in 2021, one year earlier than for Drupal 7, it makes the best sense for Drupal 7 site owners to skip Drupal 8 and migrate straight to 9.

Anne’s post includes a step-by-step planning and migration process, as well as some of the main considerations and challenges, such as making sure to have the website use the latest version of Drupal 7 to facilitate the migration, and taking into account the changes in certain practices in newer Drupal versions.

Read the whole migration planning guide

Write Better Code with Typed Entity

In the next post from May, Mateu Aguiló Bosch of Lullabot presents Typed Entity, a module that he built which can help you write cleaner, more maintainable code with fewer costs.

With Typed Entity, you create a plugin serving as a typed repository and containing the business logic rather than that of a specific entity. This can then be used to extend the class and create specific instances of the wrapped entities.

Mateu demonstrates this approach more in depth and shows examples of the module and how it works. He also includes a video version of the article for those who prefer watching.

Read more about Typed Entity

Streamlining Drupal Multisite Maintenance with Config

Next up, Byron Duvall and Bec White of Palantir.net show how to facilitate the maintenance of a Drupal multisite architecture with shared configuration rather than by using different install profiles. 

As opposed to the latter, shared configuration management is a much quicker and more straightforward process. It enables you to only make updates once (e.g. installing and setting up a module) and then rolls them out to all the sites with the shared config.

The set-up process as well as adding new sites and making updates are all simple as well; Byron and Bec also provide a step-by-step guide for each.

Read more about shared config management in Drupal

Migrating into Layout Builder

Moving on, we have a post by Chris Wells of Redfin Solutions recapping his session from the recent DrupalCon North America about migrating a Drupal 7 website to Drupal 8 with Layout Builder enabled on the new website.

The main challenge here was migrating the content which was created with WYSIWYG templates in Drupal 7 to pages created with the new paradigm of Layout Builder using overrides. For this, they used Drupal’s Migrate API.

Importing the blocks and nodes are both fairly straightforward parts of the migration; the key change is transforming the data into a format which can be read by Layout Builder, for which they use their custom process plugin.

Read more about migrating content to Drupal 8

Is Drupal Right for Universities?

Another enjoyable post from May was this next one by Mediacurrent which breaks down why Drupal is a top choice for higher education websites. Indeed, Drupal is particularly well suited to the digital needs of universities, with its high commitment to accessibility, multilingual capabilities, mobile optimizations and personalization features.

On top of that, Drupal also provides great multisite capabilities with easy and efficient management. It can help with brand visibility with its out-of-the-box SEO features, and its focus on security and privacy is now even more important with stricter privacy laws. It’s no wonder that over 70% of leading universities use Drupal to power their digital experiences.

Read more about Drupal in higher education

Books/ 31 Days of Drupal Migrations

We continue with David Rodríguez’s review of the book 31 Days of Drupal Migrations written by Mauricio Dinarte. The book is based on a series of Mauricio’s articles from a few years ago and is the most comprehensive resource for up-to-date information on the Drupal Migrate API.

David provides an overview of the book’s key information and its most important points. He highly recommends every development team should have a copy at their disposal; he has nothing but high praise for the book, in terms of both style and content usefulness, and gives it a 5 out of 5 in every category he looks at.

Read more about 31 Days of Drupal Migrations

Drupal 9: Setting Up Multilingual Content Views

Nearing the end of our selection for May, we have a blog post by Philip Norton on #! code explaining how to set up multilingual content views in Drupal 9. The issue with Views is that the wizard does not support multilingual content and this ends up creating lists of content with duplicated items.

As Philip shows, though, the solution is very straightforward. You need to first add the Default translation filter, then select a different rendering language, both of which can be done through the admin interface. This will also ensure that a content view will fall back to the original language if there’s no translation for it.

Read more about setting up multilingual content views in Drupal 9

Makers, takers and altruism

Topping off this month’s list, we have a post by Morpht’s co-founder and managing director Murray Woodman, who shares his thoughts and ideas regarding a recent post by Dries Buytaert on balancing makers and takers in open source.

Murray further elaborates on some of Dries’s key points with a simulation of “green beard altruism” by Justin Helps, which highlights the importance of encouraging altruistic behavior to ensure the sustainability of a project.

In the second part of the article, he explores how these lessons can be applied to the Drupal community, coming to the realization that we’re already taking a lot of the right steps, e.g. with the financial sponsorships of the Drupal Association and the contribution credit system.

Read more about altruism and sustainability in open source

Different hands holding up paper house

This concludes our recap for May. We hope you enjoyed (re)discovering the articles! 

Jun 14 2021
Jun 14

What are Layout Paragraphs?

According to their project page, Layout Paragraphs provides an intuitive drag-and-drop experience for building flexible layouts with paragraphs. Paragraphs are the preferred method of dealing with complex content structures inside of Drupal, and Layout Paragraphs are for dealing with complex layout structures in those paragraphs. 

Layout paragraphs are meant to help separate the content and structural needs of site builders and content editors. The concept of Layout paragraphs is not really a new idea. It builds upon a long history of layout systems including panels, display suite, blocks and panelizer, but utilizes more core API's like Entity API and Layout Builder API.

When using paragraphs in the past, extra paragraphs, or multiple versions of the same paragraphs, were needed in order to provide different layouts and styles for content creators. With a very plain editing experience, it could be very difficult for content creators to get an idea of how their page will look on the front end. Layout paragraphs are here to help simplify what content paragraphs are needed, and provide a better idea of what the page will look like when editing.

With some practice and refining of the steps below, it is possible to create and replicate a powerful layout and content system that your clients will love using. So let's get to it.

Setup steps

  1. Install modules and themes.
    • Modules required: 
    • Optional:
      • gin (recommended admin theme. Claro and some others work well too.)
      • gin_toolbar (recommended if using gin for your admin theme.)
  2. Setup the main settings for layouts and paragraphs.
    • Visit the "Layout Paragraph Labels" settings page - admin/config/content/layout_paragraphs/labels.
      • Select Show paragraph labels.
      • Deselect Show layout labels (I find this not needed, if layouts are easily distinguishable from each other).
  3. Setup a paragraph to use as the Layout source.

    This is known as a layout paragraph.

    • Call it Layout (or whatever helps you to know this is layout related) You can have multiple paragraphs that handle layouts (like one for large complex layouts and one for simple layouts inside of a layout), but best to keep simple.
    • In Behaviors, Set to Layout paragraph.
    • Select the layouts that you want to have available. You will have to come back to this as you create/update/delete layouts
      • Default core layouts are available.
      • Easy to create custom layouts using Core layout API.
    • No other fields are required on this paragraph, and nothing needed in the form display or display settings.
      • Text fields for headings and select fields with options for setting classes are things you can try to work in here, but really no other fields are needed.
  4. Setup some paragraph types that will be used in the layouts.

    These are known as content paragraphs. This part is up to you and your needs for the site.

    • Good recommendation for content paragraphs are just simple paragraphs. Some examples include:
      • One with just a WYSIWYG body field. 
      • One with an unlimited link field.
      • One for with an unlimited media field to post single images or multiple image slideshows.
  5. Setup a layout field on a content type of your choice.

    For this I prefer to keep it simple. I will have just the title field, the layout/content field, and then rename the body field to something like "teaser/summary" and set that up to only be used in teasers and meta tag descriptions.

    • Create a field of paragraph type. I usually call it field_content of field_paragraphs.
      • Set the field settings to Unlimited.
      • Include/exclude the paragraphs that you want available in your layouts. This is something you will probably have to come back to as you add new paragraph types to the site.
      • Must include the paragraph that is acting as the Layout paragraph.
    • Set the Form display.
      • Set Widget to Layout Paragraphs.
      • Set view mode to Preview. 
      • Set 0 nesting depth (prevent layouts in layouts. I like to keep it simple, but it will come down to your needs and desired user experience.).
      • Set require paragraphs to be added inside a layout (a layout must be chosen first before a content paragraph can be set).
    • Set the Display.
      • Set the label to Hidden.
      • Set to format to Layout paragraphs.
      • Set rendered as Default
  6. Place stuff in your new layouts.

    • Create a new page of the content type with your layout field.
    • When you hover over the field, an add icon will appear. Click on it and you will be able to add a layout type paragraph.
    • When you add a layout, a modal will popup where you can set the desired layout style as well as any other options that are available (this is based on what contrib you have installed or if you have any fields on your layout paragraphs).
    • Select a layout style, like One Column, and select accept.
    • You will see a "block" representing your new layout. Hover over and you will see an add icon appear at the top and bottom of the area.
    • Click on one of those icons, and you will have the option to set one of the Content paragraphs you've made available. 
    • The paragraph fields will display in a popup. Add your content accordingly and press accept.
    • Repeat with a couple more content paragraphs.
    • Make sure to add the node title, and press save.
    • Review your new node. Things may look slightly off (or wildly off). It's based on how the CSS is working in your theme. But rest assured, all the pieces of the puzzle are in place for you to work your magic.

You can change the layout and move content around.

Conclusion

Many of these steps are customizable based on your needs and your Drupal development skills. I've used select fields and view mode selection fields inside of the layout paragraphs and content paragraphs to allow content creators to get creative and apply different prebuilt styles. I've played around with preprocessing, twig templates, and extra fields to build complex displays, but still allowed for a simple user interface. The possibilities are up to you.

Jun 14 2021
Jun 14

I'm a fan of configuring things for display through Drupal's admin UI. It gives site builders confidence and power. What if you want to place blocks or views listings in amongst fields on pages of content? For example, to display:

  • A listing (view) of related content, such as accessories for a product
  • A standard contact block, advert, or some other calls to action in the middle of the content, exactly where the user is best 'caught' in their journey, rather than having to stick those in sidebars or after all the content fields.
  • Some specific value(s) pulled from fields on some indirectly related entity, through a token, such as details from a taxonomy term representing the 'section' that a page is in.
  • Consistent relevant links on user profiles to take people to common destinations

Drupal's usual blocks system allows you to put these in sidebars or above/below the usual node fields, but not between them. You could use a 'heavyweight' system like Layout Builder, Panels, or Display Suite, but those tend to entirely change the way you configure or edit your content. You could get a developer to override twig templates or write custom PHP. But is there a middle ground?

Well, of course! You might have noticed some modules already allow their page additions to be moved around amongst the usual fields on content. See these rows without widget or format settings in this following screenshot, which aren't for ordinary fields at all? Wouldn't it be great to be able to add your own?

Profile display settings with 'extra fields' highlighted

This is where the Entity Extra Field module (entity_extra_field) comes in. It supports embedding blocks, views or values to be replaced via tokens. So a site builder can set these up to be managed just like ordinary fields on the page (whether it's a node, term, paragraph, or any other type of content). Each one would act as a sort of 'pseudo-field', rendered as part of a display mode amongst the ordinary fields. It also works for form modes - so you can display useful content beside existing field widgets, perhaps displaying relevant related data to editors in the places that they would be entering content about that data.

Entity Extra Field supports visibility conditions (just like blocks, but for views & tokens too) and passing & selecting contexts for blocks. These give it quite a lot of power - for example, to conditionally hide a field rather than just using Drupal's ordinary display settings for it. So I believe this module does a better job than the older EVA module (for views), and my own similar EBA module (for blocks) did. In fact, I recommend that anyone using my EBA module in D7 should use Entity Extra Field in its place when moving to Drupal 9. Here are some screenshots of its interface - first for selecting a view to add to content:

Entity extra field administrative interface for selecting a view to add to an entity display.

And for choosing a block to display - in this case, a custom one that requires a context:

Entity extra field administrative interface for selecting a context-aware block to add to an entity display.

Each 'Extra field' gets shown on all entities of the type/bundle they are configured on. So there's no need to constantly remember to add a common block or view every time you create/edit a page. If you do want to have different ones on different pages, then you should use Views Reference or Block Field. These modules provide true fields for editors to choose which view/block to display on each individual page.

The code inside Entity Extra Field uses hook_entity_extra_field_info(), which acts just like its Drupal 7 predecessor, hook_field_extra_fields(), which I've written about before. So you could write code using that to add your own page additions too - but given that blocks, views, and content accessible via tokens are possibly the most common things to embed, that suddenly feels unnecessary. Even as a developer, I'm glad to avoid writing code that would need maintaining anyway.

I've been privileged to be able to contribute fixes & functionality to the Entity Extra Field project, resulting in a recent new release. My time for that was essentially sponsored by ComputerMinds and one of our clients who would use this site-building capability, especially around block contexts. So thanks to them! And of course a big thank you goes to Travis Tomka (droath) for making the module, and accepting my many issues & patches!

Photo by Y. Peyankov on Unsplash

Jun 11 2021
Jun 11

After quite some Google searching I found some answers that came close, but nothing that worked straight away. So to prevent you from puzzling and searching, here is how to get the image field url from a referenced node in a Twig node template

Use this code for example in node--blog--teaser.html.twig :

{{ node.field_REFERENCE.entity.field_IMAGE.entity.alt.value }}

Replace 'field_REFERENCE' with your node reference field system name, and replace 'field_IMAGE'  with the system name of your image field.

And by the way: more on Twig file naming conventions in Drupal here.

Drupal theming Planet Drupal Written by Joris Snoek | Nov 06, 2021

Join the conversation

Jun 11 2021
Jun 11

Drupal 8 Made Everything Better

From the beginning of Drupal 8, everything in the lifecycle just got better - including moving to Drupal 9 and beyond.

Design and research have not really changed, but once you begin to build, you start to see the changes. Drupal 8 and 9 are far more feature-complete, requiring far fewer contributed modules. With an elegant configuration management system built-in, it is straightforward to keep all settings in version control.

Beginning with Drupal 8, there is now a planned and continuous improvement release cycle for new versions of Drupal. This means that new features don’t have to wait for a full new major release: instead, they are incrementally included in new software releases every 6 months.

From a typical release page, they say “This minor release provides new improvements and functionality without breaking backward compatibility for public APIs”. Some examples of new functionality which have come online through this process include, media handling, content workflow, layout builder, to name but three.

As before, minor upgrades are straightforward, but the most significant change is that major upgrades no longer require a complete rebuild of your site. As only deprecated APIs are removed in each major upgrade, upgrades can now be completed in a fraction of the time. In fact, most are completed in a matter of days, and not months as before, and usually with only minimal effort on the part of the site owner.

A site redesign can also be performed at a time dictated by business needs, and does not need to be coordinated with a 3rd party release cycle. 

Jun 11 2021
Jun 11

Is it possible for us to finish everything we start? Is it possible for us to achieve every milestone that we set for ourselves and stick to every new year’s resolution we make? In a perfect world it would be, but sadly we do not live in a perfect world. 

And it’s not necessarily a bad thing to take a step back from a project you know you won’t be able to finish. I started painting my room when the pandemic began as a way to waive off the boredom, and half-way through I realised painting wasn’t for me. It was too exhausting and I wasn’t even good at it and most importantly it made me lose focus from my actual paying job. You can write a lot when you have paint all over your work desk, trust me. 

So, these unfinished projects have to be taken on by someone else, right? You can’t leave the room half painted, that would be a look the 21st century isn’t ready for. So what happens? Do you hand over the paint and the brush to the person taking over and forget about it? Not exactly. 

There are a whole bunch of things that you have to relay during the handover and keep a diligent eye on the new person to ensure that he is taking the project into the desired direction. You have to have the room painted as you had initially planned, you can’t expect a subtle lavender theme to turn out to be a neon orange at the end; that’d be a catastrophe of the highest order.

Now, we won’t be talking about painting rooms throughout this article. No, what we will be talking about is the way project managers handover business projects that are work-in-progress. What are aspects they focus on during the transition of duties, so that they do not affect the project’s completion? And does the transfer actually become fruitful for the project? Finally, I’ll share some instances from OpenSense Labs, wherein our project manager had to handover a project. So, let’s start.

The Handover Begins With Knowing the Company

If we look at project handovers, there are two scenarios that basically decide how much work it is going to take from the project manager himself. 

  • One of them is when a project is being transferred to a PM who is already a part of the organisation. 
  • And second is when a new project manager is hired within the organisation to take over an already in-progress project.

The first step we are going to discuss isn’t really necessary for the first scenario, but quite crucial for the second. And that is the knowledge of the company, its mission, its way-of-conduct and its overall cultural dimension.

Someone who has been a part of the organisation, even if it is for a little while, would already be familiar with it; however transferring project ownership to someone new would have to go through an acclimation process and that is what this step of project ownership transfer is all about.

Why is this acclimation important?

Because it provides perspective 

Being familiar with the organisation’s vision gives a perspective on things for the PM that he otherwise may not get. This perspective is important for things to sail smoothly throughout the remaining life of the project since it’d provide you with a purpose along with an overview.

Because it helps in communication 

Every organisation has its own culture. At OpenSense Labs, we follow the opposite of a traditional work culture with stringent rules and regulations that limit the scope of projects and employees. Liberty, openness and equality are some adjectives that would describe OSL’s office regime. This culture is directly related to how communications go down the hierarchy. Being familiar with it helps new PMs to fit in with the team and take things forward in a way it is used to.

Because it helps in decision making 

When you study the company you are going to take a project from, it would help you make better and more informed decisions without any disruptions.

A table is comparing a company's local process to global processes.Source: Toptal

The above image talks about some of the daily decisions a PM has to make, and knowing how to make them would make his/her work a lot easier.

Familiarising Yourself With the Nuances of the Actual Project Is Next

Now, you know the company, but do you know the project and what place it has in the company’s revenue stream? Knowing that is the next stage of project ownership transfer. This is also referred to as the knowledge transfer or at least its beginning.

Your organisation is going to have a number of projects running at all times, they could be about helping small entrepreneurs become more successful, however, all of these projects cannot be at an equal level of prominence. Some would be high priority and some would be on low. Identifying the significance of your project is what you would need to do first.

Once you have done that, you can start looking at your own project with a fine tooth comb. You would need to know everything about it to ensure that the outcome is what is expected. Start with the generic nature of the project. 

What is the project type, in-house or external?
What does the target audience look like?
What is the marketing strategy?
What are the competitors providing?

An answer to all of these questions will help you get a better understanding of the project. When you have that, then you have to dig deeper into the transition and learn about the change, everything preceding it and everything that has to follow.

What kind of progress has been made in the project?
Which aspects of the project are outstanding?
What tools and processes were being followed?
What are the restrictions and blockers holding that project back?

These questions are extremely important to ask as they would help you in knowing the deadlines and reaching them on time. Being familiar with all the issues hindering the project completion, be it about the team or client communication, won’t let you get blindsided, which can happen after a takeover.

Then You Get Acquainted With the Stakeholders and the Team 

In every project transfer, there are people who play a significant role in its completion. These are the people who are essentially responsible for all the work that goes into the project and its consequent success. As the new project manager, you ought to become acquainted with them from the very first day of the ownership transition because acclimating to people is the most difficult task of any process.

The Stakeholders

Starting with the stakeholders, these people are the ones who are going to directly benefit from the success of the in-progress project. It can be the client and his organisation and it can be people within your organisation, if it’s an in-house project affecting them.

Talking about the client, the focus is to make him comfortable with you and you being comfortable with him. During the entire transition, the client has to be kept in loop. Even if the previous PM had been fired, the client has the right to know. 

At OSL, we introduce the new PM to the client in phases. After some time, the new PM is involved more by making him prepare meeting agendas and answering client questions.

At OSL, we introduce the new PM to the client in phases. We ensure that once the former introduction has been completed, the new PM is always present in client calls even if he/she is not contributing anything. Even without the contributions, they’d be learning and that is what the transition is all about. After some time, the interaction is made more frequent and the new PM is involved more by making him prepare meeting agendas and answering client questions. During this time, the old PM is always there to handle any mishaps. Once those mishaps are no longer happening, it means the comfort is achieved and the new PM is given the command.

For an in-house project, the stakeholders would be the people using the end-product. Because they need it they’ll become your project’s advocates and in turn yours too. You have to capitalise on that. You should make yourself acquainted with them and get their feedback on the project you are delivering by testing an early version of the project on them as an option. 

Every stakeholder of the project would always want it to be successful and it is up to you to get them involved to improve your chances of success.

The Team 

Then come the people whom you would complete the project with. There are three things you have to be mindful of. 

  • One is the team’s structure and hierarchy, if there is any. You should know how they operate and what is the working dimension, remote or co-located or both. 
  • Second is to dig a little history and know about any grievances they might have had with the previous manager or even among themselves.
  • Finally, you need to know whether the team you have is of the right size, you could be understaffed or overstaffed.

These help you become one of them and make everyone feel included by eliminating any kind of friction between you and them. Having the old PM with you during the transition can help make the acquaintance process go by faster because you’d know the kind of authority and system the team is used to making the transition easier for them. Of course, if the PM has already been fired or there was no PM at all, it might be a possibility.

Understand how human psychology works in the project management here.

Knowing Exactly What Is Required of You 

Now comes the part you will play in the project. Of course, you are going to be handling it, but where would you start delivering?

Here the first important thing to know is the reason you are taking over. The previous manager could have left the organisation or he could have been made to leave. The former scenario doesn’t really have any relation to the project itself, but the latter could and you ought to know that. If a PM was removed or fired, there has to be a reason, right? He may not have done the job in the appropriate manner or he may have mismanaged the project and even the team, whatever the case, learn about it and start rectifying from the get go. Trust me that is the first plan of action expected from you.

You can only do that once you know what exactly the role of a PM is in the organisation. By this, I mean a few things.

  • You need to be aware of the way you are going the handle the client and the team;
  • You need to be aware of the extent of your duties and whether they go beyond the scales of the project;
  • You need to be aware of the procurement process as well as vendor selection as you may have to do it at some point;
  • You also need to be aware of the way your performance is going to be evaluated, how and who is going to review it.

A knowledge of all these aspects will only help you perform your duties better and get the project completed without any impediments.

Read our blog ‘Feature Prioritisation in Projects: How It's Done Right?’ to know more about project management and the feature prioritisation that goes in it.

The Final Handoff 

The above mentioned project handover necessities actually sum up the entire process and usually most of it is mentioned in the handover plan or document, which the old PM goes over with the new PM in due diligence. 

And it doesn’t happen overnight, it takes from a couple of weeks to a month, the gradual nature of the handover is what makes it fruitful for the project. Taking a few steps a day by breaking the transition into pieces that are easy to comprehend at a time is essential. Another aspect that is essential is you being shadowed, be it by the old PM or the team, that is what’ll help you learn the ropes faster.

You wouldn’t take the reins at once, it would come in increments of each step we discussed. 
You won’t be expected to answer the client worries from the get go;
You won’t have to deal with the developers from day 1;
You wouldn’t be expected to make a low performing project turn around at once. 

Everything would happen gradually. Once you have the apprehension of the company’s vision, the project itself, the stakeholders and the team along with everything that is expected of you, you’ll be ready to wear the PM hat and take the project on yourself. And the final handoff would be complete.

The Other Side of the Handover: OSL Handover Manual  

OpenSense Labs have successfully completed many projects in its life, however, sometimes these projects have been the rewards of more than a single project manager. There isn’t a particular reason for that. Sometimes the project manager had to hand over their work because he was leaving the organisation and sometimes it was because he was overburdened and couldn’t give his complete attention to the project. 

While researching this blog I talked to two of our project managers, Yash Marwaha and Abhijeet Sinha, to get a better understanding of project handover. Project handovers are a two way street, up until now we have discussed the side of the PM who will take the project forward, now let’s look at the other side and delve into the project transferer’s perspective.

Yash and His Handover Precision 

Yash is all precision and accuracy with a set system to make the handover as smooth as possible. The first thing he does is identify the type of project, which could be a long term engagement or support and maintenance. For him, this identification decides the timeline of the transition.

The steps that he follows usually go like this.

  • Creating a handover document and going over it with the new PM; 
  • Informing the client; 
  • Planning induction sessions with a handson walkthrough; 
  • Introducing the new PM to the client; 
  • Being available on calls between the new PM and the client until a comfort level is reached;
  • Finally changing the ownership when that happens.

This is a great system to follow for a handover, yet Yash has had to take over a project even after the handover has been completed. The reason was the new PM not being comfortable with the client. Even after doing everything by the book, things can still not go as smoothly as you may have wanted. You cannot control all the variables, let’s learn that from Yash.

Abhijeet and His Handover Diligence 

While Abhijeet follows much the same steps as Yash, he doesn’t focus too much on the time, rather he focuses on diligence. What I mean is he doesn’t feel that a handover has to be confined to a specific timeline. A similar project could have been handed over in a week, but that doesn’t mean that the current ownership would go the same way. For him, when you rush things, diligence goes out the window and chaos ensues.

He has two project transfers to prove his point. 

  • He had to hand over a project, redressal of a major tourism website in Kansas City, to Yash. The handover happened within 3-4 days, pretty quick, right? The reason was that Yash was already in contact with the client making the transition as smooth as smooth could be.
  • Then there was Earth Journalism, wherein an all new PM had to be assigned the ownership. He kept her in the loop for the client and the developers. He helped in removing the friction between the new PM and the developers, which happens in every transition, at the same time he ensured that she knew the contextual needs of the project. This transition took about a month. Learn more about the work done on Earth Journalism Network by OpenSense Labs here.

Project transfers can be a tricky business. There are a lot of parties involved and all may not welcome the change. As the project transferer, you have to be patient with everyone. You have to ensure that everyone involved is in favour of the new person, if not the final handover would not be the end of it. 

There is another thing that the OSL team shared with me and that is never ever transfer ownership of a three-month project mid-way. If you are to do it, do it in the beginning itself. There is no point in bringing a new PM after two months, it’s not going to benefit anyone.

Whether you are taking up a new project or getting a handover of an ongoing one, learning through Drupal website projects can be very handy. Learn what are the infinity stones of Drupal development, how to start the Drupal project the right way, how to manage your development workflow for Drupal project, and why product mindset should be preferred over project mindset.

Conclusion

In the end, all I want to say is that people have a tendency to take time to learn things and perform them in an efficient manner. Rome wasn’t built in a day, right? So, what needs to be done during a project handover is valuing the learning curve. It’s going to take time and patience to make it fly. The kind of details an on-going project can have are quite diverse and making the new project manager get a hang of them is what matters. And that requires time from the organisation given to the new PM and his efforts in making that time worth it. 

Jun 10 2021
Jun 10

When you're working on your Drupal SEO, the Meta tags module is important to your site because it tells the search engines what the content you have is all about. That is right, it's pretty much data about data. And while this seems redundant, it is incredibly important for the overall optimization of your site.

A controversy occurred during the dawn of the search engines (circa 1997) when many people abused meta tags by stuffing them full of keywords. While they were invisible to visitors, search engines gave a lot of credence to the meta tags, so it was a viable way to get to the top of the search engines.

These days, search engines use metatags less for rankings and more for determining what your website and pages are about and which keywords they best fit. Making sure these tags clearly state what your site and pages provide to a visitor will go a long way to ranking in the search engines.

There are also specialized tags that can help with local SEO and provide information that can get your products listed in the Shopping sections of the search engines, which is always helpful.

To get step-by-step instructions on how to make sure your Drupal website's metatags are properly set up, download our free Metatag module guide available within our Drupal SEO Guide section.

***

If your website has specific needs (e-commerce, local, etc.),
feel free to sign up for a free no-obligation consultation
to see if Volacci can help you with any SEO problem you might have.

Jun 10 2021
Jun 10

As a company that believes that the best outcomes are achieved when people are able to create and collaborate in open, diverse, and inclusive environments, we’ve spent the last few years strengthening Palantir’s commitment to being an equitable and just organization. We have evolved our compensation, performance, and reporting structures in an attempt to proactively identify and remove systemic barriers to equality, becoming less hierarchical and more agile. To date, these efforts have included:

  • Establishing an equitable compensation structure with defined salary levels that provide equal pay for equal responsibilities.
  • Instead of reporting to a manager, each person now has a P.O.D. (Professional and Organizational Development) team that provides facilitation and coaching in performance, growth, and development.
  • Creating a career grid that’s supported with a role-based structure that demonstrates what opportunities exist for advancement and articulates the skills and expectations for each level so that individuals and P.O.D.s are orienting learning and growth conversations around a standard for promotions and opportunities.

We know, based on our experience with the Drupal open source community, that diverse teams drive innovation and improve quality. As Drupal’s Values and Principles state, “the people who work on the Drupal project should reflect the diversity of people who use and work with the software.” We agree. And while Palantir is already one of the more diverse and representative teams in our industry, we are not yet where we want to be. We are committed to doing the work necessary to build a team that incorporates diverse experiences and strengths where everyone can bring their best selves to their work and make space for others to do so as well.  

Ironically, the tumultuous pandemic year brought tremendous stability to the Palantir team itself. Our internal commitment (which we nicknamed CODENAME Armadillo) ensured that there were no layoffs or salary reductions in 2020, which gave us individually and collectively the space to focus on what we needed to be healthy. We invested in our existing team’s ability to build the resolve and resilience we would need to reimagine and redesign what we wanted our next normal to be. 

Now as we re-emerge, we have begun adding to the Palantir team, allowing us to examine what has and hasn’t worked for us in our hiring process. Adding several positions in succession has given us the chance to experiment with this process as we seek to redesign a more effective, equitable and agile process. 

The Challenges: 

  • Workplace inequality often has its roots in hiring processes that prioritize privilege and connections over potential. Qualified candidates can be passed over if they don’t fit into patterns of what the company or those in a position to hire might have seen work previously.
    How might we create opportunities for truly interested candidates to demonstrate how they would be “culture adds”, rather than just looking for “culture fits”? 
  • In the past, Palantir’s hiring process was most successful if a candidate was already familiar with the company (and was even better if the candidate knew one of us well).  
    How might we create a scalable, equitable environment that allows everyone to experience the advantages of insider access to a Palantiri?
  • Palantir’s hiring process could be long, with three rounds of interviews (screener, team and CEO) all conducted by in-house team members with other primary responsibilities. That long duration created an unintentional slant toward those who already had jobs (as those who didn’t often took other positions while our process was still unfolding). 
    How might we accelerate the process, without compromising our ability to manage hiring in-house and involve the team?

Thinking about these questions, we have spent the last few months conducting a series of experiments designed to reduce bias in our hiring process. Here are some of the approaches we have found most successful in addressing the questions above in the initial gates of the process: the application and the initial screening conversation.

Anonymous Applications

Our efforts begin with the application stage. Our job postings include a salary range and are reviewed for gendered or biased language. When we receive resumes and cover letters, a team member who isn’t involved in the hiring decision anonymizes them, removing names, addresses, and education information that shouldn’t influence our hiring decisions. (There is software that will do this automatically for larger firms, but it doesn’t seem available to small firms and our HRIS system doesn’t yet offer this feature.)

Knowing that our process (and indeed our company!) works a little different and can ask a lot of our applications, we want to make sure that we’re making the process informative and valuable for them as well. To that end, we host a webinar that candidates can attend or submit questions for and watch afterward, if they cannot attend. During this webinar, they have the opportunity to learn more about Palantir and the position and may anonymously ask questions. Our hope is that this is a very safe and welcoming environment where they can begin to see what it might be like to work at Palantir.

A Conversation, not a Challenge

After the webinar, if a candidate chooses to continue pursuing the open position and Palantir chooses to invite them, they are invited to a video interview with our Employee Experience Manager and another team member. Prior to that interview, candidates are asked to share something that demonstrates a required skill for the position. 

For technical positions, they are provided with some sample code from a variety of languages and frameworks. The code samples we use are drawn from public code repositories and aren’t written by one of our team members. 

During the technical interview, the candidates are asked to choose one of the code samples and share any observations, experiences, or thoughts they may have about it. Unlike in a coding challenge, we don’t ask candidates to author code on a whiteboard, and there are no planted bugs or tricky logic to uncover in the samples we provide. The questions are scripted in advance and asked in the same order and same way for each candidate. 

The point of this exercise is to demonstrate the candidate's ability to abstract from the code level to talk about functionality, purpose, and risks. As consultants, we often need to talk about our work with both technical and non-technical audiences. 

For non-engineering candidates, we ask that they record a presentation on a topic about which they are knowledgeable and passionate, or that the candidate write, draw, or record a video about which Palantir value resonates for them. As we continue to hire people for additional roles, we will find ways for them to demonstrate their unique skills and point-of-view. 

During the first interview, the candidate can also ask questions and learn more about Palantir. If the candidate and Palantir both choose to move forward, the next interview is a team interview, followed by an interview with one of our CEOs prior to an offer being made. (Those interviews are largely unchanged from the previous hiring process.)

Preliminary Results

Our focus in this round of iteration has been on those candidate gating decision points where we are able to leverage antiracist, bias interruption research. As we engage in this process, we solicit feedback from the candidates about their experience and monitor the data at each stage (how many applications advance, are dropped or self-select out at each stage, etc.). Following each hiring cycle, we get together as a team to reflect on what we’ve learned and what experiments we might try in the next hiring cycle. 

So far, we have increased the number of applicants who were previously unknown to us (and vice versa). At each stage in the process, we have ended up with just about the expected number of candidates and overall candidate quality has been very high. The feedback we’ve received is that it is certainly an unusual process, but one that gives applicants (especially those unfamiliar with Palantir) a much better sense of us and our culture. 

Image "Scrabble - Resume" by Flazingo Photos licensed under CC BY-SA 2.0.

Jun 09 2021
Jun 09

expert metatag module install and config

https://www.drupal.org/project/metatag

Credits & Thanks

Thank you to:

About the Metatag module

The Metatag module allows you to set up Drupal to dynamically provide title tags and structured metadata, aka meta tags, on each page of your site.

what metatags look like in web code

Giving you control over your HTML title tag is the most important thing that the Metatag module does for SEO. That all-important tag is critical to your search engine ranking.

Note: It may be confusing that the Title Tag functionality resides within the Metatag module, but it makes sense from a technical standpoint. Both the HTML title tag and meta tags are placed in the header of a web page. By handling them both in the Metatag module, it requires less code and enables (slightly) faster rendering of your web pages.

Besides handling the title tag, the Metatag module programmatically creates meta tags for your website. Meta tags are snippets of text that tell a search engine about your pages. Meta tags help your SEO by communicating clearly to the search engine and social networks what each page on your website is about and how you want them to describe it in the search results. If you don’t do this, you will have to rely on the search engines to identify and classify your content. While they’re kind of good at this, it’s important enough that you don’t want to leave it to chance.

Global metatag suggestion screenshot

Because the Metatag module is so important, and there are many nuances to configuration, the documentation on this module is rather extensive. For this reason, we have created a free download that you can use to follow along to install, enable, and configure with the same base settings Volacci uses for all our clients.

Fill out the form below, and we'll send your copy right away!

Need help with your Drupal SEO?
Contact Volacci and we'll set up a no-obligation consultation.

Jun 09 2021
Jun 09

Do you ever stop to think about how many "things" make up the internet? 

Not necessarily websites and social media networks, but instead the individual pieces of information. Every button. Every callout. Every image. Every teeny-tiny item description in your shopping cart.

A long time ago, if you wanted to write about something on the internet, you had to create it and publish it. And if you wanted to write about it again somewhere else, you had to create it again and publish it again. 

But with "create once, publish everywhere" the manual weight of creating multiple things, publishing multiple places, and tweaking little bits of HTML across a landscape of pages is lifted. You get the most out of your content creation efforts.

What is create once, publish everywhere (COPE)?

Simply put, COPE is structured content. Rather than creating content multiple times across multiple pages, you instead create it and manage it in one place, whether you’re publishing it for the first time or the thousandth.

COPE was pioneered by National Public Radio (NPR) in a bold redesign to make it easier to share their multimedia content across devices, social media, email marketing, and more. For instances of this discussion, we’re focusing on publishing across your website.

Let’s start with a small example. Pretend you’re opening a new shoe store in your town. You really want people to visit, so you decide you’ll publish your business address and hours on every page of your website. 

But your website has 20 pages. And what if you change your business hours to be open later during the holiday season? That means you have to change that information 20 times. 

Twenty. 

But with COPE, you create a block or panel that holds your address and hours, and you tell your content management system (CMS) that you want that block to appear on every page of your website. Now when your business hours change, you only have to change that one block, and it updates across all the pages of your website with a single click.

And maybe today your website is 20 pages, but it’ll grow with more products, to 100 or 150 pages. That block means it will publish across every new page without having to be written from scratch or manually added, time and time again.

Where you’ve seen COPE

You may not realize it, but you’re running into this type of content across many websites you engage such as:

  • Entertainment websites: Upcoming episodes, shows, or movies that might interest you
  • Health care websites: Related doctors, clinic locations, or blog articles
  • News websites: Related headlines or news 
  • Recipe websites: Related recipes or blog posts
  • Retail websites: Recently viewed products or products that may interest you

COPE allows website administrators to set certain content types and attributes, or fields, which appear to your web visitors at different points in their journey. The same content or product can be seen in search listings, on cart pages, as a featured product on the front page, or in the "customers also bought" section. Different contexts, but the same content.

For example, if you’re looking online for a pair of red shoes, you may want to find something in your size (size 10) and the color you prefer (red). A website that offers these filters on its search page has categorized its content with taxonomy.

So, with these filters selected, you find a pair of retro-style Converse sneakers. You open the page to learn more about the shoes and find a description, price, and reviews. All of those things are part of the structure of that content. The website can display the same shoe on your “size 10, red” search, as well as someone’s “size 7, casual” search. 

That red pair of Converse lives on a product page that’s categorized and built in a way so that it only needs to exist once. Wouldn’t it be terrible if you had to publish and maintain an entirely new “Converse shoe” page for each size? 

COPE separates content and design

COPE doesn’t only mean you have far fewer things to keep track of when a piece of content needs to be updated or maintained, but it also separates content from design. 

Wait, what?

Yes. The process of structuring your content means you’re not reliant on how it looks on the website. It can, in fact, make internal content governance easier because you’re taking the subjective visual “feelings” away from the substance of the words. 

Let’s go back to the Converse shoes example. As a website administrator for the shoe store, you’re tasked to create a page for every shoe you offer. In setting up the page, you have to include: 

  • Shoe brand
  • Shoe name or model
  • Picture of the shoe
  • Bulleted description of the shoe’s features
  • Price of the shoe
  • Rating of the shoe, with reviews from customers

No matter if your shoe is a red Converse or a blue pair of high-heels, each product should be able to fill out all of these attributes. 

Now enter a stakeholder who says there needs to be a field for the shoe material because some of the nicest shoes are leather. But can a materials field be used across all the shoes you offer? It sure can!

And while historically, things like this always focused around “what it would look like” before “what it would say,” using structured content means the words hold just as much power as the design.

Structured content and a COPE model make it possible for you to grow and expand the content you offer across your site as the needs of your organization or audience change. A consistent experience makes it easy for people to find what they need quickly and the information to help them make their decision (or, in this case, purchase).

COPE makes cross-platform possible

You’ve built your website, and all your pages are tagged with taxonomy and are ready to share with the world. Time to launch.

Great! But your website being a destination for your brand means you want to build roads for people to reach you. Marketing has entered the chat.

With COPE, you don’t only structure content in a way that makes it easy to govern and manage that content in your CMS, but you also create a structured way to share that content across other channels.

Maybe your social posts use the product's short description and a thumbnail image of the shoes. Or maybe your email newsletters tease the top-rated shoes of the week, with a thumbnail and their star rating shown. 

COPE makes it easy to keep all of this information stored in one place. It also makes it easier to share your content across different channels in any way you need.

This marketing approach isn’t only less of a headache for your website administrators but also your whole organization. It makes your business and brand more agile, and in the long run, more efficient and successful.

Before you start COPE-ing

If you’re jazzed to get started, we’re jazzed for you, too. But before you go rushing off to your web team with this new idea in hand, let’s talk about what you should have in place before you get started. 

  1. Know what you have and what you need. A content inventory is a perfect way to start. You must understand your current digital structure and presence for both what you have and what you need. 
  2. Identify internal (and external) resources. COPE content becomes a piece of cake over time, but it might take a lot of decision-making and creation to give it legs upfront. Know if you have the team ready to take the project on or if you can outsource to an agency or partner with a vendor to get started.
  3. Get stakeholders on board early. You’ll need their input when the project kicks off and gets moving, so have conversations early and show how COPE can eliminate waste, drive sales, and encourage cost-efficiency. Stakeholders and internal experts can also help you start defining your ubiquitous language, which is integral to successful COPE.
  4. Set some high-level goals. Mostly, identify where your analytics are and where you want to go, but don’t make them your only focus. Set a SMART (specific, measurable, achievable, relevant, and timely) goal around your web traffic, conversions, and sales as a starting point.
  5. Document your plan forward. You’re not done with COPE when you hit ‘Publish’ on your website. The web is never done, and neither is your work. If you have a team, document how often you’ll meet to plan social posting, blogs, or other marketing efforts. Identify when and how content will be governed across the site, including how often and with what stakeholders or approvers. Answer these questions and write them down.

Most importantly, these discovery steps will (and should) lead your team or partner toward a domain model and, eventually, content models. Both of these help map the entire ecosystem of your website and plan for what type of pages, layouts, and templates are needed to present the information to the end-user. 

Get more content-first tips for preparing for COPE with the Content Marketing Institute.

Use COPE to master your destiny

It’s a long, winding road. Sometimes you’ll hit dead ends. Sometimes it’ll be a downhill breeze. But COPE is a worthwhile adventure for you and your team to explore as a way to more efficiently and effectively manage your website and user experience. 

If you’re ready to get started with a COPE model and need a digital partner who can lend a hand, reach out to our Lullabot team to get started.

Jun 09 2021
Jun 09

A small leak can sink a great ship. ~ Benjamin Franklin

We have seen the basic setup and configuration for Mautic plugins that leverage the integrations bundle, in the previous blog post. The key part of any IntegrationBundle is handling the authentication mechanism.  

So in this blog post, we will be covering various types of authentication and using one authentication type in the plugin that we built in the last blog post. We will continue developing the same plugin.

IntegrationBundle from Mautic Core supports multiple authentication provider methods- like API-based authentication, Basic Auth, OAuth1a, OAuth2, OAuth2 Two-Legged, OAuth2 Three-Legged, etc. The IntegrationBundle provides all these authentication protocols to be used as Guzzle HTTP Client.

In this blog post, we will implement Basic Auth authentication with a third-party service.

The following steps enable our plugin to have the Basic Auth authentication:

  • Have a form with fields for storing the basic auth credentials Form/Type/AuthType.php.
  • Prepare a “Credentials” class to be used by the Client class.
  • Prepare a “Client” service class to be used by a dedicated APIConsumer class.
  • Use Client service and implement API call-related methods in APIConsumer service class.

Step 1

The plugin depends on third-party APIs to have data to manipulate. And these APIs are gated with the authentication and authorization mechanisms. For the course of this post, we have chosen  Basic Auth as the authentication method. 

Basic Auth needed a username and password to communicate with the API. So we need a form that accepts the username and password as a key. And this key is required when connecting with API endpoints.

Let's create a form and name it  “ConfigAuthType.php” under the “MauticPlugin\HelloWorldBundle\Form\Type” namespace. This class extends the AbstractType class of Symfony. We need to implement the "buildForm()" method to add the required field.  Example code should look like this:

You can see the full version here.

It's now time to tell Mautic to pick up this form during configuration. To do so, we have to define an Integration service class implementing ConfigFormInterface, ConfigFormAuthInterface. The ConfigFormAuthInterface is the interface that lets you specify the configuration form using the getAuthConfigFormName method. 

So we name this class "ConfigSupport" and place this under the "MauticPlugin\HelloWorldBundle\Integration\Support." Here are the snippets from the class ConfigSupport:

You can find the complete ConfigSupport class here.

Time to let the IntegrationBunddle know about our "ConfigSupport" class. To do so, add a service as integration or create a service listing with the mautic.config_integration tag. The following is the code snippet of the Config.php (the plugin configuration file).

Now, at this point, we have the following things ready:

  • A service class to register the configuration support class.
  • A class to provide the configuration.
  • One can view all the code changes for step 1 here in this commit.

Step 2

For the Basic Auth, the Integrations bundle uses the “HttpFactory” class to build the http-client. Now, this class needs an object called “Credentials,” consisting of all the required keys for authentication.

If you notice the “getClient()” method of HttpFactory class under the “Mautic\IntegrationsBundle\Auth\Provider\BasicAuth\” namespace, it needs an object of “AuthCredentialsInterface.”

So our next step will be to create a separate class for credentials and create a new custom client to use those credentials.

For that, create a new class called “Credentials” under MauticPlugin\HelloWorldBundle\Connection

The class should be like given below:

This is a trimmed version of the class, and you can find the full version here.

Now that we have completed the Credentials class, we need to create a client who will make HTTP requests. Typically, we don’t need to create a separate client class if we don’t have additional logic to handle. In such cases, we can just call HttpFactory class and get the client like:

In our case, apart from fetching data, we need to cache it and polish it to be easily used for Mautic’s Lead entity.

So we will create a new class called “Client” under the namespace MauticPlugin\HelloWorldBundle\Connection.

The job of the “Client” class is to get the object of ClientInterface (\GuzzleHttp\ClientInterface).

If you need the full class details, you can just follow this link here. Because we are kind and we want to share more, we will quickly review a few methods that interest us and work with the Credentials class we wrote previously.

Here in the “getClient()” method, we are calling the “getCredentials()” method, which is creating a “Credentials” object using API keys.

By using the credentials object, we will get the client via the HttpFactory service call.

So at the end of this phase, we have the following things:

  • Credentials object to pass into getClient() method.
  • New Client class to manipulate get() method and fetch other configuration.
  • New Config.php file inside the “HelloWorldBundle/Integrations” folder to bring configuration and different integration settings.
  • Commit.

Step 3

We are now ready with the entire setup to store credentials and send the request. Now, it is time to use them in any other class or anywhere that we want to use.

In our current plugin, we have created a separate class called “ApiConsumer.” The reason is, we have several other get methods and API calls, so consolidating all the API methods into a single class is easier to manage.

To use our Client service, created via Client.php, we need to create a service that can use this class. That way, we can reuse this class without worrying about anything else.

Create a new service called “helloworld.connection.client” and add it to the Config.php in the other services section.

Similarly, we need to add additional services for the ApiConsumer class to call from other services.

You can refer to the source code to view the entire ApiConsumer class. Here is a snippet of the get() method.

As you can see, we are directly using the Client service’s reference and call the get method from the Client.php.

So at this point, we are done with the third step, where we used our authentication mechanism to fetch the data from the API.

You can refer to the commit to see the code for this step.

Conclusion

Now that we have the plugin ready to communicate with third-party API to churn out more leads, let us thank IntegrationBundle's authentication support. 

You can find about different authentication supports here.

Also, we have the third blog post coming up about how to manage and sync data coming from API. So stay tuned!!

Jun 09 2021
Jun 09

Defining your own Drupal block plugins in custom code is really powerful, but sometimes you can feel limited by what those blocks have access to. Your block class is like a blank canvas that you know you'll be pulling data into, but how should you get that data from the surrounding page? Often you have to resort to fetching the entity for the current page out of its route parameters (e.g. on a node page), in order to get the values out of its fields that you want to display. Plugins can actually have a context passed to them directly - which can be common things like the logged-in user, or the node for the page being viewed. Let's have a look at how to tell Drupal what your plugin needs, so you don't have to do the donkey work.

If you've created a block plugin, you'll already be aware of the annotation comment just above the class name at the top of your PHP file. It might look something like this:

Spot that last property in the annotation: the context_definitions part. That's where the block is defined as requiring a node context. The 'entity:node' part tells Drupal that the context should be a node; Drupal supports it just being 'entity' or various other things, such as 'language' or even 'string'. You can very easily get hold of the context for your block, e.g. in the build() method of your class, allowing your block to adapt to its surroundings:

/**
 * {@inheritdoc}
 */
public function build() {
  $entity = $this->getContextValue('node');

  return $entity->field_my_thing->view();
}

I've used a very simple tip from our article on rendering fields for the output of this method. But the key here is the use of $this->getContextValue('node');. Our block class is extending the BlockBase base class, which gives us that getContextValue() method to use (via ContextAwarePluginTrait, which you could use directly in your plugin class if you're not extending BlockBase). The 'node' parameter that we've passed to it should match the key of the context definition array up in the class annotation - it's just a key that you could rename to anything helpful. Plugins can specify multiple contexts, so distinguish each with appropriate names.

Using contextual values like this also sorts caching out for you. Drupal understands that caching for your block will need to be segmented according to this contextual value, and refreshed if the supplied node (or whatever the context type is) is updated, etc. This is so much better than having to manually fiddle with #cache properties!

In this basic case of using a node, the chances are that you're just wanting to use the node that the current page is for. Drupal core has 'context provider' services - one of which provides exactly that. Most basic Drupal installations probably won't have other context providers that provide nodes, so the node just gets automatically passed through, without you having to do anything else to wire it up. Brilliantly, the block will only show up when on a node page, regardless of any other visibility settings in the block placement configuration. You can bypass that by flagging that the context is optional in its definition - spot the 'required' key:

context_definitions = {
  "node" = @ContextDefinition("entity:node", required = FALSE, label = @Translation("Node")),
}

A slightly more interesting example is for users, as Drupal core can potentially provide two possible contexts for them:

  1. The currently logged-in user, or at least the entity object representing the anonymous user if no-one is logged in.
  2. The user being viewed - which will only be available when visiting an actual user profile page.

When there are more than one possible contexts available, block placement configuration forms offer the choice of which to use. So you might want a block in a sidebar on profile pages to show things to do with the user who owns that profile - in which case, select the 'User being viewed' option in the dropdown. Otherwise the data your block shows will just be about you, the logged-in user, even when looking at someone else's profile. Internally, your selection in the dropdown gets stored as the context mapping, which you can see in the exported configuration files for any context-aware block (including those automatically selected due to only one context being available).

If all this talk of Contexts is reminding you of something, it's because the concept was brought into core after being used with Panels in older versions of Drupal. Core's Layout Builder now uses it heavily, usually to pass the entity being viewed into the blocks that represent fields etc that you place in each section. For anyone that really wants to know, those blocks are defined using a plugin deriver - i.e. a separate class that defines multiple possible block plugins, dynamically. In the case of Layout Builder, that means a block is dynamically created for every field an entity can have. If you use plugin derivers, you might need dynamically set up context definitions too. So in the deriver's getDerivativeDefinitions() method, you could have something like this, the PHP equivalent of the regular block's static annotation:

/**
 * {@inheritdoc}
 */
public function getDerivativeDefinitions($base_plugin_definition) {
  $derivative['context_definitions'] = [
    'node' => new \Drupal\Core\Plugin\Context\ContextDefinition('entity:node', $this->t('Node')),
  ];

  $this->derivatives['your_id'] = $derivative;
  return $this->derivatives;
}

I've only lightly touched on context provider services, but you can of course create your own too. I recently used one to provide a related 'section' taxonomy term to blocks, which pulls from an entity reference field that nearly all entity types & bundles on a site had. The blocks display fields from the current page's parent section. It made for a common interface separating that 'fetching' code from the actual block 'display' code. I recommend understanding, copying & adapting the NodeRouteContext class (and accompanying service definition in node.services.yml) for your case if you have a similar need.

I hope this awareness of context allows your blocks to seamlessly adapt to their surroundings like good chameleons, and maybe even write better code along the way. I know I've had many blocks in the past that each had their own ways of pulling relevant data for a page. Contexts seem like the answer to me as they separate fetching and display data, so each part can be done well. Getting creative with making my own context types and context providers was fun too, though probably added unnecessary complication in the end. Let me know in the comments what context-aware plugins enable you to do!

Photo by Andrew Liu on Unsplash

Jun 08 2021
Jun 08

“Good marketing makes the company look smart; great marketing makes the customers feel smart.” – Joe Chernov, VP Marketing, Pendo

In today’s fast-paced digital world, marketing needs more than just a physical team to manage workflows. The traditional marketing practices involve many repetitive tasks that consume a lot of time and may hinder productivity.

This is where marketing automation integration comes into play. The integration of marketing automation tools simplifies marketing practices and eliminates repetitive tasks. Thus, helping save time, expedite processes, and boost ROI for business growth.

The Need to Integrate Your Marketing Automation Platform With Your Website

Marketing automation platforms (MAPs) help streamline and automate marketing activities to increase operational efficiency. They enable organizations to market on multiple channels by automatically triggering actions based on customer behavior.

Integrating a marketing automation platform with the website gives organizations easy visibility of customer behavior along with the centralization of data for improved workflows. It also facilitates various marketing activities, including lead generation, tracking visitors, lead nurturing, real-time sales notification, lead scoring, retention, and cross-sell and upsell to name a few.

Benefits of Integrating Your Marketing Automation Platform With Your Website

Integrating your marketing automation platform with your website comes with a myriad of benefits that enable you to connect with customers quickly and potentially increase sales. With this integration, businesses can:

marketing automation integration in drupal
  • Cut Costs and Increase ROI
  • Marketing automation tools allow businesses to set up campaigns on auto-pilot which reduces staffing needs and costs. As per reports, this also increases conversions to as high as 53% and gives companies ROI within 12 months.

  • Conduct Frequent Tests
  • Marketing automation facilitates frequent testing of marketing messages, including landing pages, emails, and online forms for adjusting and altering subject lines, CTAs, and tone of voice to better engage audiences.

  • Enhance Sales Cycle
  • Lead scoring and nurturing tools help acquire prime marketing qualified leads which are then converted to sales qualified leads with the help of human interactions.

  • Refine Processes
  • Marketing automation ensures that any obstacle along the customer journey is identified timely. And if the team is unable to convert the lead, instant feedback is provided to improve performance.

Drupal + Marketing Automation

Drupal is not only known for its scalability but also huge flexibility and an active community that contributes various marketing automation modules and plug-ins within the Drupal CMS. Other than these free and out-of-the-box tools, Drupal can seamlessly integrate with a number of third-party marketing automation software, making it a powerhouse for marketers.

Marketing Automation Integration Modules Available in Drupal

Drupal is equipped to help you leverage automated marketing strategies down to their core. Here are some of the marketing automation modules that Drupal is integrated with the most:

  • HubSpot
  • HubSpot offers a variety of inbound automation tools, including the marketing hub, sales hub, and service hub. The HubSpot Drupal module integrates its JavaScript tracking code to cover all the basic tracking needs.

  • MailChimp
  • The Drupal MailChimp module integrates MailChimp with Drupal to track and create a list of website visitors which is then sent to MailChimp for email automation. It also lets marketers create campaigns, sign-up forms, and track activity from the Drupal website.

  • Eloqua
  • Eloqua facilitates marketing campaign management, lead management and engagement, and email automation. The Eloqua Drupal module is further divided into module fragments like Webform Eloqua and Eloqua API Redux that help extend the automation engine’s functionality.

  • Pardot
  • Pardot is a marketing automation platform owned by Salesforce that helps in customer behavior tracking, lead generation and nurturing, SEO, website tracking, and more. The Drupal Pardot module integrates web analytics with Drupal that helps create, manage, and deploy online marketing campaigns.

  • Marketo
  • Marketo automates activities like lead tracking and nurturing, analytics, social marketing, personalization, and more across various devices. The Drupal Marketo MA module adds a munchkin tracking code to your Drupal website to capture lead data during submissions and updates.

Our Drupal Marketo Integration Connector automates the targeting of known Marketo leads and offers them personalized content for improved engagement, conversion, and subscription rates.

Conclusion

Integrating your marketing automation platform with Drupal is a sure-shot way of converting leads into happy customers. It empowers businesses to deliver excellent experiences, optimize productivity, and accelerate revenue growth.

Ready to Integrate Your Marketing Automation Platform With Drupal? Talk to us.

Our team of experts can help you with any Drupal marketing automation integration that you may need. To know more, simply write to us at [email protected] and we’ll take it from there.

Jun 08 2021
Jun 08

Website’s security is never (and should never be) an afterthought. A breached website does not just cause a loss in revenue but also in reputation. A secure website is one that has been developed keeping in mind different ways it could be broken into.

For this, we must ensure that the security checklist is handled before the launch and also after the launch of the site. One of the most important steps to ensure a secure Drupal website is to make certain that users have and maintain strong password policies. Out of the box, Drupal does not enforce a strong password policy. By default, you can choose to set easy (and weak passwords). But this behavior is not recommended especially for users who have content administration and other higher privilege permissions.

And that’s where the Drupal Password Policy module shines. It enables site admins to set strong password policies and enforce restrictions to a website. The Password policy module is a contributed Drupal module that is compatible with Drupal 9 as well.

Password Policy Module

Installing the Password Policy Module

Step 1: Install the Password Policy module using composer or download from here.

$ composer require 'drupal/password_policy:^[email protected]'

Note: Before installing the password policy module, make sure you have installed and enabled the Ctools module.

Step 2: Enable the downloaded module using drush or Drupal UI.

Through the Drupal UI, head to the module listing page. Under the Security tab, you will find the password policy module with submodules. Enable the first Password Policy module and then the submodules as per your requirement.

Security

Configuration

To configure your recently installed and enabled Password policy module, go to Configuration → Security → Password Policy. Here you will add password policies for various roles with different constraints as per your requirement.

Password Reset

Now give a Policy name and set password reset days. If you don't want to the password to expire, set the Password reset days as 0 days.

General Info

After this, you can add constraints and configure it through the Constraints settings tab. Note that the submodule that you added in security modules listing will list in the Constraints dropdown.

Configure Constraints

Let’s implement this with an example for better understanding. I need to add a password policy for an author role that enforces that the password must contain a minimum of 3 characters from the subsequent character types: lowercase letters, uppercase letters, digits, special characters, a minimum of 1 special character and the password length must be a minimum of 8 characters.

Character TypeNumber of CharacterMaximum LengthPolicy Constraints

Once you have configured the above constraints, apply it to the author role.

Apply to Roles

Click on the Finish button to create your new password policy. You have now successfully created a password policy for the author role.

Jun 08 2021
Jun 08

There's a neat little Drupal module called JSON Field and recently, I had a chance to play around with it. Out of the box, JSON field is a just a plain field where JSON data can be input and output on a web page. On its own, the module does not do much beyond just printing the raw data formatted as JSON. However, I got to thinking it would be ideal to nicely format the data with HTML. In this article, I will show you how I accomplished this with both a preprocess function and some custom code in Twig.

Getting started

First, you'll want a Drupal 8 or 9 instance running. In the root of your project, run:

composer require drupal/json_field

Note, if you get an error, you may need to append a version number, for example:

composer require drupal/json_field:1.0-rc4

Next, enable the module and create a new field on an entity, for example on a page content type. When I created my field, I chose the option, JSON stored as raw JSON in database

Next, input some JSON data, for sample data, I like to use Mockaroo. (At a high level, I could envision using the Drupal Feeds module to import JSON data in bulk and mapping it to a JSON field but I have not tested this.)

An example of the Mockaroo interface showing mock data being generated An example of the Mockaroo interface showing mock data being generated

Create a preprocess function

We are rendering this data in a node so I have a basic node preprocess function setup below with a sub-theme of Olivero called Oliver. Within this, we will leverage Xdebug to examine the data up close. We write this code in our theme's .theme file.

Define and check for an instance of a node

The first thing we want to do is, since we are working within a node context, we will set some node definitions and check to ensure that we are on a node page.

At the top of our file, we will add

use Drupal\node\NodeInterface;

Then, within the function, we will define the node.

  // Define the node.
  $node = \Drupal::routeMatch()->getParameter('node');

Now we check for an instance of a node:

  // If instance of a node.
  if ($node instanceof NodeInterface) {

Field PHP magic

I named my JSON field field_json_raw and we first want to check to see if the field exists and that it is not empty. For this, I like to use a PHP magic method. A magic method is a short cut of sorts to dig into the field data. In Drupal terms, this looks like:

 if ($node->hasField('field_json_raw') &&
   !$node->get('field_json_raw')->isEmpty()) {
	// Custom code here...
  }

The magic methods above are hasField and get.

Start up Xdebug

Next up, we will use Xdebug to examine the data output to see how we might prepare variables for our Twig template. Within the node preprocess function, I set an Xdebug breakpoint and start listening. Once Xdebug is running we can evaluate the field expression using the magic method again but this time adding the value on. For example, $node->get('field_json_raw')->value. That ends up with the plain value of the field:

[{"id": 1, "country": "Cuba", "animal_name": "Cape Barren goose", "description": "Curabitur convallis.", "animal_scientific": "Cereopsis novaehollandiae"}, {"id": 2, "country": "Vietnam", "animal_name": "Horned puffin", "description": "Pellentesque ultrices mattis odio." Etc...
Xdebug showing the plain value of the JSON output Xdebug showing the plain value of the JSON output

Convert the value into an array

What we need to do now is convert that to a usable PHP array. We use the json_decode function:

 // Set a variable for the plain field value.
 $json_raw = $node->get('field_json_raw')->value;
 // Convert the data into an array using json decode.
 $json_array = json_decode($json_raw);

That ends up looking like this:

Xdebug showing the converted JSON array Xdebug showing the converted JSON array

Create a template variable

Now we have a nicely formatted array to loop through once inside a twig template. The final piece is to check for valid JSON and set the template variable. Note, JSON field already check for valid json but it's probably good practice to do this anyway.

 // Check for valid JSON.
 if ($json_array !== NULL) {
  // Create a variable for our template.
  $vars['json_data'] = $json_array;
 }

Finished preprocess function

Putting it all together, our entire preprocess function looks like this:

getParameter('node');
  // If instance of a node.
  if ($node instanceof NodeInterface) {
    // Check for the field and that it is not empty.
    if ($node->hasField('field_json_raw') &&
      !$node->get('field_json_raw')->isEmpty()) {
      // Set a variable for the field value.
      $json_raw = $node->get('field_json_raw')->value;
      // Convert the data into an array.
      $json_array = json_decode($json_raw);
      // Check for valid JSON.
      if ($json_array !== NULL) {
        // Create a variable for our template.
        $vars['json_data'] = $json_array;
      }
    }
  }
}

Render the JSON variable in Twig

Now we'll go into our Twig template and render the variable with a loop. At its very most basic, it will look something like this:


    {% if content.field_json_raw | render %}
      {% for item in json_data %}
      {{ item.animal_name }}
      {{ item.animal_scientific }}
      {{ item.country }}
      {% endfor %}
    {% endif %}

Of course we want to add HTML to this to make it look nicely styled and here is where you can do most anything you want. I opted for a data table:


    {% if content.field_json_raw | render %}
      

{{ 'Animals from around the world'|t }}

{% for item in json_data %} {% endfor %} {{ 'Animal Name'|t }} {{ 'Scientific Name'|t }} {{ 'Country'|t }} {{ item.animal_name }} {{ item.animal_scientific }} {{ item.country }}
{% endif %}

The code above ends up looking like this:

The finished styled output of the JSON data Twig loop The finished styled output of the JSON data Twig loop

Summary

And there you have it, nicely styled JSON data rendered in a Twig template. Using the JSON Field module might not be a common everyday item but it definitely fulfills a specific use case as outlined here.

Resources

Tags

Jun 07 2021
Jun 07

Last month we implemented the 'Resources' page on iias.asia, as you can see: you can filter the Resource nodes on this page in the right of the screen. This is a Drupal View with exposed filters, which are placed via a block via Twig Tweak module.

There is a 'Region' Filter and a 'Tags' taxonomy reference field, which are also used in other content types. 

We only wanted to show used terms in the drop downs.

So, there are other pages (Views) that also implemented this tag as a filter (like the Alumni page). But of course: those pages have other content types, so 'used tags' are also different.

So here is how we limited the used tags, per Drupal View, this article gave us a kickstart.

YOURMODULE.module:
/**
 * Implements hook_form_alter()
 *
 */
function YOURMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // Id's of the forms we want to alter.
  $form_ids = [
    'views-exposed-form-resources-page-1' => 'resource',
    'views-exposed-form-reviews-page-1' => 'review',
    'views-exposed-form-available-for-review-page-1' => 'review',

  ];
  // Targeted taxonomy term fields.
  $select_fields = ['tid_2', 'field_tags_target_id'];
  // Continue only if current form_id is one in defined array.
  if (array_key_exists($form['#id'], $form_ids)) {
    // Loop through targeted fields.
    foreach ($select_fields as $select_field) {
      // Get 'terms in use', switch query on which field is currently in the loop.
      // This only works if you have 1 or 2 targeted filters.
      $available_terms = ($select_field == 'tid_2')
                        ? _get_available_terms_region($form_ids[$form['#id']], $form['#id'])
                        : _get_available_terms_tags($form_ids[$form['#id']], $form['#id']);
      // Continue if $available_terms exists.
      if (isset($available_terms)) {
        // Unset the existing list.
        unset($form[$select_field]['#options']);
        // Build new list with 'terms in use'.
        $form[$select_field]['#options']['All'] = '- Any -';
        foreach ($available_terms as $available_term) {
          $tid = $available_term[0];
          $name = $available_term[1];
          $form[$select_field]['#options'][$tid] = $name;
        }
      }
    }
  }
}
/**
 * Custom function to query and build new filter list.
 *
 * @param $node_type
 * @param $exposed_block_id
 * @return array
 */
function _get_available_terms_region($node_type, $exposed_block_id) {
  // Table name of tags field.
  $node_tags_table = 'node__field_profile_region';
  // Query data.
  $query = \Drupal::database()->select($node_tags_table, 'nft');
  $query->distinct();
  $query->join('taxonomy_term_field_data', 'tname', 'tname.tid = nft.field_profile_region_target_id');
  $query->join('node', 'node', 'node.nid = nft.entity_id');
  $query->fields('nft', ['field_profile_region_target_id']);
  $query->fields('tname', ['name']);
  $query->orderBy('tname.name');
  // Dynamically query node type.
  $query->condition('node.type', $node_type);
  if($exposed_block_id == 'views-exposed-form-available-for-review-page-1') {
    $query->join('node__field_boolean_1', 'available', 'available.entity_id = nft.entity_id');
    $query->condition('available.field_boolean_1_value', 1);
  }
  $result = $query->execute();
  // Build term list.
  $term_list = [];
  while ($row = $result->fetchAssoc()) {
    array_push($term_list, [$row['field_profile_region_target_id'], $row['name']]);
  }
  // Return term list.
  return $term_list;
}

/**
 * Custom function to query and build new filter list.
 *
 * @param $node_type
 * @param $exposed_block_id
 * @return array
 */
function _get_available_terms_tags($node_type, $exposed_block_id) {
  // Table name of tags field
  $node_tags_table = 'node__field_tags';
  // Query data.
  $query = \Drupal::database()->select($node_tags_table, 'nft');
  $query->distinct();
  $query->join('taxonomy_term_field_data', 'tname', 'tname.tid = nft.field_tags_target_id');
  $query->join('node', 'node', 'node.nid = nft.entity_id');
  $query->fields('nft', ['field_tags_target_id']);
  $query->fields('tname', ['name']);
  $query->orderBy('tname.name');
  // Dynamically query node type.
  $query->condition('node.type', $node_type);
  if($exposed_block_id == 'views-exposed-form-available-for-review-page-1') {
    $query->join('node__field_boolean_1', 'available', 'available.entity_id = nft.entity_id');
    $query->condition('available.field_boolean_1_value', 1);
  }
  $result = $query->execute();
  // Build term list.
  $term_list = [];
  while ($row = $result->fetchAssoc()) {
    array_push($term_list, [$row['field_tags_target_id'], $row['name']]);
  }
  // Return list.
  return $term_list;
}

Custom functions in the block above, we put these in the same .module file, but maybe it's better to place it in a Drupal service for example. Of course you can always refactor this into one function -more dynamic. But I'll leave that up to you :)

I hope this gives you a head start, please let me know if you have any questions or improvements.

Drupal code Planet Drupal Written by Joris Snoek | Jun 07, 2021

Join the conversation

Jun 07 2021
Jun 07

The overall challenge to wrangling the Webform module's issue queue is that everyone has different levels of experience in Drupal. Organizations are trying to build unique and complex digital experiences. If you combine this with the fact that we are an international community, the result is that issue queue tickets come in all shapes and sizes. Therefore, with each issue, I have to figure out the problem, priority, solution, and level of effort required to resolve the issue.

Jun 06 2021
Jun 06
Drupal 8 will be released on November 19 | Wunderkraut

Coincidence?

We're ready to celebrate and build (even more) amazing Drupal 8 websites. 
On November 19 we'll put our Drupal 8 websites in the spotlight...be sure to come back and check out our website.

By

Michèle Weisz

Share

Want to know more?

Contact us today

or call us +32 (0)3 298 69 98

© 2015 Wunderkraut Benelux

Jun 06 2021
Jun 06
77 of us are going | Wunderkraut

Drupalcon 2015

People from across the globe who use, develop, design and support the Drupal platform will be brought together during a full week dedicated to networking, Drupal 8 and sharing and growing Drupal skills.

As we have active hiring plans we’ve decided that this year’s approach should have a focus on meeting people who might want to work for Wunderkraut and getting Drupal 8 out into the world.
As Signature Supporting Partner we wanted as much people as possible to attend the event. We managed to get 77 Wunderkrauts on the plane to Barcelona!  From Belgium alone we have an attendance of 17 people.
The majority of our developers will be participating in sprints (a get-together for focused development work on a Drupal project) giving all they got together with all other contributors at DrupalCon.

We look forward to an active DrupalCon week.  
If you're at DrupalCon and feel like talking to us. Just look for the folks with Wunderkraut carrot t-shirts or give Jo a call at his cell phone +32 476 945 176.

Share

Related Blog Posts

Want to know more?

Contact us today

or call us +32 (0)3 298 69 98

© 2015 Wunderkraut Benelux

Jun 06 2021
Jun 06
Watch our epic Drupal 8 promo video | Wunderkraut

How Wunderkraut feels about Drupal 8

Drupal 8 is coming and everyone is sprinting hard to get it over the finish line. To boost contributor morale we’ve made a motivational Drupal 8 video that will get them into the zone and tackling those last critical issues in no time.

[embedded content]

Share

Related Blog Posts

Want to know more?

Contact us today

or call us +32 (0)3 298 69 98

© 2015 Wunderkraut Benelux

Jun 06 2021
Jun 06

Once again Heritage day was a huge succes.

About 400 000 visitors visited Flanders monuments and heritage sites last Sunday.  The Open Monumentendag website received more than double the amount of last year's visitors.

Visitors to the website organised their day out by using the powerful search tool we built that allowed them to search for activities and sights at their desired location.  Not only could they search by location (province, zip code, city name, km range) but also by activity type, keywords, category and accessibility.  Each search request being added as a (removable) filter for finding the perfect activity.

By clicking on the heart icon, next to each activity, a favorite list was drawn up.  Ready for printing and taking along as route map.

Our support team monitored the website making sure visitors had a great digital experience for a good start to the day's activities.

Did you experience the ease of use of the Open Monumentendag website?  Are you curious about the know-how we applied for this project?  Read our Open Monumentendag case.

Jun 06 2021
Jun 06
Very proud to be a part of it | Wunderkraut

Breaking ground as Drupal's first Signature Supporting Partner

Drupal Association Executive Director Holly Ross is thrilled that Wunderkraut is joining as first and says: "Their support for the Association and the project is, and has always been, top-notch. This is another great expression of how much Wunderkraut believes in the incredible work our community does."

As Drupal Signature Supporting Partner we commit ourselves to advancing the Drupal project and empowering the Drupal community.  We're very proud to be a part of it as we enjoy contributing to the Drupal ecosystem (especially when we can be quircky and fun as CEO Vesa Palmu states).

Our contribution allowed the Drupal Association to:

  • Complete Drupal.org's D7 upgrade - now they can enhance new features
  • Hired a full engineering team committed to improving Drupal.org infrastructure
  • Set the roadmap for Drupal.org success.

First signaturepartner announcement in Drupal Newsletter

By

Michèle Weisz

Share

Related Blog Posts

Want to know more?

Contact us today

or call us +32 (0)3 298 69 98

© 2015 Wunderkraut Benelux

Jun 06 2021
Jun 06

But in this post I'd like to talk about one of the disadvantages that here at Wunderkraut we pay close attention to.

A consequence of the ability to build features in more than one way is that it's difficult to predict how different people interact (or want to interact) with them. As a result, companies end up delivering solutions to their clients that although seem perfect, turn out, in time, to be less than ideal and sometimes outright counterproductive. 

Great communication with the client and interest in their problems goes a long way towards minimising this effect. But sometimes clients realise that certain implementations are not perfect and could be made better. And when that happens, we are there to listen, adapt and reshape future solutions by taking into account these experiences. 

One such recent example involved the use of a certain WYSIWYG library from our toolkit on a client website. Content editors were initially happy with the implementation before they actually started using it to the full extent. Problems began to emerge, leading to editors spending way more time than they should have performing editing tasks. The client signalled this problem to us which we then proceed to correct by replacing said library. This resulted in our client becoming happier with the solution, much more productive and less frustrated with their experience on their site. 

We learned an important lesson in this process and we started using that new library on other sites as well. Polling our other clients on the performance of the new library revealed that indeed it was a good change to make. 

Jun 06 2021
Jun 06

A few years ago most of the requests started with : "Dear Wunderkraut, we want to build a new website and ... "  - nowadays we are addressed as "Dear Wunderkraut, we have x websites in Drupal and are very happy with that, but we are now looking for a reliable partner to support & host ... ".

By the year 2011 Drupal had been around for just about 10 years. It was growing and changing at a fast pace. More and more websites were being built with it. Increasing numbers of people were requesting help and support with their website. And though there were a number of companies flourishing in Drupal business, few considered specific Drupal support an interesting market segment. Throughout 2011 Wunderkraut Benelux (formerly known as Krimson) was tinkering with the idea of offering support, but it was only when Drupal newbie Jurgen Verhasselt arrived at the company in 2012 that the idea really took shape.

Before his arrival, six different people, all with different profiles, were handling customer support in a weekly rotation system. This worked poorly. A developer trying to get his own job done plus deal with a customer issue at the same time was getting neither job done properly. Tickets got lost or forgotten, customers felt frustrated and problems were not always fixed. We knew we could do better. The job required uninterrupted dedication and constant follow-up.

That’s where Jurgen came in the picture. After years of day job experience in the graphic sector and nights spent on Drupal he came to work at Wunderkraut and seized the opportunity to dedicate himself entirely to Drupal support. Within a couple of weeks his coworkers had handed over all their cases. They were relieved, he was excited! And most importantly, our customers were being assisted on a constant and reliable basis.

By the end of 2012 the first important change was brought about, i.e. to have Jurgen work closely with colleague Stijn Vanden Brande, our Sys Admin. This team of two ensured that many of the problems that arose could be solved extremely efficiently. Wunderkraut being the hosting party as well as the Drupal party means that no needless discussions with the hosting took place and moreover, the hosting environment was well-known. This meant we could find solutions with little loss of time, as we know that time is an important factor when a customer is under pressure to deliver.

In the course of 2013 our support system went from a well-meaning but improvised attempt to help customers in need to a fully qualified division within our company. What changed? We decided to classify customer support issues into: questions, incidents/problems and change requests and incorporated ITIL based best practices. In this way we created a dedicated Service Desk which acts as a Single Point of Contact after Warranty. This enabled us to offer clearly differing support models based on the diverse needs of our customers (more details about this here). In addition, we adopted customer support software and industry standard monitoring tools. We’ve been improving ever since, thanks to the large amount of input we receive from our trusted customers. Since 2013, Danny and Tim have joined our superb support squad and we’re looking to grow more in the months to come.

When customers call us for support we do quite a bit more than just fix the problem at hand. Foremostly, we listen carefully and double check everything to ensure that we understand him or her correctly. This helps to take the edge off the huge pressure our customer may be experiencing. After which, we have a list of do’s and don’t for valuable support.

  • Do a quick scan of possible causes by getting a clear understanding of the symptoms
  • Do look for the cause of course, but also assess possible quick-fixes and workarounds to give yourself time to solve the underlying issue
  • Do check if it’s a pebkac
  • and finally, do test everything within the realm of reason.

The most basic don’t that we swear by is:

  • never, ever apply changes to the foundation of a project.
  • Support never covers a problem that takes more than two days to fix. At that point we escalate to development.

We are so dedicated to offering superior support to customers that on explicit request, we cater to our customers’ customers. Needless to say, our commitment in support has yielded remarkable  results and plenty of customer satisfaction (which makes us happy, too)

Jun 06 2021
Jun 06

If your website is running Drupal 6, chances are it’s between 3 and 6 years old now, and once Drupal 8 comes out. Support for Drupal 6 will drop. Luckily the support window has recently been prolonged for another 3 months after Drupal 8 comes out. But still,  that leaves you only a small window of time to migrate to the latest and greatest. But why would you? 

There are many great things about Drupal 8 that will have something for everyone to love, but that should not be the only reason why you would need an upgrade. It is not the tool itself that will magically improve the traffic to your site, neither convert its users to start buying more stuff, it’s how you use the tool.  

So if your site is running Drupal 6 and hasn’t had large improvements in the last years it might be time to investigate if it needs a major overhaul to be up to par with the competition. If that’s the case, think about brand, concept, design, UX and all of that first to understand how your site should work and what it should look like, only then we can understand if a choice needs to be made to go for Drupal 7 or Drupal 8.  

If your site is still running well you might not even need to upgrade! Although community support for Drupal 6 will end a few months after Drupal 8 release, we will continue to support Drupal 6 sites and work with you to fix any security issues we encounter and collaborate with the Drupal Security Team to provide patches.

My rule of thumb is that if your site uses only core Drupal and a small set of contributed modules, it’s ok to build a new website on Drupal 8 once it comes out. But if you have a complex website running on many contributed and custom modules it might be better to wait a few months maybe a year until all becomes stable. 

Jun 06 2021
Jun 06

So how does customer journey mapping work?

In this somewhat simplified example, we map the customer journey of somebody signing up for an online course. If you want to follow along with your own use case, pick an important target audience and a customer journey that you know is problematic for the customer.

1. Plot the customer steps in the journey

customer journey map 1

Write down the series of steps a client takes to complete this journey. For example “requests brochure”, “receives brochure”, “visits the website for more information”, etc. Put each step on a coloured sticky note.

2. Define the interactions with your organisation

customer journey map 2

Next, for each step, determine which people and groups the customer interacts with, like the marketing department, copywriter and designer, customer service agent, etc. Do the same for all objects and systems that the client encounters, like the brochure, website and email messages. You’ve now mapped out all people, groups, systems and objects that the customer interacts with during this particular journey.

3. Draw the line

customer journey map 3

Draw a line under the sticky notes. Everything above the line is “on stage”, visible to your customers.

4. Map what happens behind the curtains

customer journey map 4

Now we’ll plot the backstage parts. Use sticky notes of a different color and collect the persons, groups, actions, objects and systems that support the on stage part of the journey. In this example these would be the marketing team that produces the prod brochure, the printer, the mail delivery partner, web site content team, IT departments, etc. This backstage part is usually more complex than the on stage part.

5. How do people feel about this?

Customer journey map 5

Now we get to the crucial part. Mark the parts that work well from the perspective of the person interacting with it with green dots. Mark the parts where people start to feel unhappy with yellow dots. Mark the parts where people get really frustrated with red. What you’ll probably see now is that your client starts to feel unhappy much sooner than employees or partners. It could well be that on the inside people are perfectly happy with how things work while the customer gets frustrated.

What does this give you?

Through this process you can immediately start discovering and solving customer experience issues because you now have:

  • A user centred perspective on your entire service/product offering
  • A good view on opportunities for innovation and improvement
  • Clarity about which parts of the organisation can be made responsible to produce those improvements
  • In a shareable format that is easy to understand

Mapping your customer journey is an important first step towards customer centred thinking and acting. The challenge is learning to see things from your customers perspective and that's exactly what a customer journey map enables you to do. Based on the opportunities you identified from the customer journey map, you’ll want to start integrating the multitude of digital channels, tools and technology already in use into a cohesive platform. In short: A platform for digital experience management! That's our topic for our next post.

Jun 04 2021
Jun 04

Creating a dynamic PDF file is one of the most important points of a project. The crucial thing is to find the right solution that meets your expectations and requirements. In this article, we’ll show you one of the most popular PDF generation modules for Drupal that will be helpful for you to generate, view or download reports, articles, and invoices in PDF.

Dates

The first version of the module was released on 22 January 2015, the latest update - 18 June 2020.

The module can be installed on:

  • Drupal 7 (7.x-1.5 stable release version),
  • Drupal 8 and 9 (8.x-2.2 stable release version).

All stable releases for this project are covered by the security advisory policy.

Module’s popularity

According to the usage statistics from the module's page, it’s currently used by around 12 thousand websites.

Module’s creators

The module is created and maintained by benjy.

What is the module used for?

Entity Print allows you to print (save) any Drupal entity (Drupal 7 and 8) or View (Drupal 8+ only) to a PDF file. It uses the PDF engines based on popular PHP libraries like Dompdf, Phpwkhtmltopdf and TCPDF.

Unboxing

  1. To install Entity Print, go to its webpage or do it via composer: 
    composer require "drupal/entity_print 2.x"
  2. Install Dompdf by running composer require
    composer require "dompdf/dompdf:0.8.0" 
  3. Additionally you can install Wkhtmltopdf and TCPDF engines.
    composer require "mikehaertl/phpwkhtmltopdf ~2.1" 
    composer require "tecnickcom/tcpdf ~6" 
  4. Enable the Entity Print module.
  5. Grant permissions for non-admin users to download the PDFs.
  6. Optionally, enable the Entity Print Views module.
The installation settings of the Entity Print Drupal module

 

Configure Entity Print

Let’s check what this module allows us to configure.

  • Enable Default CSS - provide some very basic styles.
  • Force Download - force the browser to download the PDF file.
  • PDF - select the default PDF engine for printing.
  • Paper Size - change page size to print the PDF to.
  • Paper Orientation - change orientation to Landscape or Portrait.
  • Enable HTML5 Parser - Dompdf doesn't work without this option enabled.
  • Disable Log - disable Dompdf logging to log.html in Drupal's temporary directory.
  • Enable Remote URLs - must be enabled for CSS and Images to work unless you manipulate the source manually.
  • SSL CONFIGURATION - may be needed for development only, in production you shouldn’t change it.
  • HTTP AUTHENTICATION - if your website is behind HTTP Authentication, you can set the username/password.
  • EPub - select the default EPub engine for printing (currently not supported, you can follow the opened issue).
  • Word Document - select the default Word Document engine for printing (currently not supported, follow the opened issue).
The Entity Print module's configuration

 

The preferable PDF engine is Dompdf, which is (mostly) a CSS 2.1 compliant HTML layout and rendering engine written in PHP. It’s a style-driven renderer so it’ll download and read external stylesheets, inline style tags, and the style attributes of individual HTML elements. It also supports most presentational HTML attributes.

Module’s use

After the module is configured properly and all permissions are set, we can start exporting entities and views to a PDF file.

Exporting entities

Entity Print adds a disabled field to the view modes of each content type. The field has a default label value of "View PDF". To make this field visible on any content type, enable it on the Manage Display page

(/admin/structure/types/manage/[content_type]/display).

Enabling the View PDF field on the Manage Display page of the Entity Print module

From now, we’ll have a view PDF button added to our content type. The URL button is:

https://example.com/print/pdf/[entity_type]/[entity_id]

(i.e. https://example.com/print/pdf/node/1)

View PDF option visible in a PDF file

 

Here is the PDF we want to save or print:

An example of a PDF file to save or print in the Entity Print Drupal module

 

Exporting Views

With the Entity Print Views module enabled, a "Print" Global option can be added to the View's header or footer.

The URL button looks like:

https://example.com/print/view/pdf/[view_id]/[display_id]

Adding a Print Global option to the View's header in the Entity Print module

 

Debugging

For easy and quick debugging, Entity Print provides us a HTML version of the entities sent to the PDF engine. The URL looks pretty much the same as above only with /debug appended.

E.g. https://example.com/print/pdf/[entity_type]/[entity_id]/debug.

How to hide the View PDF link in the exported file

By default, the "View PDF" link is also added to the PDF. To remove it, go to the Manage Display page for the specific content type. On the Custom Display Settings section you need to enable the PDF view mode.

Custom display settings in the Entity Print module

 

Now you can disable the Entity Print field on that view mode. Next time you export the PDF, you won’t have the "View PDF" link included.

By default, the PDF view mode is installed for Nodes only. In case you have any custom entities, you must first create a PDF view mode for the specific entity type via "admin/structure/display-modes/view". You can name it whatever you like but remember that a machine name should be "pdf", as it will be automatically prefixed with the entity name.

Styling the PDF from your theme

The following examples show how to register entity_print CSS files from your_theme_name.info.yml file. You can do it for any entity type or even view.

#Add css library to all nodes:

entity_print: 
  node: 
    all: 'YOUR_THEME_NAME/print-styling' 

#Add css library to the Node entities but only article bundles:

entity_print: 
  node: 
    article: 'YOUR_THEME_NAME/print-styling' 

#Add css library to all views:

entity_print: 
  view: 
    all: 'YOUR_THEME_NAME/print-styling' 

Don’t forget to define a CSS library in your YOUR_THEME_NAME.libraries.yml:

print-styling: version: VERSION css: theme: css/print-style.css: { } 

 

Modifying templates

All the normal ways to override templates are available. Using theme hook suggestions, you can create a Twig template and modify the content of any specific entity (e.g. node--blog-post--pdf.html.twig). In this template, you can modify the markup as you normally do by using {{ content.field_example }} or {{ node.field_example }}.

You can modify the HTML output of the entire Entity Print template. Just copy the entity-print.html.twig file from its base location into your theme folder. Using theme hook suggestions, you can also create entity-print--node--[content-type].html.twig file.


 
   {{ title }}
   {{ entity_print_css }}
 </head>
 <body>
   

{{ content }}

Make sure the {{ entity_print_css }} is always included inside the tag tag head in your custom Twig template file. Otherwise your custom CSS libraries won’t work.

Custom PDF Engines

It’s worth mentioning that the Entity Print PDF engines are pluggable. It means you can easily implement your own engines. To do so, you need to create a class in your_module_name/src/Plugin/EntityPrint/NewPdfEngine.php that implements Drupal\entity_print\Plugin\PrintEngineInterface with its all required methods. After that, your plugin will be available in the engines select list on the configuration page.

Alternative solutions

There are a few other options for making a PDF of an entity in Drupal that you might want to investigate.

PrintFriendly & PDF is a plugin for Drupal 7, 8 and 9. Below you can see its features list:

  • It’s fully customizable.
  • With the On-Page-Lightbox option, the PDF file opens in a Lightbox.
  • It lets you print or get a PDF.
  • You can edit the page before printing or getting a PDF, for example by removing the images and paragraphs you don't need.

Printer and PDF versions for Drupal 8+ is a module that also works for Drupal 9. It allows you to generate the following printer-friendly versions of any node:

  • webpage printer-friendly version (at /node/[node_id]/printable/print),
  • PDF version (at /node/[node_id]/printable/pdf).

Supported libraries:

  • mPDF,
  • TCPDF,
  • wkhtmltopdf,
  • dompdf.

Summary

The Entity Print module provides multiple methods of exporting entities to PDFs via different PDF engines. It is a very flexible and customizable module which will help you in dynamic generation of your articles, invoices or other content related to your Drupal website. The module has full test coverage and is ready to be used in production for Drupal 7, 8 and 9.

Jun 04 2021
Jun 04

Continuing our series highlighting the work of initiative groups across the Drupal community, this month we are catching up with six more groups:

  1. DrupalCon Europe Advisory Group, by Imre Gmelig Meijling
  2. Drupal Trivia, by Stella Power
  3. Bugsmash, by Kristen Pol
  4. Decoupled Menus, by Théodore Biadala
  5. Project Browser, by Mihaela Jurković
  6. Security Team, by Tim Lehnen

The takeaway message this month is that there are some key opportunities to get involved and help grow the Drupal community with fun and interesting contribution. Certainly, helping Stella with the curation of questions for one of the most fun parts of the Drupal year, Trivia, has to be a highlight!

If you spot a place where your skills fit, don’t hesitate to contact either the group’s spokesperson, or Community Liaison, Rachel Lawson.

What have been your priorities in the last three months?

Together with DrupalCon Europe Advisory Group, Kuoni, the Drupal Association and many local camp organisers and passionate Drupal volunteers from Europe and around the world, we have been working on DrupalCon Europe 2021.

While still being a COVID year and people getting weary of online events and sitting behind screens all day, DrupalCon will happen. We all need that place to connect and share, albeit online.

European Drupal camps are uniting with DrupalCon so Drupal enthusiasts will have 1 major conference to go to. Speakers, sponsors and attendees won't have to take up so much effort to organize an online event themselves. Instead they can team with the DrupalCon team and the international community to create one big experience with a lower threshold to go yet another online event. Plus a bigger, international reach.

The world will see Drupal still going strong at DrupalCon and they will get a chance to connect with various regions and Drupal communities.

And what has been your greatest success in the last three months?

It's been so great to see European Drupal Associations and community leaders get together to talk about maintaining a strong Drupal experience in Europe. Getting European countries as well as other international communities working together to create a united Eurovision Drupal experience is something that is really great!

What has been your greatest challenge in the last three months?

It's been a challenge to align European communities and camps and have as many as possible to team up with DrupalCon 2021. It's not so much about making money or spending time to create the experience, rather having one strong Drupal message and letting the world know Drupal is here to stay.

Do you have a "call to action" you want to make to the Drupal Community?

Please take a look at where DrupalCon and the local camps are at and see if it's possible for your camp, association or local community to team up. This can be very small and with little effort.

It's about uniting in common cause: the more camps will underscore this by teaming up, the stronger Drupal will come out of it.

What have been your priorities in the last three months?

The main priority in the last three months was, of course, writing the questions for Trivia Night at DrupalCon North America, as well as creating the picture clues.

And what has been your greatest success in the last three months?

Another very successful Drupal Trivia night at DrupalCon North America

What has been your greatest challenge in the last three months?

The greatest challenge was writing the quiz questions. It takes a lot of work, not just in writing the questions themselves, but also formulating the rounds so you hit the right mix of topics and the right difficulty level. Of course, the switch to the online/virtual format has also been a bit of a challenge - a different way of writing the questions is required.

Do you have a "call to action" you want to make to the Drupal Community?

Yes! I'm looking for someone else to help write the questions! It takes a fair bit of preparation work, so if someone would be willing to contribute their time to help write and curate the questions, with a view to taking on the role of being the primary question curator for one of the DrupalCons each year.

What have been your priorities in the last three months?

Recent priorities for the Bug Smash team have been to prepare for the DrupalCon North America initiative keynote and contribution event in April, including recruiting mentors, as well as our regular activities of issue triage and bug smashing. One fun thing we do each meeting is we nominate issue "targets" for the team to work on. These issues cover the gamut from views to form caching to ajax to media and so much more.

To see recent issue targets, our meeting transcripts are available in the issue queue.

But, one of the great things about the Bug Smash Initiative is that you have complete freedom to work on what you want and there are a wide variety of issues to choose from. Each person focuses on whatever interests them or fits within their available time. One person like mohit_aghera may focus on writing tests while others may focus on issue triage or accessibility reviews or testing.

And what has been your greatest success in the last three months?

The Bug Smash team has had some great successes over the last few months. The DrupalCon contribution event was a great way to mentor new contributors and onboard them to the initiative. larowlan ran an introduction workshop based on pameeela's Bug Smash presentation previously given at the Sydney Drupal user group. As a result of DrupalCon's success, we've had new team members jump into our Slack channel and start contributing!

Looking at the issue queue, there were more than 600 core issues worked on in the last 3 months with almost half of those fixed or closed. One fun issue that got fixed was from 2005! Big thanks to lendude and quietone for continuing to improve our bug statistics tools so we can better understand our initiative's impact. A fun fact from quietone during the May initiative meetings was there had been a ~584 year reduction in total number of years of all open bugs in the previous month! Whoa!

What has been your greatest challenge in the last three months?

At the biweekly Bug Smash meeting, we always ask about people's challenges during the previous fortnight. Some of them are fun personal distractions like new puppies or watching America's Cup, or not so fun life things like dealing with expensive car problems. Sometimes it's other Drupal activities that take people away from Bug Smash work like other initiatives or April's full-on DrupalFest activities.

From a more tactical viewpoint, finding "low hanging fruit" issues can sometimes be a challenge when we are trying to find quick wins. Or, we'll end up focusing on new issues rather than trying to get issues we've already worked on "over the fence". But, there is one challenge that you, the reader, can help with, and that's getting issues reviewed. If you have time to help, manually testing and reviewing fixes is immensely helpful. Search the queue for anything tagged as Bug Smash Initiative with status of "Needs review".

But, all in all, the number one challenge for the Bug Smash team is usually time… not enough of it. And, often, that's due to work being particularly busy. We highly encourage organizations who benefit from Drupal to free up some of their team's time to help on initiatives like Bug Smash. And, we highly recommend you read our very own Derek Wright's blog post on why organizations should support the Bug Smash Initiative.

Do you have a "call to action" you want to make to the Drupal Community?

A very simple call to action is simply attending one of the Bug Smash meetings. We meet every two weeks in Slack and it's asynchronous, so you can still participate afterwards within a 24 hour window. They are very well-organized thanks to jibran who typically runs the meetings and are transcribed by quietone, so everyone can get credit for participating. You can introduce yourself and ask questions, and we'll help you get acclimated. You can also review the helpful Bug Smash Initiative documentation to learn more (https://www.drupal.org/community-initiatives/bug-smash-initiative/workin...), thanks largely to the writing efforts of dww with help from other team members.

The Bug Smash docs specifically have a section on "how to help" (link to https://www.drupal.org/community-initiatives/bug-smash-initiative/workin...) but, as mentioned above in our challenges, if you are keen on helping review, that would be a great focus. Issue review involves reviewing code and/or manually testing the latest code fix works.

Based on the success of DrupalCon North America, we hope to have more mentored contribution events this year, so keep your eyes open or pop into the bugsmash Slack channel to check in on the status. If you are interested in helping mentor at these events, we very much welcome that contribution as well. Hope to see you soon!

What have been your priorities in the last three months?

We published the results of the decoupled survey that shed some light into what sort of things people use and expect from Drupal when used in a decoupled fashion.

On the Technical side we have the decoupled menus module published that provides the missing pieces for API consumption of menus. This was started in contrib to try out a few things, when things are stable enough we’ll propose it for addition in Drupal Core to provide this for everyone. There are also a couple of helper JS libraries: Decoupled menu parser, Linkset.

The team also spent a significant amount of time preparing for DrupalCon, making sure we have things for people to do, test, and help.

And what has been your greatest success in the last three months?

The thing that tied everything together was DrupalCon, where Baddý Sonja Breidert, Liam Hockley, Gabe Sullice, Juanluis Lozano, Brian Perry, Joe Shindelar did an amazing job of preparing and running the Decoupled Day.

We’ve had very good participation on the different workshops and some great examples of menu consumption based on the decoupled menus module:

A solid start at the documentation structure was made as well.

What has been your greatest challenge in the last three months?

Producing documentation has been a challenge, people prefer writing code!
DrupalCon helped with seeing what needs to be documented, the survey helped with what people expect, and what kind of tools people use.

Do you have a "call to action" you want to make to the Drupal Community?

By now most of the technical pieces are present and we need people to take charge of building the documentation for all this wonderful code so that it’s accessible to more people. This will in turn help us streamline the experience of consuming menu data from Drupal API.

You can head over #decoupled-menus-initiative slack channel and the Start an end-user-friendly technical documentation issue.

What have been your priorities in the last three months?

The Project Browser initiative kick off meeting was only 10 days ago! Getting started has been the main thing so far, and we can't wait to report on our further developments.

And what has been your greatest success in the last three months?

We have formed a group of people interested in contributing their ideas and efforts to the Project Browser. Several people stepped up to coordinate initial subtasks, and we started a list of potential features, the audiences they may cater to, and what might go into the Minimum Viable Product (MVP).

Our conclusion was that the Project Browser should help make Drupal more attractive to a general audience of site owners/builders as its first priority, by enabling them to easily expand the Drupal core site features through additional modules. The Project Browser will offer any audience a list of modules that is easy to understand, contains the relevant information, and filters out and sorts the modules reliably.

What has been your greatest challenge in the last three months?

The Project Browser needs to cater to multiple audiences at the same time. Our most important audience is the general public, or framed more specifically, site owners. Discovering their pain points is always a challenge. Without understanding exactly what problem we're solving for them it's difficult to prioritize the features we should focus on.

Do you have a "call to action" you want to make to the Drupal Community?

The Project Browser initiative needs input from site owners and builders who aren't experienced with the technical aspects of Drupal. If you are able to conduct interviews with some of those people (or ARE some of those people!), please come to our Slack channel (#project-browser) and share your wishes/experiences about what would make it easier to expand your Drupal site with more features.

Editor’s note: has kindly stepped in to help compile this information as you may well be aware that the Security Team have been fully occupied with the recent Drupal core security release. Thanks Tim!

What have been your priorities in the last three months?

The security team has been focused on two key areas in recent months. The first is our core mission of supporting responsible disclosure of security advisories and updates in the Drupal community. The second has been preparing for the Drupal Association's release of the community tier of Drupal Steward, which will shortly be available to customers at drupalsteward.org.

And what has been your greatest success in the last three months?

In the last three months we've successfully two Drupal core security advisories, and twelve security advisories for contributed modules.

These advisories represent the hard work of Drupal core and contributed module maintainers, security researches, and the security team itself, and continue to prove that the Drupal security team is one of the best in the industry.

What has been your greatest challenge in the last three months?

Our greatest challenge came with the most recent Drupal core release, SA-CORE-2021-003. This core release came outside of the regular release window, and coincided with unplanned infrastructure instability that delayed the release. We know this impacted many members of our community waiting for the release to drop, especially those outside of US time zones, for whom the final release came quite late at night.

We've released a post-mortem blog to talk further about what happened and how we hope to mitigate these issues in the future.

Do you have a "call to action" you want to make to the Drupal Community?

To keep up to date with Drupal security information you can follow any of the channels described on the Drupal security landing page. In addition to the news page and sub-tabs, all security announcements are posted to an email list. To subscribe to email: log in, go to your user profile page and subscribe to the security newsletter on the Edit » My newsletters tab.

You can also get rss feeds for core, contrib, or public service announcements or follow @drupalsecurity on Twitter.

Lastly, you can join the #security-questions channel in Drupal Slack to ask real-time questions of other community members related to security.

Jun 04 2021
Jun 04

With the digital becoming a ubiquitous part of life, businesses, both B2C and B2B, need to adapt their strategies and redefine them with a digital-first mentality, to determine how to make the best use of digital channels and latest technological innovations.

While some elements of a digital strategy are common to both B2C and B2B, there are many more aspects where the two differ. In this article, we’ll compare the key factors of digital strategy in B2C versus B2B, with a focus on content and marketing strategies. 

B2C

In B2C, marketing and driving business growth is more large-scale, aiming to reach as many potential customers as possible. The focus is on the customer experience across the entire customer journey and a multitude of different devices, so experiences need to be tailored for this omnichannel reality.

Due to the high focus on CX, data-driven personalization and conversion rate optimization are also key. Data obtained through machine learning algorithms is used to get a 360 degree view of customers and enable real-time marketing across all channels that they frequent.

B2C brands frequently interact with their customers via social media - Instagram, Twitter, to a lesser extent Facebook, and lately we’ve also been seeing a huge surge in TikTok usage and opportunities there. Since the start of the pandemic, a lot of brands have also implemented their own e-commerce solutions or started a presence on Amazon.

The messaging and advertising in B2C is more brand and product-oriented (i.e. product marketing). It also leverages purpose-driven marketing that resonates most with Generations Y and Z, which form the youngest and yet the largest part of the global consumer base.

Marketing relies heavily on data, from both 1st and 3rd-party sources. Advertising is a widely used B2C tactic and takes place across the entire web (and sometimes even beyond it, e.g. via in-app push notifications or SMS). Data is often handled with a data management platform (DMP) or customer data platform (CDP).

B2B

In contrast, B2B is much more focused, often employing what’s called account-based marketing (ABM), which involves messaging targeted at prominent decision makers of potential client companies.

It’s often more direct and personal, and focuses more on building and nurturing close relationships rather than on optimizations to the immediate customer experience; this is why the phrase “human to human” or “H2H” is now popping up more frequently. This also means that personalization is key; however, it isn’t as software-driven as in B2C, but involves more human research and input.

While B2B uses social media to a lesser extent, LinkedIn is the B2B social media platform. A lot of research and initial outreach happens there, as does most of the advertising. And, while B2C primarily uses email for newsletters and promotional offers, it’s an absolutely essential channel in B2B communication.

As opposed to unique marketplace-type websites à la Amazon, a B2B company’s digital presence is mostly centered around its own website, which can have custom landing pages for specific audience personas, or tied to specific advertising/marketing campaigns.

B2B companies produce content which is more industry or company oriented, as its goal is less to lead to an immediate purchase and more to help move the client further down the sales pipeline. 

This content is often longer than in B2C and features important industry insights and company achievements. The former can be gated, meaning that visitors are able to obtain them in exchange for their personal data - which is then used to initiate a conversation with them. Gated content most typically occurs in the form of white papers, in-depth guides, reports or webinar recordings.

For technology needs, B2B companies more often tend towards enterprise software which is typically more expensive but also more capable and robust. Because of their need for 1-on-1 communication, efficient video conferencing solutions are also a must.

Like in B2C, B2B companies also rely on data, but here less so on 3rd-party data gathered through software and more on data obtained via human intel. Customer relationship management (CRM) platforms are often used for a cohesive overview of client relationships.

Top considerations for both

As we stated in the introduction, a lot of elements of a successful digital strategy are shared between B2C and B2B. A culture of agility and innovation is becoming commonplace in the fast-paced digital age with both a lot of competition and rapid market shifts, where competitive edge is gained through swift responses to constantly emerging trends.

Human-centered design and accessibility are also of extreme importance, the latter even more so in B2C since here access to a digital location often means access to physical goods or services.

Automation is another tool that’s essential for any kind of business which wants to thrive in the digital era. Both B2C and B2B companies will want to streamline their processes and free their employees up for the kind of work which requires a more human touch. 

Automated email campaigns are key marketing tactics in both fields, and we’re now also seeing a greater use of chatbots, which can be entirely automated or used together with human agents.

Since mobile usage continues to be on the rise, lately increasingly also in less developed parts of the world, mobile optimization is an absolute necessity for both areas. While B2B companies are less likely to have dedicated mobile apps than B2C brands, both need to ensure that the mobile experience is adequate and comparable to a website experience.

As for marketing and content, both B2C and B2B are seeing the value of combining physical and digital channels. In B2C, this may look like digital campaigns which are tied to in-store campaigns, or leveraging a technology like augmented reality to bring the in-store experience closer to the digital customer.

In B2B, again, this is more personal, e.g. sending personalized gifts through the mail to clients, in order to thank them for their collaboration and/or strengthen the relationship with them.

Both B2C and B2B employ different types of content to reach their audiences. In B2C, you’ll likely see a greater use of social media stories and other video content, but even B2B is now featuring more video and even audio content (e.g. podcasts) in addition to blog insights. As we mentioned earlier, though, B2B typically has more long-form content, which tends to be true for video and audio as well.

Repurposing content is another tactic that’s shared between the two. The same topic or product can be presented in a variety of ways which will have different effects on different customers; perhaps a blog post would perform better in video rather than in written form, or certain visitors may prefer the shorter and more visually appealing infographics.

Conclusion

Man in business suit working on tablet

Whether your business operates in B2C or in B2B, it needs to embrace a digital-first approach to business strategy and the leaner and more flexible tactics that are so well positioned in the digital age.

That said, the ways in which the two succeed with digital can be vastly different, as we’ve demonstrated in this article. This is particularly evident with digital content and marketing strategies, where even when the same tactics or tools are used, how they’re used differs (e.g. different social media platforms and ways of achieving personalization).

If your digital strategy is already sound, but you could do with some help in the development department, get in touch with us and we can help you select the best technologies for it and execute on it.

Jun 03 2021
Jun 03

Mapping Google Groups to Drupal user roles with Google Authentication seemed like a straightforward task, but there were a few wrinkles in the process that I didn’t expect. We stumbled into the need for mapping groups to roles while performing a routine Drupal core upgrade from 8.8.5 to 8.9.13. Complications with the existing LDAP authentication’s upgrade path — and conversations with the client — steered us towards replacing LDAP with Google Authentication.

Overall the idea is simple enough: when a user signs into your Drupal site using Google Authentication, their membership(s) to various Google Groups should map to some existing Drupal user roles. This way, users in your organization who are already affiliated with various groups can be automatically assigned appropriate user permissions in your Drupal site for editing or accessing content, approving comments, re-arranging homepage promotions or whatever the case may be.

The majority of the functionality is established with just a few downloads, installations, and configurations. Our custom functionality relies on the Social API, Social Auth, and Social Auth Google modules, as well as the Google APIs Client Library for PHP. The first step is to install and enable the above mentioned modules and library. Then comes a little insider info on configuring the necessary Google Service Account, and finally a custom implementation of the EventSubscriberInterface that reacts to authentication via Social Auth to read from Google Groups memberships. Our custom code is packaged into a simple demo module you can download to get all of this working for yourself.

There are a lot of moving parts for something you’d expect to be a simple task, but in the end it’s a relatively quick setup if you know what to expect.

The devil’s in the details: Google Service Account configuration

This bit is pretty counterintuitive: Google users that authenticate via Google Authentication don’t actually have read access to their own groups. Weird, right? Where are you supposed to pull group information if the accounts can’t read their own group data from the API?

The answer is a Google Service Account. A properly configured Google Service Account can have read access to both users and their group relationship information, which allows it to act as a go-between during authentication to pull Google Group data and map it to Drupal roles. Configuring your Google Service Account isn’t self-explanatory, but luckily Joel Steidl put together the following screencast to walk you through it. Once you’ve set up the Google Service Account, you’ll just need to create and download a JSON key file to include in the code we’ll walk through further below.

Now that your Google Service Account is properly configured and your JSON key file has been safely stored away, it’s time to tie everything together with a few blocks of code that do the actual role assigning.

Role assignment during Google Authentication: The who’s who handshake

Once you’ve configured your Google Service Account and downloaded your JSON key file, you need code that reacts to Social Auth events (like a login via Google Authentication) to trigger the role mapping functionality. I’ve added some example code below that's part of a demo module that should get you 95% of the way there, although in our demo the role mapping itself — which Google Group becomes which Drupal role — is hard coded.

If you download my demo module you’ll see I’m reacting to both the USER_CREATED and USER_LOGIN events provided by the Social Auth module’s getSubscribedEvents method. This way we can reevaluate Google Group to Drupal role mappings each time a user logs in to make sure their roles and permissions stay up to date. You’ll also see that I’m verifying the user’s email address to make sure it falls within our expectations ([email protected]_domain.com), which you can modify or remove depending on your needs — but you want to make sure that your Google Service Account will have the appropriate access to this user’s group info.

The magic happens in the determineRoles method, where the JSON key file and the Google Service Account you setup previously will come into play. You’ll need to modify the getSecretsFile method to return your JSON key file, then change the $user_to_impersonate variable to the email address that you granted the Groups Reader role as discussed in Joel’s screencast. Finally, you'll need to update the $roleAssignment array with actual Google Group names and Drupal roles.

/**
 * When a user logs in verify their Google assigned group & set permissions
 *
 * @param \Drupal\user\UserInterface $givenUser
 *   The passed in user object.
 *
 */
protected function determineRoles($givenUser)
{
  $KEY_FILE_LOCATION = $this->getSecretsFile();
 
  // Only run if we have the secrets file
  if ($KEY_FILE_LOCATION) {
    // 1. Admin SDK API must get enabled for relevant project in Dev Console.
    // 2. Service user must get created under relevant project and based on a user with
    // 3. User must have Groups Reader permission.
    // 4. Scope must get added to Sitewide Delegation.
    $user_to_impersonate = '[email protected]_domain.com';
    $client = new Google_Client();
    $client->setAuthConfig($KEY_FILE_LOCATION);
    $client->setApplicationName('Get a Users Groups');
    $client->setSubject($user_to_impersonate);
    $client->setScopes([Google_Service_Directory::ADMIN_DIRECTORY_GROUP_READONLY]);
    $groups = new Google_Service_Directory($client);
 
    $params = [
      'userKey' => $givenUser->getEmail(),
    ];
    $results = $groups->groups->listGroups($params);
 
    // Hold Map for roles based on Google Groups
    $roleAssignment = [
      "Author Group Name" => "author",
      "Editor Group Name" => "editor",
      "Publisher Group Name" => "publisher",
    ];
 
    // Loop through the user's groups an add approved roles to array
    foreach ($results['groups'] as $result) {
      $name = $result['name'];
 
      //Assign roles based on what was determined
      if (array_key_exists($name, $roleAssignment)) {
        $givenUser->addRole($roleAssignment[$name]);
        $givenUser->save();
      }
    }
  }
}

That’s it! With your modified demo module enabled, your users should get their roles automatically assigned on login. We were pretty excited to get Google Groups mapping to Drupal roles, so much so that my colleague Matthew Luzitano is considering packaging this functionality (and GUI configurations!) into a Drupal module. So if you’re not in any rush and don’t feel like browsing our demo code, you can always wait until that happens.

Do you have a different approach to mapping Google Groups to Drupal roles? We’d love to hear about it! Let us know in the comments below.

Jun 03 2021
Jun 03

How is it possible that it’s been more than a year since the pandemic started? At DesignHammer, we are all grateful to have emerged from this crisis safe and sound. In this blog, the team took the opportunity to reflect back on the past year and comment on its challenges as well as unexpected silver linings.


How has working through the pandemic made work more difficult for you?

MiniaturesA big part of my job requires getting heads-down and writing code. It's challenging to get into the flow in a house full of people having video calls.

Has it affected your work life in any positive ways?

As a group we have put a lot of effort into developing our remote work techniques so that we all work more efficiently not being in the same office. I expect a lot of that experience to continue to be relevant once the office re-opens.

Have you found there to be any silver linings for you personally over the past year of the pandemic?

Like many, I have taken up a variety of new hobbies. It's been fun to explore and develop some new skills over the last year. An example is, I got an airbrush and have learned to build and paint models.

Jay Roberts, Lead Developer

How has working through the pandemic made work more difficult for you?

While our team and our clients have stayed closely connected via Slack and GoToMeeting, some kinds of collaboration (such as brainstorming with a whiteboard or ad hoc scoping discussions) are just not as easy remotely. We have had to be more focused on scheduling internal collaboration time and have not found a great replacement for the good old whiteboard at the conference table.

Has it affected your work life in any positive ways?

I've gotten a lot more used to video calls and see the value in using them over non-video calls in many instances. I also have enjoyed not having a commute each morning and evening (don't miss driving in traffic, even for values of RDU traffic).

Have you found there to be any silver linings for you personally over the past year of the pandemic?

For several weeks of the pandemic, I worked from home with my then-fiance (now husband) which gave each other a unique look into aspects of our personalities that we may not have as likely to have seen otherwise. Unfortunately, I have not able to pick-up any new hobbies or the like as it feels as though my time has been more restricted since starting to work from home :-(

Tiffany Cissel, Developer

How has working through the pandemic made work more difficult for you?

The most challenging part of working during the pandemic has been childcare. My two kids, now in fourth and first grades, have been in virtual school for over a year now. My wife and I, both with jobs requiring multiple calls and video conferences per day have to balance also being school monitors as well as parents. Making sure kids are in the correct Zoom session at the right time, are actually paying attention to class, and helping with their schoolwork is a contestant distraction from our job responsibilities. Add to this providing tech support, enforcing outside recess time, and preparing healthy snacks on demand on top of the normally expected homework review, school project supervision, test preparation leads to many late nights trying to stay up on job responsibilities. My wife and I are really looking forward to our kids return to their year-round in-person school in July.

Has it affected your work life in any positive ways?

Scheduling has become much easier. By not having to travel to meetings with clients or prospects, we typically save hours per week. Not attending out-of-town in-person conferences saves days of travel time, as well as not being away from home. I have also been able to attend virtual conferences I never would have been able to, based on time and expense, had they had not been for the pandemic.

Have you found there to be any silver linings for you personally over the past year of the pandemic?

Little girl on battleshipOne of the silver linings of the pandemic was a project I have spent time helping my now seven-year-old daughter with. She missed not being able to see her grandparents due to COVID lockdowns in early 2020 and was interested in participating in birthday card drives for seniors isolated from friends and family. She was connected to a veteran’s group online and began sending birthday greetings, as well as follow-up letters and photos. So far, she has sent over seventy cards and letters with photos in total to over a dozen women who served in the US military during World War II. All served in either the US Coast Guard SPARS or the US Navy WAVES. The veterans, all women who are now between 96 and 106 years old, live across the US from Maine to California and North Dakota to Texas. The WAVES and SPARS share stories of life growing in the 1920s and 1930s, many in rural America, their time in service during WWII, as well as the joy my daughter’s correspondence bring to them. My second silver lining was helping my wife create a YouTube channel. The channel, Cocktails Under Quarantine, is all about helping people learn how to make craft cocktails at home through a combination of recipes, book and spirit reviews, and interviews with other content creators. The first video was intended only for friends and family, shot and uploaded to Facebook straight off her iPhone, and admittedly had pretty awful production value. Over the next twenty-five episodes we upgraded equipment and learned about audio recording, lighting, and editing, to the point that the latest results are pretty decent. While always just a project my wife and I could have fun doing together, we somehow acquired a small following, and the videos have been viewed thousands of times, with regular requests for recipes or reviews of particular spirits. Our hopes to further improve the quality of our content, and continue the channel post pandemic.

[embedded content]

David Minton, Managing Partner

How has working through the pandemic made work more difficult for you?

We lost the opportunity to simply walk over to someone's desk and brainstorm about issues we may be having with a work-related task. Plus we never get to see each other unless it's through video chat. I know this may sound crazy but I actually miss seeing my co-workers 5 days a week.

Has it affected your work life in any positive ways?

I still go to the office every day, so that aspect has not changed. Well except that the office is usually void of people. But for me, the most positive part is the lack of traffic on the roads. It's starting to fill back up over the past few months, but it's still not near the level it was before the pandemic. I think I've only been in 1 or 2 traffic jams since this all started.

Have you found there to be any silver linings for you personally over the past year of the pandemic?

I've been able to spend more time with my family which I really appreciate. Before the pandemic, they were always out doing something that keep them busy. And now that their favorite activities aren't available, along with the many restrictions, they stay home more.

Frank Yonnetti, Partner / Designer

How has working through the pandemic made work more difficult for you?

As many others have stated, the lack of social interaction has probably been the most difficult thing to cope with over the past year. It's difficult from both a morale and a productivity standpoint. In terms of morale, working form a virtual setting discourages social interaction with colleagues and I have not kept up with all the "happenings" in everyone's lives. From a productivity standpoint, it's a lot more difficult to provide and recieve immediate responses from team members via Slack than it would have been to simply walk 10 steps over to their desks from across the office. I've also missed out on the opportunity to meet new people at in-person at various conferences and networking events, so expanding DesignHammer's network and keeping up with professional communities has also been difficult.

Has it affected your work life in any positive ways?

PuppyI have to admit I don't mind gaining the extra hour everyday that would have been spent driving to and from the office through RTP traffic. Extra sleep has definitely been good for my psyche and has also probably been beneficial to me in terms of personal productivity. We already had a pretty flexible work-life balance at DesignHammer pre-pandemic, but having less personal interactions (and even less client interactions) means I have had even more personal freedom to mold my work schedule in a way that best fits my needs.

Have you found there to be any silver linings for you personally over the past year of the pandemic?

The pandemic has given me more time to connect with my partner who is also working from home. Before the pandemic I always disliked the act of cooking and would often eat out more than I'm proud to admit, but as working from home has gifted me with extra time and energy, I decided to start cooking daily. Turns out I'm actually pretty good at it, and it also turns out that weekly meal prepping and planning becomes less overwhelming with both practice, and a plethora of newly mastered recipes to choose from. I also took the WFH opportunity to adopt a new puppy since I knew I would be able to give it much more attention given the new circumstances than I would have been able to had I been commuting to an office every day. 

Hunter Deschepper, Account Manager

How has working through the pandemic made work more difficult for you?

The virtual interaction with the team is just very different. Without actually being present together, there's a higher requirement to maintain connection and camaraderie, and sometimes that doesn't happen. Additionally, it's harder to be aware of everyone's workload, so it's easier to overload someone at any specific time. And yes, I may go a bit stir crazy sometimes ;)

Has it affected your work life in any positive ways?

The fact that I've been able to be at home since my son was born in January has been a huge positive, and has greatly reduced the stress that I would have felt being at work during those first few months.

Have you found there to be any silver linings for you personally over the past year of the pandemic?

Well, my son was born January 2nd, so there's that ;) I mean, the pandemic didn't make that happen, but it's still a pretty big life goal. Also, being able to be home with my wife more (she works over the weekends, so we don't have any days off together) has been nice, even more so after Holden was born.

Michael Nicholson, Project Manager

How has working through the pandemic made work more difficult for you?

Dad and SonAround the time the world started working from home, 2 big life changes happened: the nanny for our then 1-year-old started to become less available, and ultimately pregnant, and I moved to an open floor plan loft. Managing a child learning to walk and climb amidst work made life difficult for sure. Also the loss of immediate collaboration with co-workers took a minute to get used to.

Has it affected your work life in any positive ways?

Without the, admittedly enjoyable, distractions working in an office offers, it's been easy to knock out pockets at work at once. Also, as our office has a mostly open work environment it's easier to make client or sales calls, or be less distracted by others calls and meetings.

Have you found there to be any silver linings for you personally over the past year of the pandemic?

I've been around more to take the dog for a walk, to be able to drop off and pick up my son from school. A quick trip to the park, or a walk around the neighborhood is much easier than it used to be, and since I've been home more with less desire to watch TV, I've probably read over 150 books the last year or so.

Dave Shepley, Development Strategist

How has working through the pandemic made work more difficult for you?

I personally am able to work at the office, but everyone else is working remotely, so of course there are going to be struggling with trying to communicate over the phone about projects and what needs to be done. I have also affirmed even more with myself that I hate talking on the phone and over video, I'm definitely ready for that to be over.

Has it affected your work life in any positive ways?

I've surprisingly actually been able to work more because of the pandemic and I have a more stable work schedule. Thankfully because of this I can know what my day-to-day looks like and I can be home and have free time and also spend time with my husband.

Have you found there to be any silver linings for you personally over the past year of the pandemic?

Well, I got married and was able to have a small and intimate wedding with the people I most cared about! I also moved into a new apartment and became a plant mom. And finally like I stated earlier, I have a more stable schedule in general so I'm able to spend more time at home with my family.

Madelyn Mattsson-Boze, Graphic Designer

How has working through the pandemic made work more difficult for you?

Durham HomeWhile our team and our clients have stayed closely connected via Slack and GoToMeeting, some kinds of collaboration (such as brainstorming with a whiteboard or ad hoc scoping discussions) are just not as easy remotely. We have had to be more focused on scheduling internal collaboration time and have not found a great replacement for the good old whiteboard at the conference table.

Has it affected your work life in any positive ways?

I've gotten a lot more used to video calls and see the value in using them over non-video calls in many instances. I also have enjoyed not having a commute each morning and evening (don't miss driving in traffic, even for values of RDU traffic).

Have you found there to be any silver linings for you personally over the past year of the pandemic?

We moved in to a new house just before the stay-at-home orders came out, so we have had a year to unpack and settle in.

Stephen Pashby, Account Manager

As you can see, the pandemic has imposed many challenges on the DesignHammer team. But, we’ve also managed to figure out how to thrive, work together virtually, and even pick up some new skills! We hope that you have gotten through the pandemic safely and are looking forward to seeing you in person! As always, if you need a smarter website, contact us!


Jun 03 2021
Jun 03

In recent years, accessibility has become an essential factor for teams tasked with bringing new products, services, and experiences to market. The reason for this is clear: design works best when it works for everyone. Historically, though, either out of ignorance or intention, we have often designed with the assumption that all users are alike in their abilities to perceive and interact, but more and more we’re recognizing that just like food & nutrition, humans vary considerably in their preferences and restrictions. 

To be fair, it is much easier to assume that our users are largely homogeneous; that they not only share the same preferences and goals but also their ability to achieve those goals. As we learn more about the nature of human cognition and interaction, we come to appreciate how a whole host of physical, mental, and even social characteristics can influence the fundamental ways we perceive the world.

So what is accessibility?

Broadly speaking, accessibility describes the degree to which something can be entered, or used. Architects and civil engineers have long incorporated things like wheelchair ramps, motion- or button-activated doors as ways to improve accessibility in the physical world; businesses often offer telecommunications devices for the deaf (TDD) capabilities for sales/customer services phone lines; car retailers offer vehicle modifications to make them wheelchair accessible and operable by persons with a whole range of physical disabilities. All of these enhancements are the result of the painstaking work by affected groups and their advocates toward gradual recognition of and empathy toward (and laws protecting) the varying needs of all human beings. 

“The digital world has changed so many of our lives for the better and it’s crucial to make sure the same can be true for everyone.”

Troy Shields, Sr Front End Engineer, Zivtech

In the digital world, these enhancements are defined by the Web Content Accessibility Guidelines (WCAG), put forth by the World Wide Web Consortium’s (W3C) Web Accessibility Initiative (WAI). As one of the foremost advocates for the needs of all users, the WCAG and related guidelines serve as a north star for organizations and project teams looking to justly serve users of all abilities. Indeed, the guidelines are extensive and cover a wide range of topics and best practices, but the best place to start to familiarize yourself with accessibility is via their four principles:

Principle of Accessibility #1 Perceivable

1. Perceivable

Information and user interface components must be presentable to users in ways they can perceive.

Naturally, this is a given for any interfaces we create, but it’s easy to overlook how the nature of perceivability varies by ability. For low vision users, a simple thing like an icon, button, or image may not be perceivable at all. In this and similar scenarios, designers and builders need to account for this impairment with consistent use of alt text and other modifications. Now, think of a chart or infographic, how much more difficult might it be for a low-vision user to consume that information?

Principle of Accessibility #2 Operable

2. Operable

User interface components and navigation must be operable.

Once we’ve made our user interface fully perceivable, we must then ensure interactive elements are usable. This can be really challenging as there are so many adaptations that some of our users need to make in order to interact with the physical and digital world, most of which we take for granted. Users with visual impairments may have a hard time discerning and using things like mouse-over menus, confusing or unlabeled buttons, and the like. Moreover, users with physical disabilities may have a hard time completing form elements where multiple simultaneous maneuvers are required, eg CTRL + click.

Principle of Accessibility #3 Understandable

3. Understandable

Information and the operation of user interface must be understandable.

Understandable design creates and maintains consistent conventions that help users anticipate how the interface will perform as they progress through their journeys. It’s predictable in its use of design patterns and information architecture. Amazon sells a wide range of products, but its layout for books is the same as it is for sporting goods, as it is for clothing. Imagine if every product or product category had a unique layout - how challenging might that be for a user to anticipate where they might find the product specs or customer reviews?

Principle of Accessibility #4 Robust

4. Robust

Content must be robust enough that it can be interpreted reliably by a wide variety of user agents, including assistive technologies.

As the movement to accommodate people of different abilities has taken steam, so has the development of assistive technologies to help them. Today, there is a wide range of tools and devices that are designed to deliver improved user experiences for users with a wide range of physical abilities. Unfortunately, these assistive technologies do not all perform the same, so designers and builders must work to deliver a consistent experience. Consider web browsers like Chrome, Firefox, and Internet Explorers. All of these tools are built around standardized languages and frameworks like HTML (hypertext markup language) yet they all perform slightly differently. Imagine how broad the discrepancies might be for tools that aren’t based on any real widely accepted standards.

Principle of Accessibility BONUS: Robust

BONUS: Receptive

Interfaces should provide ways for users to provide feedback on their experience 

We humbly offer this as a fifth principle for your consideration. In the spirit of continuous improvement, we should always be looking to enhance the experiences we create, and that often starts by capturing feedback and learning from those we serve. Even with many hours of accessibility training, and several successful projects under our belt, our team recognizes that we can always get better at delivering exceptional experiences. We should all strive to be open to learning and feedback, and more consistent in our willingness to apply what we learn.

...

Overall, the WCAG Accessibility Principles seek to inspire empathy in designers and builders who are committed to creating digital experiences that work for all. They help establish internal project standards that are more thoughtful, curious, and ultimately more inclusive. The principles should help organizations and project teams factor accessibility in at the start of the project instead of just running some tests at the end. Indeed, accessibility is best executed when it’s built-in to the core processes of how we work, standardizing up-front approaches for how we approach elements like navigation and information architecture, being consistent with the use of interactive elements, and so on. 
 

"Accessibility should not be an afterthought, it should be an integral part of your design strategy right from the start. "

Barry Brooks, Creative Director, Zivtech

Indeed, delivering truly accessible experiences requires additional effort and forethought to achieve, but it’s absolutely worth it. When we enable more of our users to succeed in their journey, we succeed as well. 

Jun 03 2021
Jun 03

Occasionally I find myself needing plugin-like functionality, where users/downstream can throw a class into a folder and expect it to work. My script is supposed to find and instantiate these plugins during runtime without keeping track of their existence.

In a regular Drupal module, one would usually use the plugin architecture, but that comes with its overhead of boilerplate code and may not be the solution for the simplest of use cases.

Many class finder libraries rely on get_declared_classes() which may not be helpful, as the classes in question may not have been declared yet.

If you are on a Drupal 8/9 installation and want to use components already available to you, the Symfony (file) Finder can be an alternative for finding classes in a given namespace.

Installing dependencies

Ouside of Drupal 8/9, you may need to require this library in your application:

  1. composer require symfony/finder

A simple example

  1. use Symfony\Component\Finder\Finder;

  2. class PluginLoader {

  3. /**

  4.   * Loads all plugins.

  5.   *

  6.   * @param string $namespace

  7.   * Namespace required for a class to be considered a plugin.

  8.   * @param string $search_root_path

  9.   * Search classes recursively starting from this folder.

  10.   * The default is the folder this here class resides in.

  11.   *

  12.   * @return object[]

  13.   * Array of instantiated plugins

  14.   */

  15. public static function loadPlugins(string $namespace, string $search_root_path = __DIR__): array {
  16. $finder = new Finder();

  17. $finder->files()->in($search_root_path)->name('*.php');

  18. foreach ($finder as $file) {

  19. $class_name = rtrim($namespace, '\\') . '\\' . $file->getFilenameWithoutExtension();
  20. try {

  21. $plugins[] = new $class_name();

  22. }

  23. catch (\Throwable $e) {

  24. continue;

  25. }

  26. }

  27. }

  28. return $plugins ?? [];

  29. }

  30. }

Usage

  1. $plugin_instances = PluginLoader::loadPlugins('\Some\Namespace');

This is just an abstract catch-all example with a couple of obvious problems which can be circumvented when using more specific code.

In the above example, the finder looks for all files with the .php extension within all folders in a given path. If it finds a class, it tries to instantiate it. The try-catch block is for it to not fail when trying to instantiate non-instantiatable classes, interfaces and similar.

The above can be improved upon by making assumptions about the class name (one could be looking for class files named *Plugin.php) and examining the file content (which the Finder component is capable of as well).

Let me know of other simple ways of tackling this problem!

Jun 03 2021
Jun 03

Modern websites have become more and more extensive. At some point, a user may feel confused due to a large amount of content. At the same time, the website itself starts to be hard to use. Then the need to create a convenient, easy to develop, and maintain navigation appears. The solution which will work great in this case is a mega menu.

What is a mega menu?

A mega menu is a type of navigation consisting of several levels, used on websites. The first level looks like a standard list of links, but after hovering over one of its elements, additional options are shown. These options consist not only of a list of links in the second level of navigation but often have a third or even fourth level. Sometimes there are also visible photos or even videos. A menu built in this way is visually appealing to the user and allows them to easily find their way around large websites.

Below you can see the example of how the mega menu works on the webpage built in Droopler.

Mega menu in Drupal on the example of a website created in Droopler, a website builder

 

Mega menu in Drupal

In the Drupal CMS, creating a mega menu is quite a difficult task. That’s why the modules that simplify building advanced navigation were made. One of them is Mega Menu. Not only will it save you countless time creating and customizing complex navigation, but at the same time make your website amazingly impress your users.

Here’s how the Mega Menu module works: based on the default Drupal menus, the configurable mega menus are created. We can add to them submenu or even the whole blocks, using a friendly configuration interface. The additional option is the possibility to add a few columns in the submenu, setting styles, and animations.

Creating an extensive menu in Drupal, using a Mega Menu module

Source: Drupal.org

However, it’s important to mention the downsides of Mega Menu. One of them is that the module uses a separate Bootstrap library. This not only increases the size of the CSS and JS files, but also conflicts with the Bootstrap library used on the websites. The second disadvantage is that the navigation built with the Mega Menu module is poorly optimized for mobile devices.

In Droopler, a Drupal distribution, we rewrote the frontend part of the module from scratch. This way, we eliminated the most significant downsides of the default Mega Menu module. On the example of Droopler, we’ll show you how you can create with this module an extensive menu for your website.

Creating an extensive menu in Droopler

Droopler is a Drupal-based distribution dedicated to building corporate websites. It contains ready-to-use elements and tools enabling quick creation of the websites.

Main menu configuration

We can find the main menu settings in the Drupal administration menu in Structure. Next, in Drupal 8 Mega Menu, we look for the Main navigation element and from this element's menu, we go to Edit links.

Configuration of main menu in the Drupal administration menu

After going to the edit page, the working structure of the main menu appears, which we can freely edit using the "drag and drop" method. To add more levels to the menu, we need to move the secondary element to the right to create an "indentation".

Adding new blocks

To add a block to the menu, we must first add a new content block. We go to Structure -> Block Layout -> Add custom block and select the content block.

Adding a new content block to the menu

The system takes us to a form, where we add a new block. We fill out the title and the content of interest. In this case, it’ll be the title and a few links. Next, we add another block with the content and photo.

Editing a custom block in Droopler

 

After adding two blocks, we need to add them to the region on the page and - at the same time – disable the display of these blocks in the region. In the Block Layout of the header section, we click Place Block, and then select from the popup window the block we want to add and click Place block. In the next step, we uncheck the show title option and save.

Adding new blocks to the region on the page

 

When the blocks are added to the region, we should disable them. To do this, we click Disable in the block's action menu.

Disabling display of new blocks in the region

 

After completing this step, we can start adding blocks to the menu. To do this, we go to Structure, Drupal 8 Mega Menu, and then click config next to the main navigation.

We are taken to the menu edit. In our case, we’ll add blocks to the "products" element. After clicking "products", a configuration panel appears on the right. We check the Submenu in it as active.

Activating the Submenu in the configuration panel of the mega menu in Drupal

 

Now a workspace appears under "products", where we’ll add our blocks in a moment. After clicking on this element under "products", another configuration panel appears, but this time it concerns our workspace.

The configuration panel of the workspace

 

In this panel, we use the plus and minus buttons to set the number of columns in our mega menu. In the Grid field, we set the column’s width, while the Blocks field is used to select the previously added blocks.

After setting the appropriate options, we click Save and our menu should look similar to the one below.

The ready mega menu built with Droopler, a Drupal distribution, and the Mega Menu module

 

Summary

A mega menu is a good option for presenting to the user an advanced website’s structure or a web application. With the Droopler distribution and the Mega Menu module, we can easily build the advanced pages with a user-friendly navigation which allows us to clearly show the structure of a large website.

Jun 02 2021
Jun 02

DesignHammer has been awarded two 2021 Vega Digital Awards by International Awards Associate. The Divers Alert Network website redesign has been recognized with a Canopus Award (platinum) in the non-profit category, and a Centauri Award (gold) in the associations category. 

DAN Vega Award Winner

DesignHammer collaborated with DAN to consolidate three of their sites into one user-friendly WordPress website with a custom-designed, mobile-responsive theme to maintain brand identity and more effectively engage their audiences. 

"We are pleased with the recognition of the new DAN website by the Vega Digital Awards — and we’re thrilled with the improved user experience for our customers and members."

— Bill Ziefle, DAN President & CEO

Other notable Vega award-winning website projects this year were commissioned by The Smithsonian National Air & Space Museum, Natural Resources Defense Council, and State Farm Insurance Company.

The DAN awards are the 6th and 7th Vega Digital Awards for work with our clients since 2018. DesignHammer has submitted projects and won awards in three of the last four years. Other Vega Digital award-winning projects include work for RailincThe Center for Entrepreneurial Development (CED)Highland Industries, and The William Blake Archive.

The Vega Digital Awards are administered by International Awards Associate (IAA), a group of industry innovators, creators, designers, and communications professionals, deeply committed to moving the industry forward through the discovery and recognition of new and existing talent.

Evaluated in blind judging by a panel of senior-level digital media professionals from around the world, websites are judged on visual design, content, structure and navigation/functionality, interactivity, and overall experience. Winning entries represent excellence in design, development, marketing, and communications, and the opportunity to stand out in an international competition above thousands of other entities

See the rest of the 2021 Vega Digital award winners.

Jun 02 2021
Jun 02

Theme settings are simple and powerful, here's me figuring out how to create one.

Creating theme settings have so many uses. For example, you might have a sub-theme that wants to set a theme setting for the main/accent colour, and then use CSS variables to pull that into your theme - simple. Or, in my case, I want to create a base theme that is styled with CSS and JS, but allow sub-themes to switch off those libraries and just use the HTML from our templates.

Here's how:

I've started streaming some of my work, especially if it's contributions to open source, on twitch if you'd like to follow along/subscribe. As it turns out, Twitch deletes your videos after 14 days, so I have also been uploading them to YouTube. Feel free to subscribe.

Jun 02 2021
Jun 02

Last week, when I renewed my yoga teaching credentials through the Yoga Alliance, I was required to agree to an "Ethical Commitment" based on values intrinsic to the practice of yoga, such as ahiṃsā (nonviolence), satya (truthfulness), asteya (not stealing), aparigraha (non-possessiveness), and santoṣa (contentment). While it might seem like such an agreement would be limited to my role as a yoga teacher, these same principles inform decisions that I make in all aspects of my life, including how I build my website.

The page on this site titled "How I Built This Site" describes some of the technical choices I have made to represent myself online. This is the first article in a series of articles that will describe each of these choices in more detail.

This website is built using a content management system called Drupal. The Drupal community is one of the largest free software communities in the world, with more than 1,000,000 contributors working together. The values and principles of the Drupal community align well with the Ethical Commitment to which all yoga teachers certified by the Yoga Alliance must agree. While not all of the ethical commitments overlap, here are a few examples to support my claim:

While words and documents are important, I am more influenced by my lived experiences. In both communities I consistently interact with people and witness behaviors that align with my conception of an ethical life.

One significant difference is the Drupal community's commitment to free software that is difficult to find among yoga teachers. Yoga teachers rely heavily on "free" proprietary services that exploit their users, such as Instagram, Facebook, YouTube, etc. While I have accounts on all of those platforms, I avoid using them whenever possible.

Rather, my online presence relies heavily on Drupal. In this sense, Drupal functions as my "ethical base." Many of the methods I use to communicate with people online — newsletters, RSS feeds, forms, etc. — are provided by Drupal. Certainly there are many ethical alternatives to the tools used by "surveillance capitalists," but Drupal happens to be the one that I know well. I've been using Drupal for more than a decade and I personally know many of the people who contribute to Drupal.

Both yoga and Drupal have improved my life, and there is nothing magical about either of them. Drupal allows me to interact online in a way that feels consistent with my values. People who use Drupal are granted the "four essential freedoms" of free software. While it would certainly be easier to just use the tools provided by Big Tech, I cannot use those tools in good conscience. Drupal is not automatically ethical, and can be used for all sorts of purposes, both beneficial and harmful. In my case, I use Drupal because I wish to be nonviolent, truthful, and kind to all people. For more than a decade Drupal has provided a solid ethical foundation for my online presence.

Jun 02 2021
Jun 02

If you need a temporary buffer in Drupal to save data to, Drupal's tempstore service might come in handy. We used it for example in a webshop module, where users didn't have a saved address yet and also had to option to never save their address permanently (because of gdpr).

So, after some searching, the code is pretty straight forward. This example might save you some time to implement it

We implemented this in a custom Drupal webshop service, the functions are called in other code via dependency injection. So here is how to set and get your custom data with help of Drupal's tempstore:

(Be aware: the tempstore data wíll expire automatically)

  /**
   * Set data in Drupal's temp_store.
   *
   * @param array $vars
   */
  public function setMyDataInTempStore(array $vars) {
    // Get tempstore service.
    $tempstore = \Drupal::service('tempstore.private');
    // Get tempstore data we need.
    $tempstore_data = $tempstore->get('my_custom_key');
    $params = $tempstore_data->get('params');
    // Fill vars.
    $params['var_1'] = $vars['var_1'];
    $params['var_2'] = $vars['var_2'];
    // Save vars to tempstore.
    $tempstore_data->set('params', $params);
  }

  /**
   * Get data from Drupal's temp_store.
   *
   * @return array
   */
  public function getMyDataInTempStore() {
    // Get tempstore service.
    $tempstore = \Drupal::service('tempstore.private');
    // Get tempstore data we need.
    $tempstore_data = $tempstore->get('my_custom_key');
    $tempstore_params = $tempstore_data->get('params');
    // Get vars.
    $my_var_1 = $tempstore_params['var_1'];
    $my_var_2 = $tempstore_params['var_2'];
    // Return data in array.
    return [
      'var_1' => $my_var_1,
      'var_2' => $my_var_2,
    ];
  }
Drupal code Planet Drupal Written by Joris Snoek | Jun 02, 2021

Join the conversation

Pages

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web