Upgrade Your Drupal Skills

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

See Advanced Courses NAH, I know Enough
Nov 01 2021
Nov 01

Drupal SEO Series using Metatag

The Metatag module allows you to configure structured metadata such as meta descriptions and meta keywords for your Drupal website. You can do this at the global level, on a per content type basis, per node basis and even on a per view page basis.

In this tutorial we will show you how to:

  • Install the Meta Tag module
  • Configure meta tags for a content type
  • Override meta tags on a per node basis
  • Override meta tags for View pages
  • Have more granular permissions for meta tags fields
  • Specify meta tags for different favicons

Table of Contents

Getting Started

This module can simply be installed with Composer.

Using Composer:

composer require drupal/metatag

Once downloaded go to Extend and install just the Metatag module.

Once the Metatag module has been installed, if you go to /admin/config/search/metatag you will be presented with the main configuration screen which looks like this:

From here you can configure the metatags for your entire website (Global), or just for the front page, or on a per content type basis. We will now explain what each of these configurations mean.

Global – Here you can configure the default meta tags for all pages. What you define here will be applied to all pages unless it is overridden by configuring one of the other sections.

Front Page – Here you can configure the meta tags specifically for the front page only. As mentioned above, these settings will override the Global settings.

Content – Here you can configure the meta tags for all content types. We will show you how you can specify meta tags on a per content basis in Step 2 below.

Typically, you will want to set a different canonical url for each of the above mentioned configurations.

Configuring Meta tags for a content type

We will now demonstrate how you can add default meta tags to your content type. In our tutorial, we will use the Article content type. (You can apply the same steps to your other content types.)

1. On /admin/config/search/metatag click on “Add default meta tags”

2. Select “Article”

At this point (before you click on Save), if you were to click on “Browse available tokens”, you will notice that you do not see the Article node context in the popup modal window. So tokens from the Article content type are technically unavailable at this moment. You must click on “Save” and then try again. The following screenshots show the before and after of this step.

Before saving, you will see this:

3. After saving, you get another fieldset for Article:

And if you were to click on “Edit” and then “Browse Available tokens”, you will notice that the Article node tokens are now available as highlighted in the following screenshot:

We would also like to point out that at this point that the Article node inherits the meta tags from settings in Global and Content:

4. We are now going to override this by clicking on “Edit” next to the Content: Article.

As an example, let’s add field_tags to the keywords meta tag and the body text summary to the description meta tag field for Article. We have done this in the following screenshot:

Then click on Save.

In the main meta tags configuration screen (at /admin/config/search/metatag), you will notice a new value for Content: Article as shown here:

5. Now let’s test our new setting by creating an Article node and inputting some Keywords:

After clicking on Save, go to the new Article node and inspect the source code. You will notice that the meta tags for keywords and description have been prefilled with your Article node data as shown here:

In the example above, we set some default meta tags for all article nodes. However, we can override it on a per node basis. To do this, you will need to add an extra field to your Article node of field type “Meta Tags”.

1. In the “Manage fields” (/admin/structure/types/manage/article/fields) section of your Article content type click on “Add field”:

2. Add a field of type “Meta tags” and click on “Save and continue”:

3. Now edit the Article node you just created and you will notice a new Meta Tag fieldset like this:

If you expand this Meta Tag fieldset, you can override the Meta Tags just for this node.

Setting Meta tags for Views pages

The Meta Tag module has a submodule called Meta Tag Views which allows you to override meta tags for View pages. We will demonstrate how you can use this module.

1. Install the Meta tag Views sub module via the Extend page.

2. In this example, we will edit the View of the front page. On the View edit screen, you will instantly notice a new Page Setting for your View:

3. If you expand this Page Setting, you can override the meta tags for this View page. We will override the Keywords in this example:

Now if you go to your View page (in our case it was the homepage view), you will notice the update to your Keywords meta tag in the source code:

The Meta Tag module comes with a sub module named Meta Tag Extended Permissions. Enabling this module will give you more granular permissions that can allow certain roles to access specific meta tag fields.

Click on Extend in the toolbar and install the module.

Once enabled, if you go to admin/people/permissions you will notice some new permissions settings that you can toggle as shown below:

The Meta Tag module also comes with a sub module named Meta Tag: Favicons. Enabling this module will allow you to specify your favicons.

Click on Extend in the toolbar and install the module.

After enabling this module, go to admin/config/search/metatag and click on “Edit” for the Global settings as shown here:

On the next page you will notice a new Favicon fieldset:

Now you can specify your different favicons for different sizes.

Summary

The Meta Tag module is a great module that allows you to configure meta tags for various pages of your Drupal site.

This module comes with a bunch of sub modules which we have explained in more detail. We have touched on how you can configure the meta tags on a global level, on a per content type basis, per node basis and View page basis.

We also mentioned how you can configure favicons and have more granular permissions for meta tag fields. We encourage you to try some of these settings to optimize the meta tags for your own website.

Sep 28 2021
Sep 28

Mailchimp is a web based email marketing service used to send mass emails to a list of subscribers.

Drupal, out of the box, already allows you to send emails. However, there are distinct advantages to using a service like Mailchimp to send emails and maintain your mailing lists.

In this tutorial, you’ll learn how to integrate Drupal and Mailchimp.

The Mailchimp module integrates Mailchimp and Drupal by allowing Drupal to connect via Mailchimp’s API. This module also comes with a few submodules. Each submodule provides additional functionality that leverages Mailchimp’s features.

These submodules are:

  • Mailchimp Lists
  • Mailchimp Campaign
  • Mailchimp Signup

This tutorial will cover each of these submodules in more detail.

Table of Contents

Getting Started

First make sure you have a Mailchimp account. Just go to mailchimp.com and create a free account.

It is recommended to install this module using Composer so that the Mailchimp API library will be automatically downloaded to the correct location:

composer require drupal/mailchimp

To enable the module: we can use Drush:

drush en mailchimp -y

After enabling any Drupal module, it’s a good idea to clear the Drupal cache:

drush cr

Now go to Configuration >> Web Services >> Mailchimp (admin/config/services/mailchimp)

Here you need to enter your Mailchimp API key. The initial configuration screen looks like this:

You will notice the error:

“Failed to load Mailchimp PHP library. Please refer to the installation requirements.”

This is because you have not entered your Mailchimp API key yet. To get your Mailchimp API key, log into your MailChimp account and go to Account >> Extras >> API Keys.

Create your API key and insert it in the Drupal Mailchimp API key field as shown in the above screenshot and then click on “Save configuration”.

You may need to refresh the page to suppress the error.

At this point, you have successfully linked your Drupal site to the Mailchimp API.

Using the Mailchimp Lists

A Mailchimp List is also known as “Audience” within the Mailchimp interface. It seems Mailchimp uses the terms “List” and “Audience” interchangeably within their interface.

The Mailchimp Lists submodule allows you to subscribe any entity with an email address to Mailchimp Lists by creating a Mailchimp List field and allowing anyone who can edit that type of entity to subscribe/unsubscribe and update member information directly from within Drupal.

So what does this mean? In a nutshell, it allows you to connect your Mailchimp Audience to Drupal.

Then, any Drupal entity with an email field (typically the User entity) can be used to subscribe users to your Mailchimp Audience. The process of “subscribing users” is done by the Mailchimp Signup submodule, which is explained further in this tutorial.

The Mailchimp List submodule only connects your Mailchimp Audience to Drupal so that Drupal is aware of all your Mailchimp Audiences.

Step 1: In Mailchimp go to “Audience” and create your Audience/List. For this tutorial, we have created a Mailchimp audience with the name “Webwash Test Audience”.

NOTE: You can only create a single audience using a free account.

Step 2: Use Drush to enable Mailchimp Lists in Drupal:

drush en mailchimp_lists -y

Step 3: Clear the Drupal cache:

drush cr

At this point, in Drupal if you go to Configuration >> Web services >> Mailchimp >> Audiences (admin/config/services/mailchimp/lists) you should see all of your Mailchimp lists which looks like this:

To allow Drupal users to be added to this List, go to the “Signup forms” section of your Mailchimp Audience as shown in the screenshot below:

There are a few options on this page to embed the form into your Drupal site, which mostly involves creating and editing the form from within the Mailchimp interface and then embedding the generated HTML code directly into a Drupal block or page template.

You can also use the Mailchimp Signup submodule, which creates a block or page with a simple web form with fields such as Email (required), First Name and Last Name etc. When users submit this form, they will be subscribed to your Mailchimp list.

Now that you have connected your Mailchimp Audience (List) to Drupal, you can allow users to subscribe to your Mailchimp list within Drupal.

How do you do this? You have to use the Mailchimp Signup submodule.

Using the Mailchimp Signup

The Mailchimp Signup submodule allows you to create blocks and/or pages within your Drupal site to allow users to subscribe to Mailchimp Lists. This way, you do not have to embed any Mailchimp generated code into your site.

We will now demonstrate how you can use this module.

Step 1: Enable the Mailchimp Signup submodule using Drush:

