Skip to main content

Technical Drupal Interview : Questions & Answers

Technical Drupal Interview
Technical Drupal Interview : Questions and 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 / AspectDrupal 9Drupal 10
Release DateJune 2020December 2022
PHP Version RequirementPHP 7.3+PHP 8.1+ (PHP 8.2 recommended)
Symfony VersionSymfony 4 (with some Symfony 5 support)Symfony 6
CKEditorCKEditor 4CKEditor 5 (modern WYSIWYG editor)
Frontend ThemeOlivero theme launched (optional)Olivero becomes the default frontend theme
Admin ThemeClaro (optional, but available)Claro becomes the default admin theme
Deprecated CodeStill contains a lot of deprecated code from D8Deprecated code has been largely removed
New FeaturesMostly stability & cleanupNew Starterkit theme generator, modern JavaScript components (like replacing jQuery usage in some places)
Composer UsageStrongly recommendedComposer 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.

  1. 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 accessfile managementcache 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:

  1. In our custom module, create a my_module.services.yml file.
  2. 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.

  1. 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

StepWhat We Do
1Create a module folder in modules/custom/
2Create a .info.yml file
3(Optional) Create a .module file for hooks
4(Optional) Create routing/controllers/services if needed
5Enable the module
  1. Define your service in a services.yml file (for custom services).
     
  2. Create the service class with a constructor to accept dependencies (like the database, logger, etc.).
     
  3. Inject the service into other Drupal classes (like controllers, blocks, and forms) via constructor injection.
     
  4.  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

 

FeatureServicePlugin
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).
ArchitectureBased on Symfony’s Dependency Injection Component.Based on Drupal’s Plugin API.
Configured via*.services.ymlAnnotations (e.g., @Block, @FieldFormatter), YAML, or config.
UsageUsed globally by injecting it or using \Drupal::service().Used where variation or extendability is needed (like defining multiple types of the same thing).
ExampleLogging, 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

FeatureServicePlugin
What is it?
  • Like utilities or tools (e.g., a mailer, logger, entity manager).
  • Defined once and shared.
  • Used behind the scenes.
  • Like components with multiple implementations (e.g., many different blocks, field types).
  • Swappable and often user-facing.
  • Used when Drupal needs to discover or allow selection of different implementations.
Usage Situation
  • We need a reusable utility or tool (e.g., send an email, log a message)
  • We want a shared backend functionality
  • We need a user-selectable or extendable behavior (e.g., custom block, custom field formatter)
  • We want multiple implementations of the same "type" of thing

Summary:

  • service is like a shared toolbox — global, reusable, and injectable.
  • 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:

WhatSuggested Template Name
All nodesnode.html.twig
Node type "article"node--article.html.twig
Node ID 7node--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:

  1. Users

  2. Nodes (content)

  3. Comments

  4. Taxonomy terms

  5. Files

  6. 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:

  1. Create, load, save, update, and delete entities
     
  2. Manage fields on entities
     
  3. Handle access control for entities
     
  4. View or render entities
     
  5. 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 AreaWhat it DoesExample
Entity Storage APICreate, load, save, delete entities$node = \Drupal::entityTypeManager()->getStorage('node')->load(1);
Entity Field APIManage fields attached to entitiesAdd a "summary" field to Articles
Entity Type APIDefine new types of entities (custom)Create a custom "Event" entity
Entity Access APIControl who can view/edit entitiesOnly admins can edit unpublished nodes
Entity View & Form APIRender entities or create forms for themShow a rendered view of a node
Entity Query APIFind entities with conditionsFind 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

 

ConceptMeaningExample
SourceWhere does our data come fromCSV file, JSON API, SQL table
ProcessHow the data is transformedMapping "title" column to "title" field
DestinationWhere the data ends upNode entity, taxonomy term, user
Migration PluginThe YAML + PHP config that defines the migrationmy_migration.yml

The Basic Flow

  1. Define the source (e.g., CSV file).
     
  2. Define the process (map fields from source → destination).
     
  3. Define the destination (e.g., a node of type "article").
     
  4. 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 NetflixInstagrameBayWikipedia, 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

FeatureWhat It Means
Full-text searchSearch inside long blocks of text (like articles, product descriptions)
Faceted searchFilter results by categories, dates, authors, etc.
ScalabilityCan handle millions of documents and huge traffic
High PerformanceVery fast — uses optimized indexes
Custom RankingWe can control which results show first (e.g., newer, more popular)
Multi-language supportUnderstands and indexes different languages properly
Distributed searchCan run across multiple servers (SolrCloud) for high availability

How Solr Works

  1. Ingests/Indexes our data (articles, products, etc.).
     
  2. Pre-processes the data (splits it into words, stems words, tokenizes, removes stopwords like "the", "a", etc.).
     
  3. Stores optimized indexes of the data.
     
  4. Responds to search queries very quickly using these indexes.
     
  5. Ranks and filters search results based on relevance, freshness, fields, or custom rules.

 Example of Solr Use Cases

Site TypeWhat Solr Powers
News SiteSearch articles by title, date, or tag
E-commerce SiteProduct search with filters like brand, price, and size
UniversitySearch courses, programs, people, and departments
Government SiteSearch policies, reports, and public documents

Solr Components at a High Level

ComponentWhat It Does
IndexWhere Solr stores prepared data
QueryHow do you search the index
AnalyzerHow text is broken down into searchable parts
SchemaRules for fields (e.g., title is text, date is date)
FacetsGrouping search results (e.g., 10 items in "News", 5 in "Events")
CoreA "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 performancefull-text searchfaceted searchautocompletemultilingual supportboosting, 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

PartWhat it DoesExample
Drupal Core/Search APIDefines what we want to index (content, users, taxonomy terms, etc.)Articles and Pages
Search API Solr ModuleConnects Drupal to a Solr server (sends data for indexing, runs searches)Talks to the Solr server
Apache SolrStores, indexes, and ranks our content outside of Drupal’s databaseFast, scalable searches

 

13: Why Use Solr with Drupal?

Without Solr: painful, slow.
With Solr + Search API + Facets: fast and dynamic.

Without SolrWith Solr
Slower searches (SQL queries)Super fast searches (pre-indexed data)
No advanced search featuresFaceted search, boosting, and multilingual
Hard to scale for big sitesBuilt for huge datasets
Limited ranking optionsHighly 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

  1. Install Apache Solr (server) — or use a managed Solr service (Like: SearchStax, Acquia Search, Platform.sh Solr, etc.).
     
  2. Install and enable these modules in Drupal:
     
    • search_api 
    • search_api_solr
       
  3. Create a Search API Index in Drupal:
     
    • Choose what we want to index (nodes, files, users).
       
  4. Connect to the Solr server:
     
    • Provide Solr connection details (URL, core name, credentials).
       
  5. Index our content:
     
    • Run the indexing (sending data from Drupal → Solr).
       
  6. 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

StepWhat We Do
1Create a module folder in modules/custom/
2Create a .info.yml file
3(Optional) Create a .module file for hooks
4(Optional) Create routing/controllers/services if needed
5Enable 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.

Tags

Related Solutions