Technical Drupal Interview : Questions & Answers

Being a full stack Drupal developer, got an interview call from the hiring company you have landed on the right place. You will always look for technical Drupal Interview questions list which can be helpful for you to get a job. Whether you're interviewing for a junior position or hoping to get a senior developer job, preparation is not optional. If you've worked with content types, created custom modules, or themed pages with Twig, you're already ahead of the game.
In this guide, you'll discover the most technical questions (and their answers) that may be asked in interviews. Let's first introduce a bit about Drupal itself.
What is a Drupal CMS?
Drupal is an open-source content management system that is free to use. It means we can easily develop websites without writing code and integrate with other technologies to build customized solutions. It can be used to build various types of websites, including saas based products, blog websites, online directories, e-commerce stores, and other digital enterprises. We can create organizational and further customized web applications with the help of this powerful CMS.
1: What is the difference between Drupal 9 & Drupal 10
Drupal 11 is the latest version, but Drupal 10 is currently being used by the most active organizations. It was launched on the 14th of December 2022. It introduces many new features, a few server-level semantics, and necessary tools are updated. Here is the summary of some key differences:
Feature / Aspect | Drupal 9 | Drupal 10 |
---|---|---|
Release Date | June 2020 | December 2022 |
PHP Version Requirement | PHP 7.3+ | PHP 8.1+ (PHP 8.2 recommended) |
Symfony Version | Symfony 4 (with some Symfony 5 support) | Symfony 6 |
CKEditor | CKEditor 4 | CKEditor 5 (modern WYSIWYG editor) |
Frontend Theme | Olivero theme launched (optional) | Olivero becomes the default frontend theme |
Admin Theme | Claro (optional, but available) | Claro becomes the default admin theme |
Deprecated Code | Still contains a lot of deprecated code from D8 | Deprecated code has been largely removed |
New Features | Mostly stability & cleanup | New Starterkit theme generator, modern JavaScript components (like replacing jQuery usage in some places) |
Composer Usage | Strongly recommended | Composer is necessary |
The life of Drupal 9 ended as of November 2023.
2: How will you define a Plugin in Drupal? With brief code examples
In Drupal, a plugin is a reusable small code component developed to implement a certain feature.
Main features of a Plugin:
- Extensible: Plugins are developed to be reusable. They can be easily overridden with new features or be extended lately.
- Encapsulated: They yield a specific functionality, for example, to retrieve the current city name, state, or country of the visitor.
- Flexible: We can easily add functionality without modifying core code with the help of plugins.
Various Types of Plugins in Drupal
Since Drupal has a good plugin system, there are multiple types of plugins available, each serving different purposes. Here is a list of some most commonly used plugins:
i. Block Plugins: Most commonly used plugin type
- Purpose: We can use block plugins to design custom blocks (content blocks) that we can insert anywhere in the theme.
- Example: Designing a block to show custom content or dynamic information.
- Where it's used: We can insert it in different regions of a page in a given theme (such as sidebars, footers, etc.).
<?php
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a 'My Custom Block' block.
*
* @Block(
* id = "my_custom_block",
* admin_label = @Translation("My Custom Block"),
* category = @Translation("Custom")
* )
*/
class MyCustomBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
return [
'#markup' => $this->t('Hello from My Custom Block!'),
];
}
}
ii. Field Type Plugins: For adding a new field type
- Purpose: We use "Field Type" plugins to define custom field types.
- Example: If we want to introduce a new field type not available in Drupal by default (e.g., a "rating" special field, "color picker", etc.), we can use field type plugins.
- Where it's used: We can use it to attach entities such as nodes, users, taxonomy terms, etc.
Example:
We may develop a plugin for a custom field type for ratings where users can rate articles based on 1 to 5 points.
iii. Formatter Plugins
- Purpose: Determines how a field is shown.
- Example: We may develop a "Formatter plugin" that displays the "rating" field as stars rather than numbers.
- Where it's used: In the field settings, to modify the way content is rendered.
iv. Views Query Plugins: To customize views queries at the database level
- Purpose: We can specify how a view fetches data (e.g., a custom query to get nodes).
- Example: A plugin to modify how search results are fetched for a specific view.
- Where it's used: In custom views to modify how data is queried and presented.
v. Event Subscriber Plugins: To render events & actions
- Purpose: It responds to Drupal events and reacts accordingly while performing a task when an event occurs.
- Example: We can develop a plugin that responds to user login events and sends a welcome email.
- Where it's used: It is used in Drupal’s event-based system when they are triggered.
vi. Cache Plugins: Full-fill Drupal cache mechanism
- Purpose: It modifies the way that data is cached within Drupal.
- Example: A plugin that specifies how to cache data being retrieved from an external API.
- Where it's used: It is used within Drupal's cache system.
Example of Creating a Custom Block Plugin
Let's go through an example of building a custom block plugin.
- Create the Plugin File:
Let's create a basic block that will output a message.- File structure:
modules/custom/my_module/src/Plugin/Block/MyCustomBlock.php
Code Example:
<?php
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a 'My Custom Block' block.
*
* @Block(
* id = "my_custom_block",
* admin_label = @Translation("My Custom Block"),
* category = @Translation("Custom")
* )
*/
class MyCustomBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
return [
'#markup' => $this->t('Hello, this is my custom block!'),
];
}
}
3: How do you inject a service into a custom module?
Injecting services into a custom module in Drupal 10 is a common practice when we want to use the built-in services provided by Drupal, such as database access, file management, cache handling, or our custom services.
How to Define a Custom Service?
In Drupal, services are objects that provide specific functionality (like interacting with the database, sending emails, or logging errors). Drupal’s dependency injection system allows us to access these services in our custom module classes.
In our module, create a my_module.services.yml file:
services:
my_module.my_custom_service:
class: Drupal\my_module\Service\MyCustomService
arguments: ['@logger.factory']
Steps to Inject a Service into our Custom Module
Let’s go through the steps for injecting a service into our custom module.
Define our Service in a (services.yml)File (Optional for Custom Services)
If we're injecting custom services, we'll need to define them in the services.yml file for our module. For core Drupal services, no service definition is required. Drupal comes with these features that are already built-in, without needing extra plugins or setup.
For a custom service:
- In our custom module, create a my_module.services.yml file.
- Define our custom service.
For example:
services:
my_module.example_service:
class: Drupal\my_module\Service\ExampleService
arguments: ['@database', '@logger.channel.my_module']
Create our own Custom Service Class
We need to create a class that will define the logic for our custom service. This class will live in the src/Service/ directory of our module.
Example: Create src/Service/ExampleService.php in our custom module.
<?php
namespace Drupal\my_module\Service;
use Drupal\Core\Database\Connection;
use Drupal\Core\Logger\LoggerChannelInterface;
/**
* Example service.
*/
class ExampleService {
protected $database;
protected $logger;
/**
* Constructs an ExampleService object.
*
* @param \Drupal\Core\Database\Connection $database
* The database connection service.
* @param \Drupal\Core\Logger\LoggerChannelInterface $logger
* The logger service.
*/
public function __construct(Connection $database, LoggerChannelInterface $logger) {
$this->database = $database;
$this->logger = $logger;
}
/**
* A method to log a message and execute a query.
*/
public function logAndQuery() {
// Example database query.
$query = $this->database->select('node', 'n')
->fields('n', ['nid', 'title'])
->condition('status', 1)
->execute();
// Example log.
$this->logger->info('Executed query for nodes.');
}
}
- Dependencies: This service uses the database connection (@database) and the logger (@logger.channel.my_module) services.
The __construct method: receives these dependencies, which will be injected automatically when the service is used.
Injecting the Service into our Controller/Block
Now that we’ve defined the service, we can inject it into other classes like a Controller, Block, or Form. Let’s say we want to use it inside a Controller.
- Create the controller: src/Controller/MyModuleController.php.
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\my_module\Service\ExampleService;
/**
* Controller for My Custom Module.
*/
class MyModuleController extends ControllerBase {
protected $exampleService;
/**
* Constructor to inject the service.
*
* @param \Drupal\my_module\Service\ExampleService $example_service
* The example service.
*/
public function __construct(ExampleService $example_service) {
$this->exampleService = $example_service;
}
/**
* Creates the page.
*/
public function content() {
// Call the service method.
$this->exampleService->logAndQuery();
return [
'#markup' => $this->t('Hello, welcome to my custom page!'),
];
}
}
Here’s how it works:
The controller’s __construct() method accepts an instance of our custom service (ExampleService) as a parameter.
When the controller is called, the service is automatically injected into the controller class, and we can call the service methods like logAndQuery().
Ensure Dependency Injection Works with a Controller
To let Drupal know that this controller should use dependency injection, we register the controller as a service in our module.
In our my_module.services.yml, add:
services:
my_module.my_module_controller:
class: Drupal\my_module\Controller\MyModuleController
arguments: ['@my_module.example_service']
tags:
- { name: controller.service_arguments }
Route to our Controller
Now, define a route in my_module.routing.yml to use this controller:
my_module.page:
path: '/my-custom-page'
defaults:
_controller: '\Drupal\my_module\Controller\MyModuleController::content'
_title: 'My Custom Page'
requirements:
_permission: 'access content'
Summary of Injecting Services in Drupal 10
Step | What We Do |
---|---|
1 | Create a module folder in modules/custom/ |
2 | Create a .info.yml file |
3 | (Optional) Create a .module file for hooks |
4 | (Optional) Create routing/controllers/services if needed |
5 | Enable the module |
- Define your service in a services.yml file (for custom services).
- Create the service class with a constructor to accept dependencies (like the database, logger, etc.).
- Inject the service into other Drupal classes (like controllers, blocks, and forms) via constructor injection.
- Register the service and define a route if it’s a controller.
4: What is the difference between a service & plugin?
In Drupal, both services and plugins are used to provide functionality, but they serve different purposes, have different lifecycles, and are used in different ways.
High-Level Difference
Feature | Service | Plugin |
---|---|---|
What is it? | A reusable object that provides a specific, global functionality. | A swappable or extendable component that performs a task in a specific context (e.g., block, field, view). |
Architecture | Based on Symfony’s Dependency Injection Component. | Based on Drupal’s Plugin API. |
Configured via | *.services.yml | Annotations (e.g., @Block , @FieldFormatter ), YAML, or config. |
Usage | Used globally by injecting it or using \Drupal::service() . | Used where variation or extendability is needed (like defining multiple types of the same thing). |
Example | Logging, mail sending, database access, config management. | Blocks, field types, views display plugins, image effects. |
Examples
Service Example
Logging a message:
$logger = \Drupal::service('logger.factory')->get('my_module');
$logger->notice('Something happened.');
- Service: logger.factory
- Purpose: Logging
- Centralized, non-configurable, and reusable.
Plugin Example
Creating a custom block:
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a 'Hello World' block.
*
* @Block(
* id = "hello_world_block",
* admin_label = @Translation("Hello World Block")
* )
*/
class HelloWorldBlock extends BlockBase {
public function build() {
return ['#markup' => $this->t('Hello, world!')];
}
}
- Plugin type: Block
- Purpose: Allows Drupal to discover and list available blocks.
- Configurable and pluggable by users in the UI.
Key Conceptual Difference
Feature | Service | Plugin |
---|---|---|
What is it? |
|
|
Usage Situation |
|
|
Summary:
- A service is like a shared toolbox — global, reusable, and injectable.
A plugin is like a customizable component — modular, extendable, and often configurable by users.
6: How do you override a Twig template in Drupal 10?
To override a Twig template in Drupal 10 usually means:
- Copying the primary template.
- Placing it in our theme.
- Optionally, making changes to it.
- Informing Drupal to use ours instead.
Here’s the step-by-step guide:
I. Locate the Template We Want to Override
Locate the primary Twig file. Core templates are located:
/core/themes/classy/templates/
Or
/core/modules/{module}/templates/
II. Copy It to our Theme
Copy the template into our theme’s /templates/ folder.
Example:
/themes/custom/my_theme/templates/node.html.twig
(Create the templates/ directory if it doesn't exist.)
III. Use Specific Naming (Optional but Useful)
We can also create more specific template overrides with naming conventions.
Examples:
What | Suggested Template Name |
---|---|
All nodes | node.html.twig |
Node type "article" | node--article.html.twig |
Node ID 7 | node--7.html.twig |
IV. Clear Cache
After modifying or adding templates, we need to clear Drupal's cache so we can see changes.
- We can do this via the admin UI:
Configuration » Development » Performance » Clear all caches
- We can also use Drush if we have it:
drush cr
V. (Optional) Use Debugging to See Which Template is Used
Developers can make their lives easier by activating Twig debugging:
- Edit our services.yml (usually sites/default/services.yml).
- Enable debugging:
parameters:
twig.config:
debug: true
auto_reload: true
cache: false
Quick Example:
Suppose we want a custom look for articles:
- Copy node.html.twig → node--article.html.twig into our theme
- Customize it as needed
- Clear caches
- Done!
In short:
Copy the correct template to our theme's templates/ folder, rename it appropriately, customize it, and clear the cache.
7: What are entities, and how are they different from nodes?
Before we discuss. the detailed comparison between entities and nodes, we should learn about Entity.
What is an Entity?
In Drupal CMS, an entity is a data structure used to save and manage data. It is the core object type for many things, such as:
Users
Nodes (content)
Comments
Taxonomy terms
Files
Customized config entities
Whereas a node is a specific type of entity (content) in Drupal CMS that represents a piece of user-facing data, such as:
Basic page
Article
Blog (for blogging website)
Product (for e-commerce sites)
An entity can not have a URL all the time, but a node always has a URL attached to it.
Code examples for entity & node:
How to extract all entity types:
\Drupal::entityTypeManager()->getDefinitions();
If you want to get a node (which is an entity of type node):
$node = \Drupal::entityTypeManager()->getStorage('node')->load(9);
If you want to get a user (a different entity type):
$user = \Drupal::entityTypeManager()->getStorage('user')->load(2);
8: What are Entity APIs in Drupal?
Entity APIs are sets of tools and built-in functions that let developers work with entities (nodes, users, taxonomy terms, etc.) easily in code, without writing custom code to apply different actions on these entities.
Entity APIs allow you to:
- Create, load, save, update, and delete entities
- Manage fields on entities
- Handle access control for entities
- View or render entities
- Define new entity types (if needed)
9: Why do Entity APIs exist?
- To standardize how all entity types behave (nodes, users, comments, etc.).
- To make entities fieldable, translatable, revisionable, access-controlled, etc., consistently.
- To allow developers to extend Drupal easily.
Without them, every module would have to reinvent how data is saved and loaded.
API Area | What it Does | Example |
---|---|---|
Entity Storage API | Create, load, save, delete entities | $node = \Drupal::entityTypeManager()->getStorage('node')->load(1); |
Entity Field API | Manage fields attached to entities | Add a "summary" field to Articles |
Entity Type API | Define new types of entities (custom) | Create a custom "Event" entity |
Entity Access API | Control who can view/edit entities | Only admins can edit unpublished nodes |
Entity View & Form API | Render entities or create forms for them | Show a rendered view of a node |
Entity Query API | Find entities with conditions | Find all published "Article" nodes |
10: How do you migrate content into Drupal 10? (Migrate API basics.)
We use the Migrate API — a powerful system for importing data from anywhere (CSV, JSON, databases, XML, old Drupal sites) into entities (nodes, users, taxonomy, etc.).
The Migrate API has been built into Drupal Core since Drupal 8+ — no need for external modules for basic migrations!
Basic Concepts We Must Know
Concept | Meaning | Example |
---|---|---|
Source | Where does our data come from | CSV file, JSON API, SQL table |
Process | How the data is transformed | Mapping "title" column to "title" field |
Destination | Where the data ends up | Node entity, taxonomy term, user |
Migration Plugin | The YAML + PHP config that defines the migration | my_migration.yml |
The Basic Flow
- Define the source (e.g., CSV file).
- Define the process (map fields from source → destination).
- Define the destination (e.g., a node of type "article").
- Run the migration with Drush or the UI.
A Simple Example: CSV to Node Migration
id, title, body
1, First Title, This is the first body text.
2, Second Title, This is the second body text.
Enable Core Migrate Modules
Make sure these core modules are enabled:
- migrate
- migrate_plus (for better plugins, contributed module, can be installed with composer)
- migrate_tools (optional, for Drush commands)
drush en migrate migrate_plus migrate_tools -y
Create the Migration YAML File
Example: config/install/migrate_plus.migration.example_csv_node.yml
id: example_csv_node
label: 'Import CSV into Article Nodes'
migration_group: default
source:
plugin: csv
path: private://import/example.csv
header_row_count: 1
keys:
- id
process:
title: title
body/0/value: body
destination:
plugin: 'entity: node'
default_bundle: article
What's happening here?
- Source: reads a CSV at private://import/example.csv.
- Process: maps title and body from CSV to node fields.
- Destination: creates node entities of type article.
Place the CSV File
Upload our example.csv to sites/default/files/private/import/example.csv.
(Make sure the private file system is properly configured.)
Import and Run the Migration
Use Drush to run the migration:
drush migrate-import example_csv_node
We can also roll back if needed:
drush migrate-rollback example_csv_node
Important Points to Know
- Migrate Plus → extends the core Migrate API with powerful plugins (source, destination, process).
- Migrate Tools → provides Drush commands for migrations (migrate-import, migrate-rollback, etc.).
- Process Plugins → allow field transformations (default, concat, explode, etc.).
- Migrations are configuration → usually YAML + optional PHP plugins if we need custom logic.
11: What is Solr?
Solr is a powerful, fast, scalable search engine that can index and search large amounts of data, much quicker and smarter than a normal database. It is used by big organizations like Netflix, Instagram, eBay, Wikipedia, and many Drupal websites to power search features. Solr (pronounced "solar") is an open-source search platform built on top of Apache Lucene.
Key Things About Solr
Feature | What It Means |
---|---|
Full-text search | Search inside long blocks of text (like articles, product descriptions) |
Faceted search | Filter results by categories, dates, authors, etc. |
Scalability | Can handle millions of documents and huge traffic |
High Performance | Very fast — uses optimized indexes |
Custom Ranking | We can control which results show first (e.g., newer, more popular) |
Multi-language support | Understands and indexes different languages properly |
Distributed search | Can run across multiple servers (SolrCloud) for high availability |
How Solr Works
- Ingests/Indexes our data (articles, products, etc.).
- Pre-processes the data (splits it into words, stems words, tokenizes, removes stopwords like "the", "a", etc.).
- Stores optimized indexes of the data.
- Responds to search queries very quickly using these indexes.
- Ranks and filters search results based on relevance, freshness, fields, or custom rules.
Example of Solr Use Cases
Site Type | What Solr Powers |
---|---|
News Site | Search articles by title, date, or tag |
E-commerce Site | Product search with filters like brand, price, and size |
University | Search courses, programs, people, and departments |
Government Site | Search policies, reports, and public documents |
Solr Components at a High Level
Component | What It Does |
---|---|
Index | Where Solr stores prepared data |
Query | How do you search the index |
Analyzer | How text is broken down into searchable parts |
Schema | Rules for fields (e.g., title is text, date is date) |
Facets | Grouping search results (e.g., 10 items in "News", 5 in "Events") |
Core | A "mini Solr server" with its data and config |
In Short:
Solr is a specialized search server that provides very fast, very powerful search and filtering, especially for large amounts of data.
It acts outside of Drupal (or any other system) but connects to it through APIs like Search API Solr in Drupal projects.
12: What is Solr Search in Drupal?
Apache Solr is an open-source, very fast, scalable search platform based on Lucene.
- In Drupal, Solr is often used to replace or enhance the default search system.
- It provides better performance, full-text search, faceted search, autocomplete, multilingual support, boosting, and much more.
When people say "Solr Search in Drupal," they usually mean:
- Drupal connects to an external Solr server (Apache Solr).
- Solr handles indexing and searching content instead of Drupal’s built-in database search.
- Search API + Search API Solr modules are used to integrate Drupal with Solr.
How Solr Fits into Drupal
Part | What it Does | Example |
---|---|---|
Drupal Core/Search API | Defines what we want to index (content, users, taxonomy terms, etc.) | Articles and Pages |
Search API Solr Module | Connects Drupal to a Solr server (sends data for indexing, runs searches) | Talks to the Solr server |
Apache Solr | Stores, indexes, and ranks our content outside of Drupal’s database | Fast, scalable searches |
13: Why Use Solr with Drupal?
Without Solr: painful, slow.
With Solr + Search API + Facets: fast and dynamic.
Without Solr | With Solr |
---|---|
Slower searches (SQL queries) | Super fast searches (pre-indexed data) |
No advanced search features | Faceted search, boosting, and multilingual |
Hard to scale for big sites | Built for huge datasets |
Limited ranking options | Highly customizable ranking (e.g., newer content first) |
Big Idea:
Solr offloads search work from Drupal's database and makes searching much faster and smarter.
Key Modules for Solr Search in Drupal 10
search_api — a flexible system that defines search indexes and pages.
- search_api_solr — integrates Drupal's Search API with an external Solr server.
- Facets — let's create filters (faceted navigation) for search results.
Sometimes:
search_api_autocomplete — for live search suggestions.
Basic Setup Steps
- Install Apache Solr (server) — or use a managed Solr service (Like: SearchStax, Acquia Search, Platform.sh Solr, etc.).
- Install and enable these modules in Drupal:
- search_api
- search_api_solr
- Create a Search API Index in Drupal:
- Choose what we want to index (nodes, files, users).
- Choose what we want to index (nodes, files, users).
- Connect to the Solr server:
- Provide Solr connection details (URL, core name, credentials).
- Provide Solr connection details (URL, core name, credentials).
- Index our content:
- Run the indexing (sending data from Drupal → Solr).
- Run the indexing (sending data from Drupal → Solr).
- Create a Search View (using Views):
Display the search results with filters, sorts, facets, etc.
Real-World Example
Build a faceted search page where users can:
- Search Articles
- Filter by author
- Filter by publication date
Filter by tags
14: What are the key steps to create a custom module in Drupal 10?
Create a Module Folder
Go to our Drupal site's codebase:
- Navigate to:
modules/custom/
- Create a new folder for our module, e.g.:
modules/custom/my_module/
(custom/ doesn't exist by default — create it manually if needed.)
Create a .info.yml File
Inside my_module/, create a file named:
my_module.info.yml
And add this basic content:
name: 'My Module'
type: module
description: 'A simple custom module for Drupal 10.'
core_version_requirement: ^10
package: Custom
dependencies: []
(Optional) Create a .module File
my_module.module
<?php
/**
* @file
* Contains my_module.module
*/
(Optional) Define a Services File (if needed)
my_module.services.yml
services:
my_module.example_service:
class: Drupal\my_module\ExampleService
Enable our Module
Basic Structure of a Custom Module
modules/custom/my_module/
│
├── my_module.info.yml ← (Required)
├── my_module.module ← (Optional, for hooks)
├── my_module.services.yml ← (Optional, for services)
├── src/ ← (PHP classes, controllers, plugins go here)
├── templates/ ← (Twig templates if any)
└── my_module.routing.yml ← (Optional, for page routes)
Example: Create a Simple Page Route (Optional)
If we want our module to create a page like /hello, we add:
Create my_module.routing.yml:
my_module.hello:
path: '/hello'
defaults:
_controller: '\Drupal\my_module\Controller\HelloController::hello'
_title: 'Hello Page'
requirements:
_permission: 'access content'
Create a PHP file: src/Controller/HelloController.php:
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
class HelloController extends ControllerBase {
public function hello() {
return [
'#markup' => $this->t('Hello from my custom module!'),
];
}
}
Now, visiting /hello will show "Hello from my custom module!".
Summary
Step | What We Do |
---|---|
1 | Create a module folder in modules/custom/ |
2 | Create a .info.yml file |
3 | (Optional) Create a .module file for hooks |
4 | (Optional) Create routing/controllers/services if needed |
5 | Enable the module |
Quick Pro Tips
- Use Pascal Case or snake_case names carefully.
- Clear Drupal cache often (drush cr)
- Log errors to Drupal watchdog
(\Drupal::logger('my_module')->error('Something went wrong');).
15: How can you programmatically invalidate a cache?
I. Invalidate a Specific Cache Tag
Drupal caches a lot of things using cache tags.
We can invalidate the cache related to a specific tag like this:
\Drupal\Core\Cache\Cache::invalidateTags(['my_custom_tag']);
This tells Drupal:
"Anything cached with the tag my_custom_tag should now be considered expired."
Example:
\Drupal\Core\Cache\Cache::invalidateTags(['node:123']);
This would invalidate all cache related to Node ID 123.
You may also like to read: What are the Key Differences Between Drupal 10 and Drupal 11
II. Invalidate a Whole Cache Bin
Drupal organizes caches into bins (like "render", "dynamic_page_cache", etc.).
If we want to clear an entire bin:
\Drupal::cache('render')->invalidateAll();
Example bins:
- render
- dynamic_page_cache
- page
- config
Example:
\Drupal::cache('page')->invalidateAll();
III. Delete a Specific Cache ID (CID)
If we know the cache ID (cid) of an item, we can delete it directly:
\Drupal::cache('our_bin')->delete('our_cache_id');
Example:
\Drupal::cache('render')->delete('example_cache_id');
IV. Invalidate Render Cache for a Specific Entity
When we update an entity (like a Node, User, or Taxonomy Term), we usually want to clear its render cache.
/** @var \Drupal\Core\Entity\EntityInterface $entity */
\Drupal\Core\Cache\Cache::invalidateTags($entity->getCacheTags());
I have tried to cover Drupal technical interview questions mostly backend perspective. I'll update this list soon to have frontend questions as well. Contact us if you want to help in improving this list.