drush en mailchimp_signup -y

Step 2: Clear the Drupal cache:

drush cr

Go to Configuration >> Web services >> Mailchimp you will notice a new tab “Signup Forms” as shown below. The direct Drupal URL is:

admin/config/services/mailchimp/signup

Step 3: Add a Signup Form

Click on “Add Signup Form” and fill in the details. For this tutorial we will select both Block and Page for demonstration purposes. This is a screenshot of our Signup form:

Notice that the Mailchimp Audience is automatically available (thanks to the Mailchimp List submodule).

In the Merge Field Display section, you will see the fields that are generated from your Mailchimp form. You can edit these fields by going to the Settings of your Audience in Mailchimp and then under Settings, click on “Audience fields and *|MERGE|* tags” as shown below:

If you selected Page Display mode, you can go to the URL you entered and your sign up form should look like this:

For the Block Display mode, you must clear the Drupal cache first and then you can add the block to any region in the usual Drupal way by going to Structure >> Block layout and placing the block in the desired region. We have placed our block in the right sidebar region of our homepage and it looks like this:

NOTE: If you go to Structure >> Block layout and you do not see the Sign up block when trying to place it in a region, you should clear your Drupal cache.

Permissions

It is worth mentioning that the Mailchimp Signup module comes with some permissions as shown below. You can set this to your liking:

Using the Mailchimp Campaigns

The Mailchimp Campaign submodule allows Drupal users (with the appropriate permissions) to send Mailchimp campaigns from within Drupal. The content of the campaigns can contain any Drupal entity or custom HTML content.

We will demonstrate how to set up Mailchimp Campaigns from within Drupal.

Step 1: Enable the Mailchimp Campaigns submodule using Drush:

drush en mailchimp_campaign -y

Step 2: Clear the Drupal cache:

drush cr

Step 3: Set the appropriate permissions.

The Mailchimp Campaign submodule comes with 1 permission allowing a specified role to administer Mailchimp Campaigns from within Drupal (see screenshot below). You should set this permission to the appropriate role.

Step 4: Create at least 1 Audience Tag

As of March 21st 2021, there is a reported bug whereby if you do not have any Audience Tags defined for your Audience, you will not be successful in creating a campaign in Drupal. Follow the bug here. A temporary workaround is to create at least 1 Audience Tag in Mailchimp.

So let’s create an Audience Tag in Mailchimp. In Mailchimp, there are two ways to add Audience Tags. You can either click on the Tags menu in the left sidebar for your Audience, or find the Tags setting under “Manage Contacts”. Both options are shown in the screenshot below:

Go ahead and create a tag. Even though we are not using this Tag for our Campaign, we need at least 1 Tag created until the bug has been fixed.

When this bug is fixed, Step 4 will no longer be required.

Step 5: Add your Mailchimp Campaign within Drupal

There are two ways to add Mailchimp Campaigns. One way is from within the Mailchimp interface (hereby bypassing the need for this module) and another is using this module and doing it inside of Drupal. It is important to note that if you create a campaign from within Mailchimp, it will not be imported into Drupal. However, the reverse is not true. That is, if you create a campaign from within Drupal, it will be automatically imported into Mailchimp.

To create your campaign within Drupal, go to Configuration >> Web services >> Mailchimp and click on the Campaigns tab. Then click on “Add Mailchimp Campaign”. This is shown below:

Fill in all the necessary fields. Notice that the Audience Tags field is automatically prefilled once you select the Audience as shown below:

NOTE: At the time of writing this tutorial (March 21st 2021), if you try to create a Campaign from within Drupal, it will only work if you do not select a template as shown below.

Whatever you type into the “Content” field will be inserted into the email body when you send the Campaign. Follow this issue to keep updated when there is a fix.

Once you create your Campaign in Drupal, it will look similar to this:

And your Campaign will be automatically imported into Mailchimp which will look like this:

Summary

Mailchimp and Drupal can be connected to integrate Mailchimp’s features in Drupal. We have shown how to use the Mailchimp module to do this.

The Mailchimp List submodule can be used to connect your Drupal entities to a Mailchimp Audience.

Once connected you can then use the Mailchimp Signup submodule to provide a page/block for Drupal users to actually sign up and be added to your Mailchimp Audience.

And finally the Mailchimp Campaign submodule can be used to create Campaigns within Drupal.

Sep 21 2021
Sep 21

View Bulk Operations, commonly referred to as VBO, is a module that allows specifically defined actions that can be simultaneously executed on rows of Views data.

This tutorial will show how to install this module and set up a simple View with a defined action and VBO field. We will then demonstrate how to use VBO to perform this action on selected View rows. We will also show how you can define permissions for roles to use our defined action.

Drupal Views Series

Table of Contents

Getting Started

We can easily download VBO using Composer:

composer require drupal/views_bulk_operations

To enable VBO you can use drush:

drush en views_bulk_operations -y

After enabling any Drupal module, it’s always a good idea to clear the cache:

drush cr

Create a View

For this tutorial, we will create a simple View that will list recently created content of type “Basic Page”.

For our View to display results, we should have some content of “Basic Page” already created. If you don’t already have content, go ahead and create some content of type “Basic Page”.

Now let’s set up a very simple View. Our View just lists nodes of type “Basic Page” in a table format. Here is a screenshot of the Views configuration screen:

And here is the output of the above View:

Add VBO field to the View

The magic happens when we add the VBO field to our View. For this tutorial, we will create an “Unpublish” action that will allow users to unpublish nodes of “Basic Page” in our View.

1. In the Fields section of our View, add the “Views bulk operation” field:

2. After clicking on “Add and configure fields”, look for the “Selected Actions” section. We are going to select “Unpublish content item” and give it a label of “Unpublish” and then click on “Apply”. (You can select multiple actions as needed.) This is shown below:

Now your View should look like this:

3. If you had selected multiple actions, they would all be shown in the “Action” dropdown list. You can select some rows using the VBO field and apply the Action of “Unpublish” to see the changes. Follow the 3 steps in this screenshot:

The following screenshot shows the results after doing this to the first 2 rows. Notice the “Published” column values have been updated.

Specify which roles can apply specific Actions (Optional)

What if you only wanted to allow specific roles to use specific actions? The awesome developers of View Bulk Operations included a sub module called “Actions Permissions” to accomplish just that!

Let’s say we only wanted the “Authenticated User” role to use the “Unpublish” action in our above View.

After enabling the sub module “Actions Permissions”, go to Admin >> People >> Permissions and in the list of Actions Permissions you should select “Execute the Unpublish content item action on Content” as shown below:

Now only the “Authenticated User” role can apply the “Unpublish” action in our View. This “Actions Permissions” sub module becomes a very powerful feature when you have multiple roles in your site.

Summary

Views Bulk Operations (VBO) allows users to perform actions on View rows data. In this tutorial, we have shown how you can add the VBO field to a View and optionally give a specific role permissions to use this action.

Sep 07 2021
Sep 07

The Coffee module adds quick search functionality for backend pages in Drupal. The module was inspired by the Spotlight app on MacOs and Alfred.

Coffee makes it possible to navigate quickly through backend configuration pages by just searching for them instead of using the toolbar.

Table of Contents

Getting Started

Before we begin, download Coffee by running the following Composer command:

composer require drupal/coffee

Then go to Extend and install the module.

How to use Coffee

To display the pop-up window, use alt+D (or alt+K) for Windows or opt+D for MacOs.

Start typing the page title, and you should see results returned, then click on one of the returned results and you’ll be redirected to the page.

You can also display the pop-up by clicking on the “Go to” link in the toolbar.

Jump to Create Page using :add

Furthermore, Coffee facilitates opening a new page or article for you, just type “:add” and choose an article or a basic page. You can also go to the front page by typing colon only.

Module Settings

You can configure the module by going to Configuration -> Coffee (/admin/config/user-interface/coffee).

Here you can configure which menus will appear in the results and the max number of items returned. By default, it’ll only show a max of 7 results.

Module Permissions

The module comes with two permissions:

  • Access Coffee: This allows you to use the Coffee functionality.
  • Administer Coffee: This allows you to configure the module.

If you have an editor role and you want them to use Coffee then assign them the “Access Coffee” permission.

Change Keyboard Shortcut

Currently, you can’t change the default shortcut key from Command/Ctrl/Alt-D. There is, however, a patch for the module if you really want to do it.

If you want to define your own commands in the Coffee module using (hook_coffee_command); see coffee.api.php for more documentation.

Alternative to Coffee

The Admin Toolbar module comes with a quick search functionality which is similar to Coffee. You can learn more about this by reading the “Add Quick Search and Drop-downs to the Toolbar using Admin Toolbar in Drupal” tutorial.

Summary

The Coffee module offers handy functionality especially if you spend a lot of time administering Drupal sites.

The ability to quickly jump between pages can speed things up and make you more productive.

Aug 24 2021
Aug 24
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

Linkit gives you an easy interface with an ‘autocomplete’ field to search for content on your site, and then link to it. In other words, it provides search functionality to find the content on your site and insert the corresponding internal link.

