Drupal Debug: Effective Techniques And Tools
Today, we will discuss how to do Drupal Debug. This means getting the tools and methods to turn complex issues into workable solutions.
Debugging tools can give you more information about your application's status and context while performing different tasks. You usually need Drupal debug tools for two main reasons: either your site or a specific feature isn't working correctly, or you want to learn how a certain feature works.
Understanding what to search for and where to begin takes practice and a systematic method. As you get used to Drupal debug will speed up and become simpler because you'll identify common issues and know how to fix them.
In this blog, we will discuss effective tools and Drupal debug techniques, including the Devel module, Twig debugging, Backtrace, and more.
Before moving forward, take a look at our services if you are thinking about moving to Drupal 10.
Now, let’s begin!
Drupal Debug: Backtrace
Debugging PHP problems on a Drupal site can range from simple fixes to major challenges. PHP has a debugging tool named debug_backtrace, which shows the sequence of code that occurs before the backtrace function is used.
Imagine - When you open a page, you might come across an error message that appears like this:
warning: Invalid argument supplied for foreach() in /modules/field/field.module on line 966.
Drupal debug bactrace is tough to understand the issue from the error message alone. One way to find out what is causing the error is to add Drupal debug code to the relevant file in Drupal.
-
Open the file you need in your doc root. In the example given, it's
/modules/field/field.module
2. Go to the line number mentioned in the error message.
3. At the top of the function, add this code:
Note: This may cause your website to break. Only do this in a development or staging environment.
var_dump(debug_backtrace()); die ();
This shows all the PHP functions and their arguments that called the current function. Typically, the technical details in the Drupal debug backtrace will help you identify which module or function is causing the error.
Also Check Out:
1. Creating your own Twig Extension in Drupal
2. Configuring XDebug on your Server
3. Drupal 11 Upgrade: Checklist For Drupal 7 to 11 Migration
4. Key Modules to Start with Drupal 9 Website
Drupal Debug: Twig
Drupal Twig debug is a modern, quick, and safe template framework that assists developers in creating new templates and managing existing ones efficiently. There are many differences between PHP templates and Twig. Drupal Twig debug features its own syntax and coding rules.
Drupal enable Twig debug in D10 and D11 is easy. It allows developers to find template names and theme suggestions quickly, which helps in creating new template naming systems. Every Drupal 9 site has a default.services.yml file found in the sites/default folder.
Process to Turn on Drupal Twig Debug in Drupal 9:
There are several ways to turn on Drupal Twig debug theme. This is the easiest method. Just follow these steps one by one to Drupal enable twig debug template by editing services.yml.
-
Go to the /sites/default folder
-
Duplicate the default.services.yml file and change its name to services.yml.
-
Open the services.yml file and find 'twig.config'.
-
Turn on debug mode.
(Note: Set auto_reload to true and cache to false are optional settings.)
5. Go to the /sites folder.
-
Edit the development.services.yml file and include this code.
parameters:
twig.config:
debug:
true auto_reload: true
cache: false
7. Make a copy of the example.settings.local.php file and change its name to settings.local.php.
8. Remove the comment from the next line of code.
$settings['cache']['bins']['render'] = 'cache.backend.null';
9. Open the settings.php file and look for the following code section.
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) { include $app_root . '/' . $site_path . '/settings.local.php';
}
10. Add it to the end of the file.
11. Empty the caches and you're done.
Examine your browser's inspector to view all the available template suggestions in the code and identify which templates are currently in use.
Turning on Drupal Twig Debug Using Drupal Console
If you are using the Drupal console, you can do all of this with one command: drupal site:mode dev
Just make sure to switch back to production settings before uploading your site. Run drupal site:mode prod before you upload it to the server.
Process to Turn on Drupal Twig Debug in Drupal 10:
Path --> admin/config/development/settings
Drupal Debug: Devel Module
The Devel Drupal debug module offers a unique way to Drupal debug compared to traditional tools like Xdebug. Instead of showing results right away, it saves the details of variables, including their nested properties and methods, into a lasting log. This log acts like the watchdog module, keeping a constant record of debugging data.
The module uses the Devel module for clear Drupal debug output and works with other modules to provide a complete look at class structures and methods, improving the debugging process.
Devel Drupal debug module is a well-known developer module that offers many tools for development and debugging, making common tasks easier.
Devel Generate is a tool that creates sample content for Drupal sites. This includes menu items, taxonomy terms, and nodes. It is helpful for testing or showing off your Drupal website with fake users, content, images, and more. The Devel module for Drupal can easily generate all of this content for you.
The table shows how different versions of the Devel Drupal debug module work with specific versions of the Drupal core.
Version Compatibility | |
---|---|
Devel Version | Drupal Core |
5.2+ | 10 |
5.0,5.1 | 9,10 |
4.x | 8.9+,9 |
8.x-2.x | 8.x |
Keep in mind that Devel Drupal debug module and its submodules are meant for local development and should not be used on live production websites.
How to use Devel for Easy Debugging?
Devel Drupal debug module provides various tools for easy Drupal debug, with dpm() being the most popular function.
dpm($variable): Displays a variable on the screen for review.
Here is a simple process to fix your code with Devel Drupal debug module:
Step 1: Find the Problem
Locate the part of your code that you think has an issue. Clearly state what you want the code to achieve and what it is currently doing.
Step 2: Use dpm() to Check Variables
Insert the dpm() function in your code at the point where you want to check a variable's value. For instance:
$node = Node::load(1);
dpm($node);
Executing this command will display the contents of the $node variable on the page, allowing you to review its properties and values.
Step 3: Check Queries with dpq()
$query = \Drupal::database()->select('node', 'n')
->fields('n', ['title']);
dpm($query);
Step 4: Review the Results
After you receive the output from dpm() check the actual values against the expected ones. If any results that don't match what you expected, there is likely an error in your code.
Step 5: Improve your Code
Use the information you collected to adjust your code logic. Keep refining until all problems are fixed. This means there should be no errors, and the actual results should match the expected ones.
By following these steps and using dpm() you can find and fix issues in your Drupal code.
Drupal Debug: Xdebug
Using Xdebug for profiling and tracing is an advanced method that greatly improves Drupal development processes.
Xdebug is a strong and flexible debugging tool for PHP. It gives developers important information about how their applications perform, helping them find slow parts, improve code speed, and enhance overall efficiency.
Profiling with Xdebug means carefully looking at how long different functions take to run and how many resources they use in a Drupal application. By creating detailed reports, developers can see exactly how each function affects performance, helping them focus on the most important areas for improvement.
Xdebug records a detailed timeline of function calls, showing parameters and return values, which helps in thoroughly analyzing how the code runs.
It offers a major benefit with its easy integration into well-known development environments. Developers can quickly set up Xdebug to function with their preferred IDEs, leading to a hassle-free debugging process. This integration improves the ability to find and fix performance issues, making Drupal applications stronger and more responsive.
Xdebug’s remote debugging feature is helpful for developers working in teams or together. It enables easy performance checks and troubleshooting in different development setups.
Explore our services if you want to migrate from your exsisting content management system to Drupal.
Drupal Debug: Drupal Migration Debugging
Drupal migrations can be quite difficult to troubleshoot.
You frequently deal with a large amount of data. Moving a small number of items, such as 5 or 10, is simpler to do by hand using copy and paste.
When you attempt to move thousands of items, it can take a while to realize that you chose the wrong target field. This process is not efficient.
Drupal migrations might look easy at first glance, but they are quite complicated. This complexity comes from the fact that the Migrate API offers a straightforward method for developers to set up migration processes.
Many subsystems, such as Entities, Database, and Plugins, work together during a migration. Even a simple migration includes many classes.
Migrations can also create mistakes that must be corrected, showing why it's important to learn how to troubleshoot them well.
Simple Debugging
We will start with a simple way to identify mistakes during migration.
To reduce possible mistakes, we should manage the migration in small, gradual steps. This means we will proceed slowly and increase the data we move little by little.
-
Checking your Migration Description File
The first steps in our migration debugging process include looking at two main issues that frequently occur in many migrations. So, before we move forward, let's take a quick look:
-
Whitespaces: Any additional spaces might be causing issues with the migration description file. We will quickly check all lines in the file to find any extra spaces.
-
Indentation Mistakes: The migration description file is in YAML format, which arranges data in a key-value system with levels of hierarchy. Each level needs to be indented two spaces to the right. Mistakes in indentation are common and can cause errors when the file is processed.
-
Refreshing Configuration Items
We also need to tackle another problem while fixing our migration: finding a simpler way to update the configuration object that comes from the migration description file in the config/install path.
When the module is installed, a configuration object is made and can be found in your Drupal setup. While debugging, we need to modify the file and refresh it to check if our changes were successful.
Drush and Drupal Console can both be used to run specific imports of configuration files, taking advantage of the special import features each tool provides.
Using Drupal Console
drupal config:import:single --directory="/modules/custom/migration_google_sheet/config/install" --file="migrate_plus.migration.taxonomy_google_sheet.yml"
Using Drush
drush cim --partial --source=/folder/
We can also remove active configuration objects using Drush or Drupal Console.
drush config-delete "migrate_plus.migration.taxonomy_google_sheet"
drupal config:delete active "migrate_plus.migration.taxonomy_google_sheet"
If we choose to utilize the Drupal user interface, we have access to alternatives such as the contributed Config Delete module available at drupal.org/config_delete.
This module improves the internal configuration synchronization menu by adding more options to help remove configuration items from our Drupal setup.
To do this, just download the module with Composer and enable it using Drush or Drupal Console.
composer require drupal/config_delete
drush en config_delete –y
This method lets us bring back configuration objects without causing issues with the current versions saved in the database.
If you decide to update and compare your configuration versions, the Configuration Update Manager module could be a good option.
-
Average Debugging Utilizing Migrate Devel
We need to use some middle techniques to get more details about the process. At this point, we will use different modules and plugins to help improve how we see the migration process.
Migrate Devel
Migrate Devel is a contributed module that enhances the migration processes by providing additional functionalities, including new options for Drush. The Migrate Devel module offers 2 options that can be utilized with the Migrate Tools drush command migrate:import (mim).
drush migrate:import <migration> --migrate-debug
drush migrate:import <migration> --migrate-debug-pre
--migrate-debug: prints each row as it's migrated (MigrateEvents::POST_ROW_SAVE)
--migrate-debug-pre: same idea, but before the process is run on the row (MigrateEvents::PRE_ROW_SAVE)
The Debugging Process Plugin
The Migrate Devel module introduces a new process plugin known as `debug`. This plugin functions by outputting the value it receives directly to the terminal. The `debug` plugin presents several benefits compared to the `log` plugin available in the core Migrate API.
-
The `print_r()` function effectively manages both arrays and scalar values.
-
It allows for a clear distinction between debugging code that needs to be eliminated and logging plugin configurations that should remain intact.
-
This approach is time-efficient, as it eliminates the necessity of executing the `migrate:messages` command to access the logged values.
You can utilize the `debug` plugin as a substitute for `log`. There is a specific scenario in which the use of `debug` proves to be particularly advantageous. When employed within a process plugin chain, it allows you to observe the transformation of elements at each stage.
-
Terminating Unsuccessful Migration
In the event that the migration is unsuccessful, you may encounter the following error when attempting to execute the migration again.
Migration MIGRATION_NAME is busy with another operation: Importing
Execute the subsequent command to release the migration lock, provided that Migrate Tools or Migrate Run is installed.
$ drush migrate:reset-status MIGRATION_NAME # or drush mrs MIGRATION_NAME
If Migrate Tools or Migrate Run have not been installed, please utilize:
$ drush php-eval "var_dump(Drupal::keyValue('migrate_status')->set('MIGRATION_NAME', 0));"
NULL
If you encounter the following error while attempting to execute the command mentioned above:
\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.
-
Limiting and Individual Migrations
The installation of Migrate Tools is a prerequisite for executing the following commands:
When undertaking extensive migrations, it is advantageous to restrict the number of rows being imported. This approach enhances the speed of the import and rollback processes while allowing for more precise field mappings and callbacks.
$ drush migrate:import --limit=10 MIGRATION_NAME
The subsequent commands facilitate the importation and rollback of a specific migration entity for development purposes:
$ drush migrate:import --idlist=123 MIGRATION_NAME
$ drush migrate:rollback --idlist=123 MIGRATION_NAME
The identifier typically corresponds to the primary ID of the entity undergoing migration; however, additional details can be found in the migrate_map_MIGRATION_NAME database tables, particularly in the sourceId column.
Also Check out:
1. Drupal SDC v/s Storybook: What’s The Difference?
2. Drupal SDC: Advantages of Single Directory Components
3. Starshot: Drupal’s New CMS Initiative
4. SDC: Integrating Storybook & Single Directory Component
Key Takeaways:
-
Debugging PHP issues on a Drupal site can vary from easy solutions to significant difficulties.
-
Twig is a fast, modern, and secure template engine that helps developers easily create new templates and handle existing ones effectively.
-
Devel is a popular development module that provides various tools for development and debugging, simplifying many routine tasks.
-
Xdebug is a powerful tool for profiling and tracing that significantly enhances the development process in Drupal.
-
Drupal migrations might look simple at first glance, but they are really quite complicated.
Subscribe
Related Blogs
Drupal SDC v/s Storybook: What’s The Difference?
One helps you set up your UI components, and the other allows you to work with them. we are exploring Single Directory…
Starshot: Drupal’s New CMS Initiative
The Drupal community is excited about the Drupal Starshot project, which aims to update and improve the Drupal experience…
DrupalCon Singapore: It’s A Wind Up For 2024
OpenSense Labs team attended the DrupalCon Singapore 2024 and it was a wonderful and valuable experience, especially since it…