How to apply Patch for Drupal core or Drupal Module

Example of patch, for module Token (token-insert-textfocus-3423115-1.patch)
Example of patch, for module Token (token-insert-textfocus-3423115-1.patch)

 

Introduction

Drupal is a powerful and flexible content management system, but sometimes, you may need to apply patches to fix bugs, issues, security edits or modify existing functionality. Patching Drupal core or contributed modules ensures your site remains up-to-date without waiting for official releases. In this guide, we’ll walk you through the process of applying a patch correctly, using several methods.

In this tutorial, we will try to patch Drupal Token module (token), with patch taken from issues section from drupal.org (file: token-insert-textfocus-3423115-1.patch

This can be done for all Drupal versions (7,8,9,10,11) 

 

What is a patch?

A patch is a change in code that primarily fixes, improves, or add new features to the code of a module or application it self.

 

Where to get a patch?

Answer to this question can be simple, you can find patches to modules at the module download page, help pages, or module issues lists, can be found in news feeds. We can make our own patch file, that fix particular problem or extend modules feature.

For this example, the patch is downloaded from Token module download page. And we will try to path Token module.

 

Solution 1

This first approach is consist of using Git command (Git is open source revision control system) to apply selected patch, this command need to be executed inside the folder, where our files that need to be patched are located.

Apply Patch to code, using Git command ( git apply [<patch>...] )
git apply token-insert-textfocus-3423115-1.patch

# also possible to get details on patch
git apply --stat token-insert-textfocus-3423115-1.patch

# verify patch
git apply --check token-insert-textfocus-3423115-1.patch

In command line (Ubuntu 22.04)
We have used command git apply to add patch code to code of the module file (js/token.js)
token-insert-textfocus-3423115-1.patch - patch file downloaded from Token module repository 
 

 

Solution 2

In this approach, we will use Patch command (in most cases installed by default in Linux type systems) to apply a patch, this command also need to be executed inside the folder, where files that are located and patch.

Apply Patch to code, using Patch command ( patch [filetopatch] [patchfile] )
patch js/token.js token-insert-textfocus-3423115-1.patch

In command line (Ubuntu 22.04)
We have used command patch to add patch code to code of the module file (js/token.js)
token-insert-textfocus-3423115-1.patch - patch file downloaded from Token module repository 

 

Conclusion

Applying patches in Drupals using GIT or Patch commands is a straightforward process when done correctly. Always remember to monitor official updates, as patches may become obsolete with new module or core releases.