Using the same interface, you can also insert external links. So you can insert links, both internal and external, with the same interface.

It supports internal links to nodes, users, taxonomy terms, files and comments, etc. With this module, you do not need to copy or remember the target URL, or go back and forth to find out and verify the exact link. It provides a more user-friendly interface well integrated with the insert link function of the editor.

Table of Contents

While working on links, you will find that you need something more, such as the option to open the link ‘in a new window’. You might as well also install another module called the Editor Advanced Link, which is another popular module which provides enhanced features for inserting links. For this reason, it is recommended also to install this module at the same time, to make it more complete.

In fact, it was also mentioned in the project page of the Linkit module that, starting from version 8.x-5.x, support for link attributes has been removed, and this Editor Advanced Link module is recommended there.

Getting Started

Installation of the Linkit module is easy. There are no extra requirements. Just follow normal module installation procedure. However, note that there are different versions in this module. At the time of this writing, there are:

  • 6.0.0 which requires Drupal 8.8 | 9
  • 8.x-5.0 which also supports Drupal 8.8 | 9
  • 8.x-4.3 which supports Drupal 8 prior versions
  • 7.x-3.6 for Drupal 7

If you are running Drupal 8.8 or above, we suggest installing 6.0.0 or later. For older versions of Drupal 8, you should install version 8.x-4.3. In this article, we shall focus on the latest 6.0.0 version.

Installation using Composer

If you follow the normal Composer installation, like

composer require drupal/linkit

ft will install version 8.x-4.3 by default. To install the latest version of the module, which is recommended, you need to specify the version in the Composer command:

composer require drupal/linkit:^6.0.0-beta2

Enable the Linkit module after installation.

Installation of the Editor Advanced Link module is straight forward. There are no extra requirements. Just follow normal module installation procedure.

Installation using Composer

Install using Composer:

composer require drupal/editor_advanced_link

Enable the Editor Advanced Link module after installation.

Configuring the Linkit Module

Configuration of the Linkit module is a little bit different for different versions of the module. In this article, we shall focus on the latest version 6.0.0.

1. Go to Configuration > ‘Content authoring’ and click on ‘Text formats and editors’

2. Click on Configure on the text format you’re going to use. In this example we’ll click on Configure on the “Basic HTML” row.

3. Enable Linkit under the ‘Enabled filters’ section by checking ‘Linkit URL converter’

4. Scroll up back to the ‘CKEditor plugin settings’, and select the ‘Drupal link’ tab. Make sure the ‘Linkit enabled’ option is checked, and then select the appropriate ‘Linkit profile’. Let’s choose the ‘Default’ profile for now. For more details about Linkit profiles, it will be covered below later.

After this configuration has been completed, linkit will be available for users.

How to Use Linkit

Users normally create content in the long text format fields using the default Drupal editor. To insert a link, you first highlight the text and click on the ‘Link’ button, and an ‘Add Link’ window will popup and there you can enter either an internal or external link.

You can see the small text under the space in this popup window, it says ‘Start typing to find content’, because it is now an ‘autocomplete’ field, which is enabled by the Linkit module.

If you are looking for the link to another internal content on the same site, just start typing with the title or keywords, and the system will automatically search for the matching content:

Here you just select the right content, and the system will insert the appropriate internal link for you into the editing text.

Note that these figures show the scenario without the Advanced Editor Link module enabled.

After installing and enabling the Editor Advanced Link module, an extra attribute ‘Title’ becomes available by default.

The ‘Title’ attribute, when entered, will appear when you hover over the link.

There are other attributes available apart from ‘title’, but they are limited by the ‘Allowed HTML tags’ setting in the Basic HTML editor configuration. These other attributes need to be enabled before you can use it.

To enable the other attributes from this Editor Advanced Link module, go to

1. Go to Configuration > ‘Content authoring’ and click on the ‘Text formats and editors’

2. Click on Configure on your text format.

3. Scroll down to the bottom and find the Filter settings. Select ‘Limit allowed HTML tags and correct faulty HTML. There you can find the attributes allowed associated with the tag for links. After the Editor Advanced Link module is enabled, the following allowed HTML tag reads:

Here you can find the attribute ‘title’, and that’s why it is available by default.

4. To enable the ‘target’ attribute, you can modify this allowed HTML tag by inserting the tag as follow:

target</strong>>

And then save the configuration. After that, you will find the extra attribute in the popup window:

With this ‘target’ attribute, you can configure the link to be opened in a new window or a new browser tab.

If you are an advanced user, you may add more available attributes to the allowed HTML tags for additional attributes. They include the following attributes highlighted as bold. Each represents a separate attribute corresponding to different CSS elements.

target class id rel</strong>>

We shall not go into details for these other attributes here.

Create Additional Linkit Profiles

Additional Linkit profiles can be created:

1. Go to Configuration > Content authoring and click on ‘Linkit’

2. From this page you can create and manage all your Linkit profiles. To create a new profile, click the ‘+ Add profile’ button, then enter in a “Profile Name”.

3. Click on the ‘+ Add matcher’ button to continue

4. Select a matcher from the list. When you search the content by autocomplete in the URL field, this is the entity you select here which the system will search from.

5. After selecting the matcher, you will arrive at this following page for additional configuration for this particular matcher.

6. Enter the ‘Metadata’ in the form of ‘tokens’. Metadata is additional information to be displayed in the autocomplete list of search which helps content creators to better identify the right content to select. Click on the ‘Available Tokens’ to display the list of tokens you can choose to configure. This list is based on what matcher you have chosen above.

As an example, following is the metadata field in the default profile for ‘content’:

by [node:author] | [node:created:medium]

which adds the name of the author and the date created to the list of autocomplete search. When searching in the URL field, it will look like this. The small text comes from the ‘metadata’ configured.

7. Complete other settings or you can leave them as default, then Click ‘Save changes’ to save this matcher.

For each profile, you can add additional matchers for different types of content that are allowed. Following is an example of multiple matchers created in a single profile, which allows content creators to search for different types of content entities. Each matcher will be configured with different matching metadata to display. This will make the content searching much easier.

In this example, matchers include content, users, taxonomy and media items (if the media module is enabled).

8. Do not forget to select the right profile in the target text format editor:

Summary

The Linkit module, together with the Editor Advanced Link module, provides a user-friendly interface for inserting both internal and external links.

The Linkit profile allows you to configure the appropriate metadata which appears when searching for content. This is helpful to content creators to accurately locate the appropriate content in the autocomplete search.

These 2 modules together allow us to provide a very nice user-experience for the content creators, and make life easier for them.

Jun 30 2021
Jun 30
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

Infinite scrolling is a technique used to show more content as the user scrolls down a page eliminating the need for the user to click to go to the next page. This is commonly implemented in popular social media apps.

This tutorial will demonstrate how to use the Views Infinite Scroll module to achieve this and also show options that can be used to customize the user interaction with the infinite scrolling behavior.

We will show you how to:

  • Install the module
  • Set up a simple view
  • Add the infinite scroll behavior
  • Customize the infinite scrolling behavior.

Drupal Views Series

Table of Contents

Getting Started

We can easily install Views Infinite Scroll using Composer:

composer require drupal/views_infinite_scroll

To enable you can use Drush:

drush en views_infinite_scroll -y

Step 1: Set up your View

For the purposes of this tutorial, we are assuming you already have a content type set up and have already generated enough content for it.

We are going to create a simple View that lists Articles (Title and Body fields).

Go to Structure -> Views -> Add view

Here is a screenshot of our simple View. There is nothing fancy. We are only listing published Articles and have created a Page display for it.

If you’re new to Views then check out our “Getting Started with Views” tutorial.

Step 2: Adding the Pager

In the Pager settings of your View, change the type to “Infinite Scroll” (leaving all the settings as default for now).

Also, in the Advanced section of your View, set “Use AJAX” to “yes”.

Here is how our View settings looks now:

Save your View and go to the URL of the View page to test out your Infinite Scroll. You should now see a “Load More” button in the pager section of your View page that looks like this:

And that’s it! You now have infinite scrolling for your View. However, there are more options that can be configured for your Infinite Scroll. These are all optional as we shall demonstrate them now.

Step 3 (Optional): Replace the button text

You can add tokens to your Infinite Scroll button to enhance the user’s experience.

In the pager section of your Views configuration page, open the settings of your Infinite Scroll pager as shown in the screenshot below:

Set the button text to “Load @next_page_count more (Total @total)” as shown in the screenshot below:

Now your Views Infinite Scroll Pager button text will look like this:

@next_page_count” and “@total” are called “tokens” in Drupal. The tokens are replaced with actual data automatically.

View Infinite Scroll supports the following tokens:

  • @next_page_count
  • @remaining_items_count
  • @total

Step 4 (Optional): Automatically Load Content

Currently, users would have to click on the “Load More” button to get the next set of content. The Views Infinite Scroll page has an option to automatically load content (without the need to click on the button).

