Magento 2 How To Create And Apply A Custom Patch

Creating Patches In Magento 2:
If you want to create a patch in Magento 2, you need to follow some given steps so you can create your custom patch in a easy way.
We are considering that you installed Magento using composer and you are using git as a repository.
Now, consider there is a file on path "vendor/magento/module-catalog/Block/Navigation.php"

1) cd vendor/magento/module-catalog/Block // Go to the vendor module file path
2) git init . // Initialize git file
3) git add -A . // Add all the files in the current directory using Dot(.)
3) git add -A Navigation.php // If you want to add only few files or one file, you just need to add them manually given in command instead of dot(.)
4) git commit -m "Adding files to create difference"

Now add your changes to the vendor/magento/module-catalog/Block/Navigation.php file and then follow below steps:
5) git add -A . // Add you changes with single file or multiple files
6) git commit -m " This commit shows your changes available in the patch"
7) git format-patch -1 HEAD // This is the final command to create patch file
8) Rename the new patch you created as per your requirement
9) rm -rf .git // Remove temporary git repo from the current directory
Consider we have renamed patch to "TEST_CATALOG_NAVIGATION_ISSUE.patch".

Applying Patches In Magento 2:
You need to follow the given steps to apply a patch to your Magento website:
1) Create a "patches" directory, if it does not exist, in the root of your Magento installation.
2) Move the custom patch you created to the patches/ directory.
3) You need to install the composer patches package if it is not there in your Magento setup:
composer require cweagans/composer-patches
4) Now open the "composer.json" file at the root of your Magento installation and edit the existing "extra" object to look like the below code snippet given where you need to specify the composer package to apply the patch to as well as a description of the patch and a reference to the file location:

"extra": {
    "magento-force": "override",
    "composer-exit-on-patch-failure": true,
    "patches": {
        "magento/module-catalog": {
            "test-patch-description-here": "patches/TEST_CATALOG_NAVIGATION_ISSUE.patch"
5) Run "composer install" to apply the patch 6) Next you need to run "composer update magento/module-catalog" to update the composer.lock file which is used to track which patches have been applied to each composer package in an "extra > patches_applied" object. 7) Add the composer.json, composer.lock and the newly added patches/* patch file to your git version control, and commit and then push the changes.

Now, whenever you deploy your Magento application to development, staging, release, pre-production or production environments, this patch will be applied whenever "composer install" will run.

Hope this helps you guys!

Leave a Reply