Go to the settings of your Views Infinite Scroll pager and check the box “Automatically Load Content” and click on Apply.

Save your View and then test it. As you scroll to the bottom of your View, another set of content should automatically be loaded.

Warning: Enabling this setting means that the user never actually gets to the footer of your page until they have exhausted loading all of your content. For example, if you had 1000 articles, it would take a very long time to see the footer. This means that if you had important links in your Footer (like Privacy policy links etc), it’s almost unreachable.

Step 5 (Optional): Exposing Options to the User

Views Infinite Scroll allows you to expose settings to allow the user to control selected displays options. We will demonstrate by doing an example. In the Settings of your Views Infinite Scroll Pager, scroll to the “Expose Options” and check “Allow user to control the number of items displayed in this view”, then click on Apply and save your View.

This results in the following being added to the top of your View page:

This specific option will allow the user to select how many results are returned everytime they click on the “Load More” button.

Summary

Views Infinite Scroll is a neat module that allows you to add infinite scrolling behavior to your View. We have shown how you can use this module to achieve this infinite scrolling behavior and also demonstrated a few of its customizations along with one of it’s biggest pitfalls.

Jun 23 2021
Jun 23
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

In Drupal, content is stored in the database. Views is a query builder that allows the user to extract content from the database and output it in various displays such as tables and lists. With Views, the user does not have to know or write any SQL queries. If you want to create a page or block in Drupal that lists any kind of content based on different filter criteria, you should use Views!

In this tutorial, we will explain what Drupal Views are and how to create it. We will also demonstrate some simple customizations such as page settings, filters, sorting, display options, exposed filters, permissions, creating a View Block and creating an admin page using Views. By the end of this tutorial, you will know how to create and customize a Drupal View.

Drupal Views Series

Table of Contents

Getting Started

As of Drupal 8, Views already comes packaged with Drupal core so there is no need to download anything. If you installed Drupal using the standard installation profile then it’ll be already installed.

Go to Extend and make sure Views and Views UI are installed.

How to Create a View

In this section, we will walk you through the process of creating a very simple View that lists  published Articles using the teaser view mode.

First, ensure you have enough article content on your website and ensure you are logged in as the administrator. Now let’s create the View.

1. Go to Structure -> Views (admin/structure/views) and click on “Add view”.

2. On the “Add view” page, fill out the fields as suggested in the screenshot below. All we are doing here is giving the view a name, selecting “Article” in View Settings and ticking the box “Create a page”. Every other field can be left as the default for now. Click on “Save and edit” when you are finished.

Views Creation Screen – Figure 1

And that’s it! You have successfully created your View. If you were to go to “/latest-articles” you can see the output of your View.

We will now explain the major parts of the Views configuration screen. We have highlighted different sections of the Views configuration screen in the screenshot below and labelled each section with a number for easier reference and explanation.

Views Config Screen – Figure 2

Label 1 – As the name suggests, this is the title of the View. This is the text that will appear as the title of the /latest-articles page.

Label 2 – This determines the output style of the view. Frontend themers can use this to style the output by overriding the default templates provided by Views. There are also contributed modules that can extend and provide more options such as Views Slideshow.

Label 3 – This determines how each row result of the View should be displayed. Currently it’s set to “Content” which allows us to choose different view modes like Teaser or Full Content. If you want to show just specific fields of your Articles, you can change it from “Content” to “Fields”. Then, you can select the fields you want to display in Views Config Screen Label 4.

Label 4 – Based on which Format style you choose above, this section will allow you to choose the specific fields to display.

Label 5 – This section allows you to define criteria for filtering your View results. Currently we are only showing published articles.

Label 6 – As the name suggests, we can define how to sort the View results. You can also sort on your content type fields by adding them here.

Label 7 – This is the path for your View page.

Label 8 – If you want to add your View page to any of your Drupal menus, this is where you can do it.

Label 9 – In this section you can define specific permissions for who is allowed to access your View.

Customizing your View

Let’s say we want to customize our current View to display a table layout with just Title and Body fields of the Article content type. But we also wanted to allow the user to input a text string that will filter the results against the Title. We will refer to the labelling in Figure 2 to help with our explanation.

1. Update the Format (Views Config Screen Label 2). Set it to Table. You can leave the default Table settings.

2. In doing Step 1, you may notice that Views automatically added the Title field in the Fields section (Label 4). Let’s add the Body field as well.

Click on “Add” in the Field section:

In the “Add fields” popup, search for “body” and click on “Add and configure fields”.

On the “Configure field: Content Body”, you can leave all the defaults and just click on Apply.

3. Now let’s demonstrate how to allow the user to enter text into a field that will automatically search against the Title field. In Drupal Views, this is called an “exposed filter”.

To create this exposed filter, click on “Add” in the Filter Criteria section (Label 5).

Then search for Title in the next screen and click on “Add and configure filter criteria”.

On the next screen, check the box “Expose this filter to visitors, to allow them to change it”. More options will automatically become available. Make sure to set the Operator to “Contains” and then click on “Apply”.

Tip: “Contains” means Views will use the string entered by the user and execute a SQL search in the database for any string that contains the characters entered in that order, i.e., “...LIKE %usertext%...” in SQL.

4. Now that we have set the Table Format, Title/Body fields and exposed filters, it’s time to save the View. This step can be easy to miss so don’t forget it!

Now if you view the actual View page, the View output should look like this:

Create Block using Views

A View Block is just a regular Drupal block except it originates from Views.

For demonstration purposes, let’s say we wanted to create a block version of the View page we created above.

There are two ways to do this. You can either click on “+Add” or click on “Duplicate as Block”. Both options are shown below:

Once you have done that you will notice you will now have “Block Settings” instead of “Page Settings”. This makes sense since now we are dealing with a Drupal Block.

Go ahead and save your View. Once the View is saved, a Drupal block is automatically generated and will be listed alongside all the other Drupal blocks.

Place the block anywhere in your Drupal site as you normally would place any Drupal block into a region. Here is a quick video of how to place a Drupal block into a region. We placed ours in the left sidebar and it looks like this:

You will notice our exposed filter is not being displayed in our Block. There is one extra step involved if you want to get exposed filters to work in View blocks. On the View configuration screen, inside of Advanced, set “Use AJAX” to yes and save your View. Here is how that looks:

Now our Views Block has the exposed filter which looks like this:

Create Admin Page using Views

Let’s say we wanted to use the View page we created above but place it within the admin UI and only accessible to a person with elevated permissions (in other words, not anonymous users). This is a screenshot of the end result we are trying to achieve:

There are a few things we need to edit in our existing View to achieve this. All of the changes we have to make will be in the Page Settings of our View config screen (See Figure 2). We need to update three things:

  1. Label 7 – Update the Path
  2. Label 8 – Update the Menu
  3. Label 9 – Update the Access Permission

1. Updating the Path: In the Views config screen, update the Path to “admin/content/latest-articles”.

2. Update the Menu: In the Views config screen, update the Menu. Clicking on “No menu” will take you to the Menu item entry config screen. On this screen, choose Menu Tab for Type, enter a Menu link title and set the Parent to “” and then click on Apply.

3. Update the Access: We can do this either by defining the Permission or by defining the role. For this tutorial, we will define the permission. In the Views config screen, click on “View published content” and change it to “Access the content overview page”.

4. Save your View!

Now if you go to “admin/content/latest-articles” as a logged in user, you should see your View page. If you tried going to this same page as an anonymous user you should get Access Denied.

Summary

In this tutorial, we introduced you to Views and some of its potential capabilities by providing some simple customizations. We specifically concentrated on demonstrating how to create a View Page and a View Block which list published Articles and also included a View exposed filter which allows the user to enter a text string to search against the Title. We also touched on how you can create an admin page using Views by updating its path, menu and permissions.

Views, which is in Drupal core as of version 8, is a very powerful tool and can be highly configured and customized. We hope we helped in getting you introduced to Views and the potential it has.

Jun 15 2021
Jun 15
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

Drupal SEO Series using Metatag

When someone tweets a link from your website, Twitter can use Twitter Cards to attach rich photos, videos and media to Tweets.

By doing some minimal configuration changes on your Drupal site using the Metatag Module and the Twitter Cards submodule, users can see a “Card” added below the tweet that contains neatly formatted information coming from your website, as shown in Image 1 below.

Image 1 shows an example of a “Card”.

The cards are generated using HTML markup in the HEAD region of your Drupal site; that’s why the Metatag module is used.

Twitter will scrape your site and generate the card using the HTML meta tags.

Table of Contents

Twitter Cards

There are four variations of Twitter cards. They are:

  1. Summary Card – Displays Title, description, and thumbnail
  2. Summary Card with Large Image – As the name suggests, similar to Summary Card but with a larger image
  3. App Card – A Card with a direct download to a mobile app. Use this Card to drive app downloads
  4. Player Card – Displays video/audio/media.

Image 1 above shows a “Card” of type Summary with Large Image.

In this tutorial, we will look at the steps involved in setting up the “Summary Card with Large Image” Twitter Card.

Getting Started

The Metatag module has a dependency on the Token module. However, if you download and enable the Drupal module using Composer and Drush, the dependency is automatically taken care of as we will show you now.

Use composer to download the module:

composer require drupal/metatag

Once the Metatag module is downloaded using composer, the Token module, which is a dependency, will be downloaded automatically.

Then enable the “Metatag: Twitter Card” submodule:

drush en metatag_twitter_cards -y

The above Drush command will automatically enable the Metatag: Twitter Card submodule, Metatag module and Token module.

Finally, it is always a good idea to clear the cache after enabling Drupal modules:

drush cr

Configure Twitter Cards

By default, Twitter Cards can be added to any content type. We will now configure the Twitter Cards for the Article Content type.

1. Go to Configuration > Metatag (admin/config/search/metatag) and click on “Add default meta tags”.

2. On the next page, select “Article” (or whatever content type you want to configure) from the Type dropdown.

3. Then click on Save. This is required for the correct tokens to appear in the “Browse available tokens” window.

4. Edit the “Content: Article” configuration from the Metatag page.

5. Click on “Twitter cards” to expand the field set and then select “Summary Card with large image” from the Twitter card type dropdown.

6. Now, we have to add tokens into the correct fields. Click “Browse available tokens.” then click on Nodes.

NOTE: If you can’t see “Nodes”, this means you need to save the “default meta tag” option first then edit it again.

Fill in the following fields:

  • Description: [node:summary]
  • Site’s Twitter account: Add your twitter account, i.e., @webwashnet
  • Title: [node:title]
  • Page URL: [node:url]
  • Image URL: [node:field_image] (adjust the field name accordingly)
  • Image alternative text: [node:field_image:alt] (adjust the field name accordingly)

Find Image Field Token

For this type of Twitter card, an image field must exist in your content type. We will show you how to use Token to grab that image data. Click on “Browse available tokens”.

Then drill down by going to Nodes -> Image. This assumes you’re using the Image (field_image) field on the Article content type.

The token should be [node:field_image].

Once you have found the image entity URL, make sure your mouse focus is in the empty Image URL Twitter Card meta tag field, and then click on the image entity URL token value. This will copy/paste the token value into the Image URL field.

Find Image Field Token on Media Asset

If you’re using a media field instead of an image field for handling assets, then use the following token, [node:field_media:entity:thumbnail] (change the field_media name accordingly).

7. Configure any extra fields as needed, then scroll down and click on Save.

8. Once you have filled out the other Twitter Card fields with their respective token values, you should validate the end result markup using the Twitter Card Validator tool. We will now show you how to validate your Twitter card.

As you can see, Twitter successfully recognised our “Summary with large image” card and displayed the information correctly.

NOTE: You’ll need to make sure your website is publicly accessible for the validator tool to work.

View HTML Source

If you want to see the generated markup, view the HTML source on your Drupal site and look for the “twitter:*” meta tags.

Summary

Twitter can display a neatly formatted version of your website’s content whenever someone’s tweets a link to your content. There are various types of Twitter cards depending on your needs.

We have shown how you can use the Metatag module and Twitter Cards submodule to configure Drupal 8 to correctly send your website’s content to Twitter and how to validate your markup to ensure Twitter correctly parses your website content.

FAQ

Q: I changed the default meta tag configuration, but the tags are not changing?

Try clearing the site cache. Go to Configuration > Performance and click on “Clear all caches”.

May 31 2021
May 31
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

Drupal comes with a toolbar which is useful when administering a Drupal site. If you log in and have the correct permissions, you’ll see a toolbar across the top of the page that allows you to access back-end configuration pages.

The Admin Toolbar module extends the functionality of the toolbar and gives you lots of extra features such as drop-down menus, access to cache and cron settings and an autocomplete search.

In this tutorial, you will learn how to install and configure Admin Toolbar and its sub-modules.

Table of Contents

Getting Started

Let’s begin by downloading the Admin Toolbar module.

Run the following Composer command:

composer require drupal/admin_toolbar

Then go to Extend and install Admin Toolbar and its three sub-modules.

Functionality around the toolbar is spread across four modules in total. Here’s a breakdown of what each module does.

Admin Toolbar

Provides an improved drop-down menu interface to the site toolbar.

Admin Toolbar Extra Tools

Adds menu links like Flush cache, Run Cron, Run updates, and Logout under the Drupal icon

Admin Toolbar Links Access Filter

Provides a workaround for the common problem that users with ‘Use the administration pages and help’ permission see menu links they don’t have access permission for. Once the issue https://www.drupal.org/node/296693 be solved, this module will be deprecated.

Admin Toolbar Search

Provides quick search functionality for configuration pages.

Let’s take a look at each module in more detail.

This module is the base module of Admin Toolbar. After installation, it provides drop-down functionality on top of the standard toolbar.

There is a new version 3.0.0 released recently, which requires Drupal 8.8 or above. With this version, a new configuration form was introduced to limit the number of bundles to display in the drop-down menu, resulting in performance issues.

To configure this new mechanism, go to:

Admin > Configuration > User interface > Admin Toolbar Tools

The default value is 20, but can be modified here. Just pay attention to the warning on this page which says ‘Loading a large number of items can cause performance issues.’. We can leave it 20 by default to start with.

This sub-module adds extra drop-down functionality to the base module by providing the following additional functions:

  • Additional menu items are available in the drop-down functionality
  • An extra Drupal logo icon will be attached to the left corner of the Admin Toolbar, which provides additional functions in a convenient manner:
  • Index – provides a list of functions indexed in alphabetical order
  • Flush all caches – flush all caches, or individual caches of the system.
  • Run cron – run a cron job immediately, instead of waiting for the default time period of 3 hours.
  • Run update – run a system update process, generally after system or module updates.
  • Logout – provide fast access to the logout function.

This sub-module offers a workaround for users which have the ‘Use the administration pages and help’ permission but not access to the specific pages. Menu items are still visible even if the user doesn’t have access.

Once https://www.drupal.org/node/296693 is fixed this module will be deprecated.

This sub-module doesn’t require any configuration, just install and you’re done.

An ‘Admin toolbar quick search’ box is provided on the Admin Toolbar. This is useful for beginners, site builders or administrators who are not familiar with Drupal. They can find the functions they are looking for, administrative or configuration pages by searching here.

Summary

Admin Toolbar is a must-have module on any Drupal site. It gives site administrators and builders a better user experience when managing content and configuration.

I especially like the quick search functionality offered by “Admin Toolbar Search”. This makes it easy to search for configuration pages.

May 18 2021
May 18
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

Creating a block using views is pretty straightforward. You could create a block to display a list of published articles or ones that have been promoted to the front page. Then you can add that block into any theme region.

But you may encounter a situation where you no longer have any articles which are published and then you end up with an empty block.

Views comes with a feature that allows you to hide a block if no results are returned and this is what will be covered in this tutorial.

Drupal Views Series

Table of Contents

Getting Started with a Simple Example

We need to display a block that lists all articles that have been promoted to the front page. This can easily be achieved by using a custom views block

The views configuration will look something similar to the following:

This is a block created from views, and we can place the block on the sidebar, like the following:

The criteria of the views setting is based on some articles having the ‘Promoted to front page’ option checked.

The Problem

However, sometimes articles may not be promoted at all.  As a result, there are no results returned from the views setup above, and the block will look like this:

How to Fix It

To avoid this situation, we can choose to Hide the Block when no results are returned.  In fact, there is an option of ‘Hide block if the view output is empty’ at the bottom corner of the views setting, which a lot of people might easily overlook.

Simply enable this option, and it is done.

With this option enabled, the block will disappear when the view returns no results, like the image below:

Summary

This ‘Hide block if the view output is empty’ option is actually one which is very useful, but it can be easily overlooked.

May 12 2021
May 12
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

When someone shares a Facebook post with a link to your website, Facebook lets you control how your website content appears to others by parsing your Open Graph (OG) markup.

By doing some minimal configuration changes on your Drupal site using the Metatag Module and the Metatag: Open Graph sub module, you can define what specific content can be shown on Facebook regardless of whether it’s shared from the desktop or mobile web or a mobile app.

It is easier to explain by showing the end result of what we are trying to accomplish. For example, the homepage of www.webwash.net has the following OG markup inside of the :

If someone posted www.webwash.net to Facebook, then Facebook would parse the OG markup like this:

And the end result would look like this:

You can clearly see the corresponding OG tags for the content.

If you want to learn more about the OG tags. Click here for a detailed list and explanations of the Facebook OG tags.

In this tutorial, we are going to show you how to configure a content type to dynamically populate the Facebook OG tags using the Metagtag module and Metatag Open Graph sub module.

Table of Contents

Getting Started

The Metatag module has a dependency on the Token module. However, if you download and enable the Drupal module using composer and drush, the dependency is automatically taken care of as we will show you now.

Use Composer to download the module:

composer require drupal/metatag

Once the Metatag module is downloaded using composer, the Token module, which is a dependency, will be downloaded automatically.

Then enable the “Metatag: Open Graph” sub module:

drush en metatag_open_graph -y

The above drush command will automatically enable the Metatag: Open Graph sub module, Metatag module and Token module.

Finally, it is always a good idea to clear the cache after enabling Drupal modules:

drush cr

By default, Open Graph can be added to any content type. We will now configure Open Graph for the Article Content type.

1. Go to Configuration > Search and meta data > Metatag and click on “Add default meta tags”.

2. On the next page, select “Article” (or whatever content type you want to configure)  from the Type dropdown.

3. Then click on Save. This is required for the correct tokens to appear in the “Browse available tokens” window.

4. Edit the “Content: Article” configuration from the Metatag page.

5. Then in the Open Graph fieldset on the same page, click to expand it. You will now notice quite an exhaustive list of OG tags that you can populate. Firstly, we are going to demonstrate how to populate the Image OG tag.

For this to be successful, your Article content must have at least an image field. We will show you how to use Token to grab that image data.

Click on “Browse available tokens”.

From the Token window click on Nodes to drill down and find the content type fields.

NOTE: If you can’t see “Nodes”, this means you need to save the “default meta tag” option first then edit it again.

Fill in the following fields:

  • Content type: article
  • Page URL: [node:url]
  • Title: [node:title]
  • Description: [node:summary]
  • Image URL: [node:field_image] (adjust the field name accordingly)

Find Image Field Token

To use an image stored in an image field, click on “Browse available tokens”.

Then drill down by going to Nodes -> Image. This assumes you’re using the Image (field_image) field on the Article content type.

The token should be [node:field_image].

Find Image Field Token on Media Asset

If you’re using a media field instead of an image field for handling assets, then use the following token, [node:field_media:entity:thumbnail] (change the field_media name accordingly).

6.After you fill out all of your OG tags fields, click on Save and clear the Drupal cache. If you do not clear your cache, the OG fields may not populate for existing content.

7. Once you have filled out the other OG fields with their respective token values, you should validate the resulting OG markup using the Facebook Sharing Debugger tool. We will now show you how to validate your OG markup.

NOTE: Your website has to be publicly accessible for the debug tool to work.

8. First we need to create a test Article node (make sure to upload an image to our image field). Our test article looks like this:

9. Paste the url for this node into the Facebook Sharing Debugger tool. The output should look like:

As you can see, Facebook successfully parsed our OG markup and displayed the information correctly.

Summary

Facebook lets you control your website’s content whenever someone’s shares a link to your content regardless of whether it’s shared from the desktop or mobile web or a mobile app. Facebook does this by parsing the Open Graph (OG) markup provided by your website. We have shown how you can use the Metatag module and Metatag Open Graph sub module to configure Drupal 8 to correctly generate the OG markup needed by Facebook and we have also shown how to validate your OG markup to ensure Facebook correctly parses your website content.

FAQ

Q: I changed the default meta tag configuration, but the tags are not changing?
Try clearing the site cache. Go to Configuration > Performance and click on “Clear all caches”.

Apr 27 2021
Apr 27
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

File Management Series

Removing files from Drupal is more tricky than you might think. There has been another tutorial about this using the module File Delete.  It requires going through a cycle of minimum 6 hours.  By default, Drupal protects files from removal which are still being used and referenced in other content. Instead of directly deleting a file, the linked usages need to be cleared first, and the files marked as temporary, then finally the system will remove them during cleanup.

This is actually a good policy. However, sometimes it’s annoying to wait for a few hours before these files are being cleaned up. In particular, if we are sure these files are unused or orphaned, there is another module called Fancy File Delete, which solves this problem.

Fancy File Delete allows you to delete files straight away without having to wait.

However, great care must be taken when using this module, because it has a ‘force delete’ option. Use of this module should be restricted to experienced administrators.

Table of Contents

Getting Started

Before we begin, go download and install Fancy File Delete.

Using the following Drush commands:

composer require drupal/fancy_file_delete

NOTE: The module requires the Views Bulk Operations (VBO) module which will be downloaded when you run the above command.

Deleting Files

To follow a proper procedure to delete files, administrators should still go through the proper file handling process by removing them from the nodes and the media library first, even though these processes can be bypassed using this module.

After installing and enabling the modules, go to Admin >> Configuration >>  Content authoring >> Fancy File Delete. In the first tab ‘Info’, it shows a brief description on how to use the module.

Enter the ‘List’ tab, a list of all the files in the system can be found from here.  Select the file(s) to be deleted using the checkbox in front of each file, then select ‘Delete Files’ in the ‘Action’ option on the top of the page, then click the ‘Apply to selected items’ button.

Note that there is another option for Action, which is ‘FORCE Delete Files (No Turning Back!)’.  When a file cannot be deleted, try this option but handle with care.

Can’t See Action Drop-Down

If you can’t see the Action drop-down on the list page that means you’ll need to reconfigure the view.

1. Edit the List view by clicking on the pencil icon.

2. Once you’re editing the view, click on the “Views bulk operations” field.

3. Enable the actions by clicking “Select all”.

Then save the view and you should see the Action drop-down.

Delete Files manually by FID

As can be seen above, there is a File ID for each file.  Files can be deleted using this FID by entering them under the ‘Manual’ tab. Just enter the FIDs of the files to be deleted, one per line, and press the ‘Engage’ button.

Deleting Orphaned and Unmanaged Files

Additional options are available to delete orphaned and unmanaged files if the system detects them.

Deleting Files from the ‘Files’ or ‘Image’ Fields

Note that in the above procedure using ‘Fancy File Delete’ module, it is not a requirement to remove them from the nodes first:

  • It bypasses the default file delete procedure in Drupal, and therefore it should be handled with care.
  • Files deleted will also be removed from previous node revisions too.
  • Files deleted will also be removed from the list of files under Admin >> Content >> Files
  • Files deleted are permanently removed totally from the system, including the physical file in the server.
  • It does not require waiting for the minimum 6 hours requirement.

When the files are uploaded through the media module and deleted without first removing them from the nodes and the media library first, this ‘Fancy File Delete’ module still remove the files same as above, except the following:

  • Files deleted will still be removed both physically from the server and from the list of files under Admin >> Content >> Files, like above.
  • The file will not be shown in node because it is empty, but an empty entity will remain both in the node and in the media library.

Using Drush

If you use Drush, you can delete files straight away using the “drush entity:delete” command.

For example:

drush entity:delete file 1

This command will remove the file from the Files page and delete it from the file system and you won’t have to wait.

Summary

This module offers a more straightforward and efficient way to remove files from a Drupal site permanently. It is powerful and capable of bypassing the default file handling procedures in Drupal. But that also means bypassing the file protection mechanism of Drupal. It handles file deletion in an efficient manner which is an advantage, but it is also a disadvantage at the same time.

On a large site where there are more users and content authors. When deleting files are granted to more people, it is difficult to guarantee that everybody is careful enough to understand the underlying structure and relationships between files and content. There is a higher risk of accidental deletion of files. In such situations, a better protection mechanism might be necessary.

On a small site or in a small team where content is easier to manage and control, efficiency might be preferred.

Apr 15 2021
Apr 15
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

File Management Series

In Drupal, files can be uploaded to the site for users to view or download. This can be easily achieved by creating a file or image field on content types.

In the back end, a list of all the files uploaded can be viewed by the administrator, by going to Administration > Content > Files (admin/content/files).

Files uploaded can be easily removed from the individual content pages (see the image below), but removing them entirely from the system is another story. You might be surprised that you cannot find a button, a link or an option to remove these deleted files entirely from the system.

After deleting files on content, if you go to the Files (admin/content/files) page, you will find the deleted files are still there, and the status still shows ‘Permanent’, even though they are already removed from the nodes. It seems very confusing. Removing files from content and removing files from the system are two different things in Drupal.

To remove files from the system, we need to add the file delete function. This can be achieved by installing the File Delete module.

Table of Contents

Getting Started

The File Delete module adds the ability to delete files from within the administration menu.

To download the module run the following Composer command:

composer require drupal/file_delete

How to Configure

After installing the module, we need to add a ‘Delete link’ to the Files page.  We can do that by going to Administration > Structure > Views and edit the views of the Files list. By default, the name of the views is ‘Files’:

To add the ‘Delete link’, we need to add a field called ‘Link to delete File’ in this views, which appears like the following image:

Select this field.  We can keep everything by default, and then click ‘apply’ and save the views.  Next, go to Administration > Content > Files, and there we shall see the ‘delete’ link there, like the following:

How to Use

With this ‘delete link’, we can remove the delete files from the system by clicking on the ‘delete link’ shown in the above diagram. Note that Drupal will protect all the files, and will not allow files to be deleted when they are being used in any content.  If you try to delete a file which is still being used in a node, you will see this following error message.

The Tricky Part

In some cases, even if you have deleted the files from the nodes, and the files are no longer visible in the nodes, you might still find this error message disallowing you to remove the file from the system.

But that might be correct because these files might still be used in content. The nodes where these files came from might have more than one revision. These files removed from the current revision might still be attached to the previous revisions.

When this happens, check out the nodes again for multiple revisions, like the following example:

Only when all attachments (including the old revisions) are cleared, then these files can really be removed from the system. So in summary, when we delete the files, we need to make sure that these files are not being used in any content, including the old revisions.

The File Status

Even though you can successful remove deleted files from the system using the ‘Delete link”, you will still find the following:

  • The file is still on the list
  • The status of the file is changed from ‘Permanent’ to ‘Temporary’
  • The file is used in 0 places (that means it is not used with any nodes)

Following is an example how it will look like:

But why do these deleted files showing ‘temporarily’ status still appear in the list?  Here is why …

In fact, the files removal process has already been initiated. Drupal will delete the file in the following sequence:

  1. Change the status from ‘Permanent’ to ‘Temporary’
  2. Wait for a minimum of 6 hours
  3. Upon the next cron-run after 6 hours, the system will really remove these temporary files

That is why you still see these deleted files in the list within this 6-hour period.  This is how Drupal manages temporary files.

Temporary File Management

If you go to Administration > Configuration > Media > File system, you will find a configuration and explanation at the bottom of the page:

Here it says temporary files will be deleted in the next cron run after 6 hours. Note that 6 hours is the minimum. This ‘6 hours’ setting can be changed, but 6 hours is already the minimum.  See the following options for the configuration:

With the ‘Media’ module, files can also be added as media documents instead of a ‘File’ field.  These files added as media documents can also be deleted, but it will be a little bit different in the operation. Again, the system will not allow deleting files that are still being used.

To delete such files added as media entities, pay attention to the following:

  1. Confirm that the media is not being used on the site first.
  2. Go to Administration > Content > Media to the list of media entities, and delete the designated items here first.
  3. Next go to Administration > Content > Files, and then delete the designated files here.

It will go through the 6-hour cycle described above, but we should leave it to the system to handle it from here.

The Files list is within the administration area, accessible by the administrator. But if other users will require access to this area to delete the files, user permissions need to be configured specifically to this module.

Using Drush

If you use Drush, you can delete files straight away using the “drush entity:delete” command.

For example:

drush entity:delete file ID

This command will remove the file from the Files page and delete it from the file system and you won’t have to wait.

Summary

The file delete procedure in Drupal is not that user-friendly. The module provides the ability to delete files in Drupal.  The procedure for deleting files is a little bit complicated, due to the fact that files can be used therefore associated with different entities in the system.  Also, for this reason, it is suggested that file delete be handled by an experienced administrator with the right permission and access to the administration area.

Mar 23 2021
Mar 23
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

File Management Series

Drupal doesn’t support the ability to replace existing files. You can create and delete files, but you can’t replace a file without using a module. If you try to upload a file with the same name Drupal will append “_0”, “_1”, etc… to the filename and increment it.

Luckily two modules can help with replacing files, and they’re called Media Entity File Replace and File Replace.

What is the main difference between Media Entity File Replace and File Replace?

Both modules will replace “files” whilst retaining the original file’s filename by performing an “overwrite” function in the backend. In Drupal, an uploaded “file” can be a “media entity” or a “file entity”.

As the module names suggest, the main difference is that Media Entity File Replace works at the media entity level, whereas File Replace works at the file entity level.

Table of Contents

This module allows editors to replace files at the media entity level by overwriting the existing media files. Because it overwrites the files, the filename and path are exactly retained.

You should use this module to allow content editors to replace media entity files whilst keeping the same filename and path as the original file.

Getting Started

1. Download and enable the module. This module requires no additional libraries and can simply be installed with composer which is the recommended way.

To install using Composer:

composer require drupal/media_entity_file_replace

If you get the following error when using Composer:

  [InvalidArgumentException]
  Could not find a version of package drupal/media_entity_file_replace matching your minimum-stability (stable). Require it with an explicit version constraint allowing its desired stability.

Then specify the version:

composer require drupal/media_entity_file_replace:^1.0-beta3

To enable the module using Drush:

drush en media_entity_file_replace

2. Clear the cache. You can easily clear the cache via the Drupal admin UI at admin/config/development/performance or by the drush command:

drush cr

A quick overview of this step is adding a media field to an existing content type and uploading an actual media document. If you already have a media field in your content type and an uploaded media file then you can skip to step 3.

A. For any content type (we will use the default Drupal Article content type in this tutorial), add a Media field and check “Document” as the Reference type. See Image 1 below.
B. Go to Content >> Media and click on “Add Media”. At the next page, select “Document” and proceed to upload a file. Note the filename.

Image 1 – Enable “Document” reference type for the newly created Media field in the Article content type

3. Now enable the “Replace file” widget that comes from the Media Entity File Replace module.

Go to Structure >> Media Types >> Document >> Manage Form Display and enable the “Replace file” widget. This widget is disabled by default. See Image 2 below. You will not be able to replace a file until you enable this widget.

It’s a good idea to position the “Replace file” widget right under the file widget as shown in Image 2 so that when a user is editing a file, the “Replace file” widget is right under the file that they want to replace.

Image 2 –  Enable the “Replace file” widget in the Document media type found under “Manage Form Display”.

Without this module and widget enabled, the default Drupal interface will appear as in Image 3.

Image 3 – The default Drupal 8 interface to replace a media file.

4. Now if you go to Content >> Media and edit the document media that we uploaded in Step 2.B, you will see the “Replace file” widget as shown in Image 4 below. Notice that the default Drupal widget is automatically removed (see the difference between Image 3 and Image 4).

Image 4 – The “Replace file” widget coming from the Media Entity File Replace module

5. Go ahead and replace the original uploaded file with a new file with a different filename. Upon replacing the file, if you left the default option “Overwrite original file” checked, then Drupal will upload the new file and set the old file for deletion. Even if your new file has a new file name, Drupal will store the new file whilst retaining the filename of the original file. Note that the filename is the same as that noted from Step 2.B.

If you click on the new uploaded file even after doing a refresh in the browser, you may still see the old content of the original file. You must do a hard refresh in your browser to see the contents of the newly uploaded file.

More information: How to do a hard refresh in Chrome, Firefox and IE.

File Replace

This module allows editors to replace files at the file entity level by overwriting the existing files. Because it overwrites the files, the filename and path are exactly retained.

You should use this module if you want to allow content editors to replace file entities whilst keeping exactly the same filename and path as the original file. It is useful in cases where existing files in Drupal need to be updated occasionally.

Getting Started

1. Download and enable the module. This module requires no additional libraries and can simply be installed with composer which is the recommended way.

Using Composer:

composer require drupal/file_replace

To enable the module using Drush:

drush en file_replace

2. Clear the cache. You can easily clear the cache via the Drupal admin UI at admin/config/development/performance or by the drush command:

drush cr

3. There is one extra manual step that you must do. Because this module only provides the “Replace page” for each file upload, it does not provide a link to this page from the Drupal UI. You can access the “Replace page” directly by typing the URL into the browser. You can manually type the following URL into the browser:

admin/content/files/replace/{{ fid }}

Where {{ fid }} is the file id of the file you want to replace. For example, if the fid was 6, then you would go to:

admin/content/files/replace/6

This is not ideal. We will show you how to link to the page from the default Drupal Files overview page. (The outcome we are trying to achieve is shown in Image 11.)

Go to Content >> Files and click on “Edit view” as shown in Image 5.

Image 5 – On the Files overview page, click on the Edit icon to the top right to edit the View.

Alternatively, you can go to Structure >> Views and edit the Files view as shown in Image 6.

Image 6 – Editing the Files view found on the View listing page.

4. Add a Custom text field to the Files View as shown in Image 7.

Image 7 – Adding a Custom text field to the Files view.

5. Then add some custom text for the text of the link. See Image 8

Image 8 – Adding custom text for the link anchor text

Also, edit the “Rewrite Results” section and enter the following in the “Link path”:

admin/content/files/replace/{{ fid }}

You can also enter custom text in the “Title text” field although this is just for aesthetic purposes. See Image 9 below.

Image 9 – Rewriting the results of the link to include a relative path.

Now click on “Apply (all displays)” and save your View.

6. The last step is to enable the “Replace files” permission for the role that you want. See Image 10.

Image 10 – Enable the permission “Replace files” for your role.

7. Now go to the Files overview page at Content >> Files and you will see a “replace” link as shown in Image 11.

Image 11 – Showing the custom “replace” link created from editing the Files view

Click on the “replace” link next to the file you want to replace and this will take you to another page where you can upload a new file as shown in Image 12.

Image 12 – The “Replace file” page provided by the File Replace  module.

Common Pitfall – Caching

Static files served by Drupal are usually cached externally (outside of Drupal) by services such as Varnish, Content Delivery Network (CDN) and the user’s browser. By default, a user’s browser will not pick up the content of the newly uploaded file until after the max-age header which is set in .htaccess for two weeks for static files. In other words, if you replace a file and do nothing, end users will see the new file content after two weeks (unless they locally do a hard refresh).

Clearing Drupal’s internal cache will not solve this caching caveat because Drupal is not involved with serving static files. This is the job of your webserver.

There are a few options worth mentioning:

Summary

Drupal does not retain filenames for uploaded files that are replaced or overwritten. Additionally, Drupal stores uploaded files as either media entities or file entities depending on your set up. This tutorial demonstrated how to retain existing file names when replacing media or file entities. There are two contributed modules you can use to solve this problem and they are Media Entity File Replace and File Replace. These modules will allow you to overwrite existing media and files respectively, whilst keeping their original filenames.

Mar 02 2021
Mar 02
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

The “Long text and summary” field has a formatter called “Summary or trimmed”. This formatter allows you to trim text to a specified set length which is important if you’re displaying a list of articles. The last thing you want is to have an article display 1000 words on the homepage.

However, this default “Summary or trimmed” formatter cannot trim the summary. If the author enters in lots of text into the summary it’ll display everything.

The Smart Trim module offers a field formatter for trimming text fields. Additional settings are available more than the default “Summary or trimmed” option – an improvement over the default formatter.

Smart Trim can also apply to Text (Plain) and Text (Plain, Long) fields which, by default, do not have the “Trimmed” option available.

Table of Contents

Getting Started

Before we can begin, go download the Smart Trim module.

Using Composer:

Composer require drupal/smart_trim

Once downloaded go and install the module.

How to Use Smart Trimmed Formatter

1. Go to Structure > “Content types” and click on the “Manage display” on a content type row.

2. Under the “Format” of text fields, an option of “Smart trimmed” will be available.  Select this option.

3. After the “Smart trimmed” option is selected, click on the cogwheel on the right.  More configuration settings are available. (The Summary option is not available for text fields without summary.)

4. Configure the settings accordingly, then click Update and save.

Format Settings

Trim units

Trimming of text can be applied to characters or words. This takes care of word-boundary issues on trimming.

Suffix

Suffix can be appended to the trimmed text, such as “…”.

Display more link?

When enabled, a link of “More” will be added to the bottom of the page. This will allow the user an option to view the entire page.

Summary

This option is only available when using the “Text (formatted, long, with summary)” field. Three options are available:

  • Use summary if present, and do not trim
  • Use summary if present, and honor trim settings
  • Do not use summary

These options allow overriding of the summary.

Strip HTML

This option will Strip out any HTML when displayed. This is important if you’re truncating text because you could display an opening HTML tag but not close which could break the site styling.

Summary

The Smart Trim module provides a more powerful trimming formatter than what is offered out-of-the-box. Best of all, it can be used on any type of text field.

FAQ

Q:  Can I use this module for all text fields?

Yes, it can be applied to all default text fields, plain or formatted, short or long.

Editorial Team

About Editorial Team

Web development experts producing the best tutorials on the web. Want to join our team? Get paid to write tutorials.

Feb 22 2021
Feb 22
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

This tutorial will demonstrate how to use the Custom Permissions module.

By default in Drupal, user permissions in the Drupal backend are not very granular.

For example, if you want to give a role the ability to edit only the “Basic site settings” in the Drupal admin UI. In Drupal, this can be achieved by giving the access permissions “administer site configuration”. However, with this permission enabled, the role will also have the ability to edit other site settings which you may not want a user to have access to.

Enter the Custom Permissions module.

With this module, you could solve the above problem by creating an extra custom permission to edit only the “Basic site settings” page without assigning the “administer site configuration”.

This light-weight module will allow you to specify the exact admin route (or path) that you want to give permissions to without giving the role access to everything in the administration section.

In this tutorial, you’ll learn how to create a custom permission which will only have access to the “Basic site settings” page. We’ll be using the 8.x-2.x version of the module.

Table of Contents

Difference between 1.x and 2.x?

Both versions accomplish the same functionality, but the difference is that when specifying the page you want to give access to, version 8.x-2.x uses routes and version 8.x-1.x uses paths.

Diagram 1 – Version 8.x-1.x using paths Diagram 2 – Version 8.x-2.x using routes

How to Find out the Route Name

A route in Drupal is a path which is defined for Drupal to return some sort of content on. Routes are defined in a module’s MODULE_NAME.routing.yml file. There can be routes defined in contributed, custom or Drupal core modules.

For Drupal core routes (paths in the Drupal core admin UI), you would want to text-search for the path in: web/core/modules/system/system.routing.yml

For contributed or custom routes, search in the relevant modules’s “.routing.yml” file.

In our example, the block of code in system.routing.yml for our path “admin/config/system/site-information” is:

system.site_information_settings:
   path: '/admin/config/system/site-information'
   defaults:
     _form: '\Drupal\system\Form\SiteInformationForm'
     _title: 'Basic site settings'
   requirements:
     _permission: 'administer site configuration'

The route name is bolded above to show you what the route name will be. The exact route name is: system.site_information_settings.

Using Devel

If you prefer not to search through code to find the route name, look at using the Devel module. Devel comes with a Routes Info page which lists all the active routes and its paths, and you can filter the page. This makes it easy to find the correct route.

Once the module is installed click on the Devel link in the toolbar then “Routes Info”.

On the “Routes Info” page you’ll see a long list of routes and its paths.

Getting Started

This module requires no additional libraries and can simply be downloaded with Composer.

Using Composer:

composer require drupal/config_perms

Installing the module with above composer command will install version 8.x-2.x of the module.

Once downloaded go and install the module.

How to create a Custom Permission

In this tutorial, we are going to create a custom permission to allow a role to access and update only the “Basic site settings” page in the Drupal admin UI.

1. Once the module is installed, go to People > Custom permissions.

You’ll notice that the module comes with four default custom permissions.

2. Click on the “Add permission” button, and you will get an additional row to add a new permission.

3. Give your new permission an admin human-readable name and click on “Save”. Note that this name is only visible to the site admin. The route that we want to use for the “Basic site settings” is “system.site_information_settings”.

4. Go to People > Roles and edit the permissions of the role that you want to assign this new custom permission too. We will use the “Authenticated user” role in this example.

5. Scroll to “Custom Permissions” and you will see the new custom permission human-readable name you created in Step 3. Enable it.

6. For the new role to access the administration pages in Drupal, you also have to enable “Use the administration pages and help”. You can also enable “Use the toolbar” so the user can see the enabled permission in the admin toolbar although this is just for convenience and not a requirement for this tutorial.

7. Now, the user with the role “Authenticated user” will have access to the following permission as shown below:

Summary

Drupal, by default, may not always define granular permissions to certain administrative pages. Typically, a role can be given all or no access to administrative pages.

Using the contributed module Custom Permissions (version 8.x-2.x) you can define custom permissions for specific Drupal admin pages. This module provides finer granular permissions for specific Drupal routes/paths.

Editorial Team

About Editorial Team

Web development experts producing the best tutorials on the web. Want to join our team? Get paid to write tutorials.

Jan 13 2021
Jan 13
[embedded content]

Don’t forget to subscribe to our YouTube channel to stay up-to-date.

The roles and permissions system in Drupal is powerful, but it can be tricky to configure correctly. Some permissions give a role too much privileged access where others aren’t granular enough.

An excellent example of this is if you need to create a role to manage user accounts.

Drupal comes with the permission “Administer users” which lets you create user accounts, only give this permission to trusted users.

The above mention permission allows you to create user accounts but you can’t assign them roles without “Administer roles and permissions”. But this permission (“Administer roles and permissions”), will enable you to assign any roles, including the default Administrator role.

From this:

To this:

In some circumstances, you don’t want users who can create user accounts to have the ability to assign any roles, especially the Administrator role.

What if you want to control exactly which roles can be assigned? This is where Role Delegation can help.

Table of Contents

Getting Started

To get started, download and install Role Delegation.

composer require drupal/role_delegation

Using Role Delegation

All the module does is offer granular permissions for assigning roles.

Once the module is installed, go to People > Permissions and search for the Role Delegation section.

You’ll notice that you get a specific permission for each role, and you also get the “Assign all roles” for absolute power.

All you need to do is give one of the “Assign {role} role” permission and they’ll be able to assign users into that role.

Assign Role

Once a role has been assigned a few “Role Delegation” permissions, they can assign roles in two ways.

First, if you edit an account you should see the Roles checkbox below Status.

The module adds a new tab on user accounts called Roles. This page has all the allowed roles as checkboxes.

Select a role and click on Save to assign them.

Summary

The functionality that Role Delegation offers should be in Drupal core in my opinion. If you need to control which roles can be assigned then it’s a useful module to add to your Drupal site building toolbox.

FAQ

Q: I can’t see the “Administer roles and permissions” permission on my site?

It was changed from “Administer permissions” to “Administer roles and permissions” in Drupal 9.1.

Ivan Zugec

About Ivan Zugec

Ivan is the founder of WebWash and spends most of his time consulting and writing about Drupal. He's been working with Drupal for 12 years and has successfully completed several large Drupal projects in Australia.

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