Drupal combines structured content management with an extensible PHP framework. Developer interviews often turn on the boundaries between content and configuration, access checks and presentation, or cached output and the data that can invalidate it. Explaining those boundaries matters as much as knowing where to add a module or template.
This guide to 100+ Drupal Interview Questions and Answers contains 120 questions across beginner, intermediate, and experienced levels. It covers entities, fields, configuration, Views, services, plugins, Twig, render arrays, caching, APIs, security, testing, and deployment for Drupal developer roles.
How can recruiters detect AI-assisted cheating, deepfakes, and impersonation during Drupal interviews?
A Drupal interview might ask a candidate to build a small feature, trace a route to its controller, or diagnose stale content that appears only for certain users. Follow-up questions about permissions, configuration dependencies, render arrays, and cache metadata reveal whether the candidate understands how the feature behaves across requests. Unauthorized real-time assistance can hide gaps in that reasoning.
Sherlock AI helps recruiters detect potential AI-assisted cheating, deepfakes, candidate impersonation, and unauthorized real-time assistance during Drupal developer interviews.
Pair interview-integrity checks with a focused module, entity, or theming exercise. Ask candidates to explain the access rules, identify what must be deployed, and show how they would test a changed permission or content value. Review suspicious activity in context rather than treating a signal as proof of misconduct.
Drupal Interview Questions
Choose questions that reflect the role's balance of site building, PHP development, theming, and integration work. Start with content modeling and configuration, then add access, caching, and deployment scenarios. Establish the Drupal core version and relevant contributed modules before discussing release-dependent behavior.
Drupal Interview Questions for Beginners
These beginner questions cover modules, themes, content types, fields, entities, Views, configuration, routing, and basic access control. They test whether a candidate can distinguish site-building choices from custom code and explain how a simple feature fits into Drupal.
What is Drupal, and when is a structured content management system a better fit than building every feature from scratch?
How do Drupal modules and themes divide responsibility for a site's behavior and presentation?
What is the difference between core, contributed, and custom modules, and how would you choose among them?
How do Composer and Drush serve different purposes in a modern Drupal project?
What Drupal and PHP versions should you establish before using an interview example or installing a module?
What is an entity in Drupal, and why is it incorrect to say that every piece of stored content is a node?
How does a content type relate to the node entity type, a bundle, and individual content items?
How do base fields differ from configurable fields attached to a bundle?
What is the difference between a field widget and a field formatter?
When should one content item reference another entity instead of duplicating its text in a field?
What are taxonomy vocabularies and terms, and how would you use them to classify articles?
How does a reusable Media entity differ from the underlying file it may reference?
What does Views do, and how do a view's query and its displays work together?
How do ordinary filters, exposed filters, and contextual filters differ in Views?
How do a block plugin, a placed block, and reusable custom block content differ?
How do theme regions and Layout Builder differ as ways to arrange page content?
How do roles and permissions control what a Drupal user can do?
Why is hiding a menu link or an edit button not sufficient to protect the underlying operation?
How do revisions differ from publishing status and editorial moderation states?
What is the difference between content translation, interface translation, and configuration translation?
How do a route name, an internal path, and a URL alias differ?
Why do formatted-text fields have a text format, and why should unrestricted HTML be limited to trusted users?
How do content, configuration, and environment-specific state differ in Drupal?
What information belongs in a custom module's .info.yml file, and why does its machine name matter?
What connects an incoming URL to a controller or form, and where is route access declared?
What is a Drupal service, and why is dependency injection useful in custom code?
How do hooks, plugins, and event subscribers solve different extension problems?
What happens during a Form API form's build, validation, and submission stages?
Why do Drupal controllers and blocks usually return render arrays instead of printing HTML?
What is Twig responsible for in Drupal, and what application logic should remain outside templates?
How do Twig template suggestions and preprocess code help customize presentation without editing core files?
Why should a theme or module declare CSS and JavaScript in asset libraries instead of hard-coding script tags?
What different questions are answered by cache contexts, cache tags, and cache max-age?
What kinds of work belong in Drupal cron, and why is cron not a guarantee of execution at an exact time?
Which Drupal reports and logs would you check first when a newly installed feature fails?
What is the purpose of composer.lock, and why should a team commit it with composer.json?
How would you assess and apply a Drupal security update without treating a successful download as a completed update?
Why should a module normally be uninstalled in Drupal before its code is removed with Composer?
What does Drupal core's JSON:API module expose, and why does enabling it not grant clients unrestricted access?
Why should Drupal feature work use a separate development environment and a tested backup-and-restore process?
Drupal Interview Questions for Intermediate
These intermediate questions examine services, plugins, entity APIs, forms, configuration schema, cache metadata, Twig, and web APIs. They focus on implementing features that remain correct across users, languages, content changes, and configuration imports.
Which files and namespaces would you create for a small Drupal 11 module with one permission-protected page and one reusable service?
How would you inject an entity-type manager into a controller rather than call the global service locator throughout its methods?
How does a services.yml definition connect a service ID, a PHP class, and constructor arguments?
How would you load a bounded list of articles for display while making the entity query's access-check decision explicit?
How would you create or update a node through the Entity API while accounting for field values, validation, and operation-level access?
How would you render an entity in a view mode without losing access decisions, field presentation, or cache metadata?
When would you implement a custom field type, widget, or formatter, and which responsibility belongs to each?
How would you define a simple custom block plugin with a PHP attribute in Drupal 11?
How does dependency injection into a block plugin differ from constructing an ordinary service?
How does Drupal convert a route parameter into an entity, and why does successful conversion not prove the user may access it?
How should a custom access check return an AccessResult and preserve the dependencies of its decision?
How would you implement a small FormBase form that rejects invalid input before any data is saved?
How would you build a configuration form with ConfigFormBase and distinguish editable configuration from read-only configuration?
How would you update a dependent form element with AJAX while preserving form state and server-side validation?
How would you protect a custom state-changing route against CSRF, and why is a permission check alone insufficient?
How would you alter a specific form without editing its original module, using Drupal 11's supported hook mechanisms?
How would you move a new content type and view from development to production without copying production content backwards?
How would you separate environment-specific endpoints and secrets from configuration that is exported to version control?
What does configuration schema describe, and how does it support typed data, translation, and validation?
How would you choose among configuration, state, private temporary storage, and cache for different kinds of non-content data?
How do Twig auto-escaping, the raw filter, and quoted HTML attributes affect the safety of a template?
If preprocess code adds data from another entity or configuration object, how should its cache dependencies reach the rendered output?
How would you attach JavaScript behavior to both initial and AJAX-inserted markup without binding the same handler repeatedly?
Why can adding a relationship to a View duplicate rows, and how would you choose between correcting the relationship, aggregation, or a different display?
How do a View's access setting and its data filters differ, and why must you preserve entity-access enforcement in its query and output?
What cache context would a block need if its message depends on the current user rather than only their permissions?
Why might a cached list remain stale when a new matching entity is created, even if every displayed entity's cache tag was added?
How do cacheability and attached assets bubble through nested render arrays, and what can go wrong when you render too early?
How do Internal Page Cache, Dynamic Page Cache, and render caching differ in the work they reuse?
How would you describe a migration's source, process pipeline, destination, and source-ID definition?
How would migration_lookup and migration dependencies preserve references when source and destination entity IDs differ?
How would a client request related resources and paginate a JSON:API collection without assuming one response contains every accessible item?
What must you verify before enabling authenticated JSON:API writes, including permissions, read-only mode, and the authentication method?
When would you move work from a page request into a queue worker, and what must happen before a claimed item is considered complete?
How does the Batch API help a user-triggered bulk operation, and how is its purpose different from a background queue?
How would you log a failed external request with useful context while avoiding credentials, personal data, and misleading success messages?
How do database update hooks, post-update functions, configuration import, and Drush deploy fit into a release?
When would you choose a unit, kernel, functional, or FunctionalJavascript test for a custom Drupal feature?
How would you select and render the appropriate entity translation while accounting for language fallback and cache variation?
How would you investigate repeated entity loads or remote calls inside a render loop before adding more caching?
Drupal Interview Questions for Experienced
These experienced-level questions address architecture, performance, security, migrations, multilingual behavior, testing, deployment, and upgrades. They ask how an engineer diagnoses a problem, preserves content and configuration integrity, and validates changes across environments.
When would you model a business object as a node bundle, a custom content entity, configuration, or an external record?
How would you design and test tenant-specific content access across entity pages, Views, JSON:API, and cached output?
How would you change a field or custom entity schema that already contains production data without assuming a cache rebuild performs the migration?
How would you diagnose a moderation workflow where a translated draft unexpectedly changes the published experience in another language?
How would you make scheduled or time-sensitive content become visible on time across render caches, anonymous page caches, and a CDN?
How would you reduce an exploding number of cache variants without combining outputs that different users are not allowed to share?
An anonymous visitor sees another visitor's cookie-dependent content after the cache warms; how would you trace and repair the cache boundary?
How do allowed, forbidden, and neutral access results combine, and why must their cache metadata survive an andIf or orIf operation?
How would you modernize annotation-based plugins while checking whether their plugin managers support PHP attributes?
When should a reusable custom feature expose a plugin type instead of one service, a hook, or an event?
How would you design an event subscriber whose priority, side effects, and failures remain understandable alongside other modules' subscribers?
When would service decoration be safer than replacing a core service definition, and how would you test the compiled container?
How can lazy builders and placeholders isolate highly dynamic output, and what access and cacheability obligations still remain?
How would you verify that a content update invalidates every necessary layer from entity rendering to the reverse proxy or CDN?
How would you diagnose a slow View with several relationships and filters while preserving access rules and validating the resulting query plan?
How would you design a custom JSON endpoint that validates input, checks entity and field access, handles transactions, and returns appropriate failures?
How would you make a queue worker safe when a lease expires or a retry repeats an external side effect?
How would you make a long-running import resumable, observable, and bounded in memory when the remote source fails intermittently?
When would you choose high-water tracking versus track_changes, and how would you handle equal timestamps, out-of-order records, and deletions?
Why is a migration rollback not equivalent to restoring a backup, and how would you protect editorial changes and external side effects?
How would you scope a Drupal 7-to-11 migration so that content, redirects, files, access rules, and custom functionality are verified separately?
How would you prepare a Drupal 10 codebase for Drupal 11 using compatibility checks, deprecation remediation, dependency review, and regression tests?
How would you reconcile production configuration changes with version-controlled configuration without silently overwriting an editor's legitimate changes?
After a deployment changes code, database schema, configuration, and files, what makes a rollback safe or unsafe?
How would you design an external-service integration so credential rotation, timeouts, retries, and cache behavior can be changed safely?
How would you secure a feature that fetches a URL supplied by a user without allowing access to unintended internal or metadata endpoints?
Why is private file storage alone not a complete authorization design, and how would you test download access and cache behavior?
When would Drupal's Access Policy API help with dynamic permissions, and how must the policy declare the context of its decisions?
How would you keep a decoupled frontend consistent with Drupal publication, permissions, relationships, and cache invalidation rather than treating JSON:API as a raw database export?
A JavaScript widget breaks after several AJAX replacements; how would you investigate behavior attachment, once markers, detach cleanup, and stale state?
How would you preserve keyboard access, labels, errors, focus, and progressive enhancement when customizing a complex Drupal form or theme component?
What regression tests would expose access or language leaks that only appear after another user has warmed the cache?
How would you decide which service interactions can be mocked and which entity, schema, access, or cache behavior needs a kernel or browser test?
How would you resolve a Composer dependency conflict that blocks an urgent Drupal security update without deleting the lock file or bypassing platform requirements as a shortcut?
Why can copying configuration between independently installed sites fail or cause harm, and how would you handle UUIDs, dependencies, and site-specific ownership deliberately?
How would you prevent or detect lost updates when an editor and an integration modify the same Drupal entity concurrently?
When should you use route parameters, route alteration, or a route subscriber instead of generating a separate route for every content item?
How would you reduce a cache stampede around an expensive calculation without holding an unbounded lock or serving data outside its access boundary?
How would you investigate an intermittent production-only Drupal failure using correlation, logs, timings, configuration differences, and a reproducible case?
What checks would you require in a Drupal module's CI and release pipeline before deploying changes to entity behavior, configuration, access, and caching?
Drupal Interview Questions and Answers
The answers follow the same order as the question bank. They explain the Drupal mechanism, then describe its effect on a feature or failure scenario. Read examples with their stated module files, services, permissions, entity fields, and enabled dependencies in mind.
Drupal Interview Questions and Answers for Beginners
The beginner answers establish the main Drupal concepts and show how they connect. They distinguish content from configuration, explain how routes and permissions work together, and introduce the rendering and theming responsibilities behind a page.
1. What is Drupal, and when is a structured content management system a better fit than building every feature from scratch?
Drupal is an open-source content management system and application framework built with PHP. It provides structured content, editorial tools, user accounts, access controls, translation, and APIs that a team can configure and extend.
It is a strong fit when an organization manages many related content types, several editorial roles, or content reused across websites and other channels. For example, a university can model departments, courses, and staff as related records instead of maintaining independent HTML pages.
The benefit is reuse of established content-management capabilities, not freedom from engineering. A small static site or an application with almost no editorial requirements may not justify Drupal's administration and maintenance overhead.
2. How do Drupal modules and themes divide responsibility for a site's behavior and presentation?
Modules supply functionality; themes shape how that functionality is presented. A module might define an event entity, validate registrations, provide a route, and build a list of upcoming events. A theme controls the list's markup, typography, spacing, and responsive styling through templates and assets.
The boundary is architectural rather than a rule that modules cannot contain CSS or templates. Modules often provide sensible default presentation, which a theme can override. Business rules and authorization should remain in modules or their services so that changing the active theme does not change who may register or how registrations are stored. Core and contributed extension files should not be edited directly.
3. What is the difference between core, contributed, and custom modules, and how would you choose among them?
Core modules ship with Drupal, contributed modules are separately maintained community projects, and custom modules contain site-specific code owned by the project team.
Start by checking whether core already meets the requirement. For a contributed option, review compatibility with the project's Drupal and PHP versions, supported releases, security-advisory coverage, maintenance activity, dependencies, and the amount of functionality it adds. Test it against the actual requirement rather than choosing solely by download counts.
Custom code is appropriate for genuinely specific business behavior or a small integration that existing modules do not fit. It also creates a long-term testing and maintenance obligation. Whichever option is selected, use Composer to manage applicable package dependencies and avoid patching vendor files manually.
4. How do Composer and Drush serve different purposes in a modern Drupal project?
Composer manages the project's code dependencies: it resolves compatible package versions, downloads them, and records the resolved versions in composer.lock. Drush is a command-line interface for operating a Drupal site, including installing modules, importing configuration, rebuilding caches, and running database updates.
For a development project that already includes Drush, these commands illustrate the separate responsibilities:
Bash command
The first command obtains Pathauto and resolves its package dependencies; the second installs the module in Drupal's active site. Downloading code does not itself install the module. Use project-local Drush, confirm the target site, and review dependency and configuration changes before deploying the resulting release.
5. What Drupal and PHP versions should you establish before using an interview example or installing a module?
Establish the exact Drupal major and minor version, its support status, and the PHP version used by both the web server and command-line tools. Then check the module's declared compatibility, Composer constraints, and required PHP extensions.
For this October 2026 material, the baseline is Drupal 11.4.x. Its supported PHP matrix includes 8.3, 8.4, and 8.5, with PHP 8.3 as the minimum and 8.4 recommended. A project can impose tighter requirements through its dependencies, so the minimum is not a promise that every module combination works.
Examples also need version checks: plugin attributes and class-based hooks have evolved across Drupal releases. Drupal 7 code should be identified as legacy material, not presented as the default approach to a Drupal 11 project.
6. What is an entity in Drupal, and why is it incorrect to say that every piece of stored content is a node?
An entity is a typed object managed through Drupal's Entity API, with defined storage and supporting behavior. Content entities hold application data, such as nodes, users, taxonomy terms, media, and comments. Configuration entities describe configurable structures, such as content types and views.
A node is only one content entity type, commonly used for editorial pages and articles. A user account is not a node, even though it is stored in the database and may have fields. Likewise, an uploaded file has its own entity representation.
The distinction matters when selecting storage handlers, access checks, forms, and rendering APIs. Code should work with the actual entity type instead of assuming that every record has a node ID or node-specific behavior.
7. How does a content type relate to the node entity type, a bundle, and individual content items?
The node entity type defines the general model for node content. A content type is a bundle of that entity type: it groups nodes with a particular purpose and field configuration. Each individual article or event is an entity instance belonging to one bundle.
For a site that defines an event content type, the entity type is node, the bundle machine name is event, and an individual conference listing might have node ID 42. The event's date and venue fields belong to the site's configured model.
A content type's definition is configuration, while its individual nodes are content. Do not assume Article and Basic Page exist automatically: Drupal 11.4 removed them from the Standard profile and recipe.
8. How do base fields differ from configurable fields attached to a bundle?
Base fields are defined by the content entity type in code and normally exist across its bundles. Examples on nodes include the identifier, title, and publication status. Their definitions describe properties such as the field type, constraints, and whether values can be translated or revised.
Configurable fields are managed through field configuration and attached to selected bundles, often using the administration interface. An event bundle might have field_event_date, while an article bundle does not.
Field storage configuration describes shared storage characteristics, including the data type and cardinality. Bundle-level field configuration supplies settings such as a label and required status. Some base-field settings can also have bundle-specific overrides; base field does not mean every setting is permanently unchangeable.
9. What is the difference between a field widget and a field formatter?
A widget controls how a field is edited on a form. A formatter controls how that field's stored values are displayed. Both are plugin types, but they operate at different stages and can change without changing the underlying field type.
For an entity-reference field, the editing widget could be autocomplete or a selection list. Its formatter could display linked labels or render the referenced entities using a selected view mode. The editor experience and visitor experience are configured independently.
Widgets are arranged in a form display, while formatters are arranged in a view display. Hiding a field from one display is a presentation choice, not a replacement for field-level access control.
10. When should one content item reference another entity instead of duplicating its text in a field?
Use an entity reference when the related information has its own identity, lifecycle, or reuse requirements. For example, several event nodes can reference one venue entity rather than copying the venue's name, address, and accessibility details into every event.
That relationship allows a venue update to appear wherever its current data is rendered, and it supports filtering and navigation by venue. Decide which target entity types and bundles are allowed, whether the relationship is required, and whether it accepts one or several values.
Duplication can be intentional when a historical snapshot must remain unchanged, such as the address recorded on a completed transaction. A live reference is not automatically a historical snapshot, and its target still requires appropriate access checks.
11. What are taxonomy vocabularies and terms, and how would you use them to classify articles?
A vocabulary is a collection of classification terms. Terms are content entities within that vocabulary and can have descriptions, additional fields, and hierarchical relationships. A vocabulary defines a classification system; a term represents one category within it.
For an article site, create a Topics vocabulary with terms such as Accessibility, Research, and Community. Add a taxonomy-term reference field to the article bundle and restrict it to that vocabulary. Editors can then assign one or more topics, and Views can produce topic-based article lists.
Use separate vocabularies when classifications serve different purposes, such as Topics and Regions. Decide whether editors select approved terms or may create new ones; uncontrolled free tagging can produce duplicate or inconsistent categories.
12. How does a reusable Media entity differ from the underlying file it may reference?
A file entity represents a managed file and records information such as its URI, filename, and MIME type. A Media entity is a reusable content item that wraps an asset through a media source and adds editorial structure, fields, and display behavior.
For example, an Image media type can reference an image file while also carrying a credit or caption. Several pages can reference the same Media item instead of independently uploading the same asset. A Remote video media item can reference an external video URL rather than a locally stored file.
Media access and file delivery are separate concerns. Restricting a Media entity does not make a publicly accessible file URL private; sensitive assets need an appropriate file-storage and access design.
13. What does Views do, and how do a view's query and its displays work together?
Views builds configurable listings from data that Drupal exposes to the Views system. It combines a data source with filters, sorting, relationships, paging, and output settings, reducing the need to write a custom listing controller and database query.
A view can have multiple displays. For example, an Events view can provide a paginated page and a small sidebar block. Displays can share settings or override selected settings, such as the item limit or presentation format. They execute according to their own effective configuration; they are not simply two visual wrappers around one permanently stored result set.
Views UI is the administrative editor, while Views provides the runtime functionality. Verify access behavior and performance using representative users and data.
14. How do ordinary filters, exposed filters, and contextual filters differ in Views?
An ordinary filter applies a condition chosen by the view builder, such as showing only published event nodes. An exposed filter lets visitors supply a value through a form, such as choosing a region. A contextual filter takes an argument from the display's context, commonly a path parameter or a configured default value.
For a venue page, a contextual filter can limit an events listing to the current venue. The same listing might expose an event-category selector while keeping the published-status filter fixed.
Configure validation and the behavior for missing or invalid contextual arguments explicitly. Otherwise, a missing venue identifier might unexpectedly show all events. None of these filters should be treated as a substitute for entity or display access control.
15. How do a block plugin, a placed block, and reusable custom block content differ?
A block plugin is the implementation that supplies a block's behavior and renderable output. A block placed through the Block layout interface is a configured instance of a plugin, with settings such as theme region, weight, and visibility conditions. That placement is stored as configuration.
Reusable custom block content is a content entity with fields, such as a promotional message and image. Drupal exposes it for placement through block plugins, but the editorial content and the placement are different records.
For example, the same reusable promotion can appear in two regions with different placement settings. Editing its content affects those uses; changing one placement's visibility does not rewrite the promotion. Layout Builder also supports inline blocks with a different reuse lifecycle.
16. How do theme regions and Layout Builder differ as ways to arrange page content?
Theme regions are named areas of the page shell, such as header, sidebar, and footer. A theme declares its regions, and administrators place blocks into them. This is useful for site-wide elements such as navigation and a footer notice.
Layout Builder arranges sections and components within supported entity displays. A site can define a default layout for a bundle and, when enabled and permitted, let editors override the layout for an individual entity. Components can include fields and blocks.
The two approaches can coexist: a theme supplies the page shell while Layout Builder structures the main content. They also have different storage implications; a default display layout is configuration, while an individual entity's layout override belongs with that entity's content.
17. How do roles and permissions control what a Drupal user can do?
Permissions represent named capabilities, such as creating a particular content type or administering configuration. Roles group permissions, and users receive capabilities through their assigned roles. Anonymous and authenticated roles provide baseline permissions for visitors and signed-in users respectively.
An editor role might allow creating articles and editing its owner's articles without allowing module installation or permission administration. Test the role using an ordinary account rather than relying on an administrator's experience.
Apply least privilege and distinguish broad administrative permissions from narrowly scoped editorial operations. Permissions are also only part of authorization: entity ownership, publication state, workflow transitions, and entity-specific access handlers can affect whether a particular operation is allowed. A role's name alone does not grant special behavior.
18. Why is hiding a menu link or an edit button not sufficient to protect the underlying operation?
Hiding a link changes the interface, not the authorization boundary. A user or automated client can still request the underlying URL or submit a crafted request without using the visible page controls.
Protect the operation on the server through route requirements and the relevant entity or business-rule access checks. For a node-editing route, check update access to the actual node, not merely whether the caller is logged in. State-changing operations also need the appropriate request-method and CSRF protections; Form API provides supporting mechanisms for forms.
When an access result influences cached output, preserve its cacheability metadata so one user's decision is not reused incorrectly for another. Test direct requests by unauthorized accounts as well as the appearance of buttons.
19. How do revisions differ from publishing status and editorial moderation states?
A revision is a stored version of an entity's data. Publication status indicates whether content is published, while a moderation state represents a step in an editorial workflow, such as Draft, Needs review, or Published.
These concepts work together but are not interchangeable. With Content Moderation, an article can retain a published default revision while a newer draft revision is being reviewed. The newest revision is therefore not necessarily the revision anonymous visitors should see.
Workflow configuration determines the states, allowed transitions, and whether a state is published or becomes the default revision. Transition permissions control who can move content between states. Revision history supports auditing and recovery, but it does not itself define an approval process.
20. What is the difference between content translation, interface translation, and configuration translation?
Content translation manages language variants of content entities and their translatable fields, such as an article's title and body. Interface translation manages user-facing strings supplied by software, such as button labels and administrative messages. Configuration translation manages translatable configuration values, such as a site name or a field's configured label.
For a bilingual news site, an editor translates an article through content translation, the interface provides translated Save buttons, and configuration translation supplies localized display labels. Translating one category does not automatically translate the others.
The Language module establishes the site's languages and language selection. Field-level translation settings determine which values vary by language and which remain shared, so those settings should follow the editorial model rather than simply enabling every available option.
21. How do a route name, an internal path, and a URL alias differ?
A route name identifies a routing definition, an internal path is the path that definition matches, and a URL alias provides an alternative readable path. For example, entity.node.canonical can match /node/42, while an alias might be /events/community-day.
Generate links through Drupal's URL and entity APIs instead of assembling path strings. In PHP code that already has a loaded node in $node, the canonical URL object is:
PHP example
Drupal can then apply outbound path processing, including aliases and language handling, when generating the link. The alias does not create a separate content item or change its permissions. Generating a URL also does not prove that the current user may access its destination.
22. Why do formatted-text fields have a text format, and why should unrestricted HTML be limited to trusted users?
A formatted-text value includes both the entered text and a text-format identifier. The format selects the filters that process that text for display, including restrictions on allowed HTML. The rich-text editor is an editing aid; it is not the security boundary because requests can bypass it.
Unrestricted HTML can allow hostile markup or scripts to run in other visitors' browsers, so permission to use such a format should be limited to highly trusted users. Ordinary editors should receive the least permissive format that meets their needs.
Render formatted fields through Drupal's field formatters or processed-text rendering. Printing the stored raw value, especially with Twig's raw filter, can bypass the configured filtering and create a cross-site scripting vulnerability.
23. How do content, configuration, and environment-specific state differ in Drupal?
Content is the information users create and maintain, such as articles, media, users, and taxonomy terms. Configuration defines how the site behaves and is structured, including content types, field definitions, views, and role permissions. Configuration can be exported to YAML and moved through a deployment workflow.
State stores environment-local operational values that should not be synchronized as site configuration, such as a task's last-run timestamp. It is not a general substitute for content storage or a secure secrets vault.
For example, an event's venue address is content, the definition of its address field is configuration, and the last successful synchronization time is state. Production credentials belong in a controlled environment-specific secrets mechanism, not exported configuration or committed settings.
24. What information belongs in a custom module's .info.yml file, and why does its machine name matter?
A module's .info.yml file declares metadata that lets Drupal discover the extension and determine whether it can be installed. It includes the human-readable name, extension type, core compatibility, and any Drupal extension dependencies. Description and package grouping help administrators understand it.
For a custom module named event_notice, place this file at web/modules/custom/event_notice/event_notice.info.yml in a recommended-project layout:
YAML example
The machine name connects filenames, namespaces, services, and configuration ownership. Choose it deliberately rather than renaming an installed module casually. Declare third-party PHP package requirements in the module's composer.json; .info.yml is not a replacement for Composer dependency management.
25. What connects an incoming URL to a controller or form, and where is route access declared?
Drupal's router matches the request to a route definition and invokes its configured controller or form. Static custom routes normally live in the module's .routing.yml file. The route's requirements declare access conditions, while its defaults identify the handler and optional title.
For example, event_notice.routing.yml can contain:
YAML example
This assumes the module supplies src/Controller/NoticeController.php with an overview() method. A form route instead uses _form with a form class. Choose access requirements for the actual operation: a general content-viewing permission is not sufficient for administrative or entity-specific changes. Rebuild route caches after changing definitions.
26. What is a Drupal service, and why is dependency injection useful in custom code?
A service is an object managed by Drupal's service container, typically supplying reusable functionality such as logging, configuration access, or entity storage coordination. Dependency injection gives an object the collaborators it needs rather than making it locate them through global calls.
For a custom NoticeBuilder whose constructor accepts EntityTypeManagerInterface, explicit registration in event_notice.services.yml could be:
YAML example
The class belongs in the module's src/NoticeBuilder.php; the YAML alone does not implement it. Explicit dependencies make responsibilities visible and allow test doubles in unit tests. In container-created custom classes, prefer injection over repeated \Drupal::service() calls, which hide dependencies and couple code to the global container.
27. How do hooks, plugins, and event subscribers solve different extension problems?
Hooks let an extension react at defined lifecycle points or alter data supplied by another subsystem, such as modifying a form. Plugins provide discoverable implementations of a particular capability, such as a field formatter or block type. Event subscribers listen for dispatched events, often from Drupal or Symfony services.
The extension point determines the mechanism: adding a new formatter requires a formatter plugin, while changing an existing form uses the form-alter hook. Subscribing to a request event is useful when the requirement genuinely belongs to the request lifecycle.
Drupal 11 supports class-based hook implementations, but support and exceptions depend on the hook and version. Check the target API rather than assuming that all extension mechanisms are interchangeable or that every plugin uses identical discovery metadata.
28. What happens during a Form API form's build, validation, and submission stages?
Form API separates describing a form from validating and acting on a submission. A form class supplies buildForm() to define elements, defaults, and actions. Drupal processes submitted input and invokes validation, including the form's validateForm() method. Validation errors prevent normal submission handling.
When validation succeeds, submitForm() performs the intended operation, such as saving configuration or creating a record, and can set a redirect. Submitted values and processing state are accessed through FormStateInterface, not by reading raw request globals throughout the class.
Building can occur more than once, including during AJAX requests and rebuilds, so it should not send emails or save business records as a side effect. Validate authoritative rules server-side even when the browser also performs input validation.
29. Why do Drupal controllers and blocks usually return render arrays instead of printing HTML?
Render arrays describe output instead of immediately producing it. They let Drupal apply templates, attach assets, enforce supported rendering behavior, and carry cacheability metadata through the rendering pipeline. Controllers and blocks therefore remain customizable without embedding all their presentation in PHP.
For a plain, potentially untrusted string already available as $notice_text, a controller method can return:
PHP example
#plain_text escapes the string for display. A richer component can use a theme hook and structured variables instead of concatenated HTML. Data-dependent output also needs its relevant cache contexts, tags, and lifetime; using a render array does not infer every dependency automatically. Directly printing HTML bypasses this structured response-building process.
30. What is Twig responsible for in Drupal, and what application logic should remain outside templates?
Twig is Drupal's presentation template engine. It combines prepared variables and renderable content with markup, simple conditions, loops, and template composition. It should not become the place where the site queries storage, saves entities, calls remote services, or decides authorization rules.
For example, inside a node template whose content type defines field_summary, presentation can use the prepared field render array:
Twig example
Keeping the field as a render array preserves its configured formatter and associated rendering metadata. Prepare additional display variables in appropriate PHP presentation code. Drupal enables Twig autoescaping, so ordinary strings are escaped; adding |raw to make unexpected markup appear is not a safe general fix.
31. How do Twig template suggestions and preprocess code help customize presentation without editing core files?
Template suggestions give Drupal more specific template names to consider for a theme hook. For example, a custom theme can supply node--event.html.twig to change presentation for the site's event node bundle instead of changing every node template.
Preprocess code prepares or adjusts the variables passed to a template. A theme's MYTHEME_preprocess_node() implementation can add a presentation-oriented variable, while business operations and authorization remain in modules and services. Any newly introduced data dependencies still need correct cacheability metadata.
Use development-only Twig debugging to inspect the active template and available suggestions. Put overrides in the custom theme and rebuild caches after discovery-related changes. Editing a template inside core or a contributed extension makes the customization vulnerable to being overwritten by updates.
32. Why should a theme or module declare CSS and JavaScript in asset libraries instead of hard-coding script tags?
Asset libraries give Drupal a structured declaration of CSS, JavaScript, and dependencies. Attaching a library lets Drupal manage ordering, avoid repeated inclusion, and participate in asset aggregation instead of loading ad hoc script tags from templates.
For example, event_notice.libraries.yml can declare:
YAML example
The example assumes those files exist in the module and that its JavaScript uses Drupal behaviors and once. Attach event_notice/notice to the relevant render array through #attached, rather than loading it on every page unnecessarily. Declare additional dependencies such as core/drupalSettings only when the script actually requires them.
33. What different questions are answered by cache contexts, cache tags, and cache max-age?
Cache contexts answer which request conditions produce different variants of the output. For example, output that changes with permissions needs the relevant permission context. Cache tags answer which underlying data changes invalidate the cached result, such as changes to a particular node or configuration object. Cache max-age answers how long the result may remain reusable.
These are complementary. A permission-dependent listing can need contexts for access variation, tags for its content dependencies, and a time limit for externally refreshed information. A time limit alone does not separate users or invalidate changed content immediately.
Prefer cacheability metadata obtained from the actual dependencies and preserve it as rendering proceeds. Setting max-age to zero everywhere avoids useful caching rather than correcting missing contexts or tags.
34. What kinds of work belong in Drupal cron, and why is cron not a guarantee of execution at an exact time?
Drupal cron runs periodic maintenance, such as cleanup, checking for updates when the relevant functionality is enabled, and processing configured queue workers. Custom modules should keep cron work bounded and move substantial per-item processing into queues rather than attempting an unlimited import in one invocation.
Automated Cron depends on site requests and the configured interval, so a quiet site may not trigger it promptly. An external scheduler can invoke cron more predictably, but locks, execution limits, failures, and queue backlogs still affect actual completion times.
For a time-sensitive process, define an execution target, monitor successful runs, and make retryable work safe to repeat. A cron schedule by itself does not guarantee that an email or synchronization completes at an exact second.
35. Which Drupal reports and logs would you check first when a newly installed feature fails?
Start with the Status report at /admin/reports/status to check version, runtime, filesystem, database-update, and other detected installation problems. Then inspect Recent log messages at /admin/reports/dblog if Database Logging is installed, or the configured external log destination when using Syslog or another logging integration.
Match errors to the failure time, route, and user operation. PHP-FPM, web-server, and infrastructure logs can reveal failures that occur before Drupal records an application log entry. For browser-side failures, also inspect the network response and JavaScript console.
Confirm that required modules are installed, permissions are correct, and deployed configuration matches the feature. Reproduce the problem in development and collect the underlying exception before treating repeated cache rebuilds as a diagnosis.
36. What is the purpose of composer.lock, and why should a team commit it with composer.json?
composer.json declares the project's dependency requirements and allowed version ranges. composer.lock records the exact versions resolved for that project, including transitive dependencies. Committing both lets developers, CI, and deployment builds install the same resolved dependency set.
For an existing application with a lock file, composer install follows the lock file; composer update resolves dependencies again within the declared constraints and can change the lock. Updates should therefore be deliberate, reviewed changes tested before deployment, not an incidental step on a production server.
The lock file is not a complete backup or environment specification. Reproducibility also depends on compatible PHP and extensions, project code, build tooling, configuration, and any additional controlled installation inputs.
37. How would you assess and apply a Drupal security update without treating a successful download as a completed update?
Read the security advisory to identify affected versions, severity, and any special mitigation or update instructions. Compare it with the deployed dependency set, including contributed modules and libraries, rather than checking only the core version.
Create or confirm a recoverable backup, apply the compatible fixed versions in a controlled environment, and review the Composer lock-file changes. Run automated tests and focused checks of important user flows. Deployment must also execute required database updates, configuration changes, and cache rebuilds through the project's tested procedure.
Finally, verify the version actually served by production, pending updates, application health, and relevant logs. A downloaded package is only code on disk; it does not prove that the running site is updated or that the vulnerability's additional remediation steps are complete.
38. Why should a module normally be uninstalled in Drupal before its code is removed with Composer?
Uninstalling lets Drupal run the module's cleanup logic while its classes and services are still available. It updates the installed-extension state and removes or adjusts owned configuration and storage according to the module's implementation. Removing code first can leave an installed extension that Drupal can no longer load.
Before uninstalling, review dependent modules, configuration, and content. Uninstallation may delete data, and Drupal may block it until specific dependencies or records are addressed. Back up anything that must be retained.
After the uninstallation has completed, remove the package with Composer and capture the intended configuration changes. For deployments across environments, coordinate the sequence so each site's uninstall occurs while the needed code is still present; deleting a directory is not an uninstall strategy.
39. What does Drupal core's JSON:API module expose, and why does enabling it not grant clients unrestricted access?
Drupal core's JSON:API module provides standardized HTTP access to supported content entity resources and their relationships. It derives resources from the site's entity types and bundles, so a configured article bundle can be available under a resource path such as /jsonapi/node/article.
The API applies Drupal's entity and field access rules. An anonymous client does not gain permission to read unpublished content merely because the module is enabled, and authentication identifies a caller without granting extra authorization by itself.
Core JSON:API is read-only by default; write operations require configuration and appropriate permissions. Test requests as the actual client roles, including field exposure and unpublished records. Authentication, CSRF handling where applicable, and operational protections still require deliberate design for writable integrations.
40. Why should Drupal feature work use a separate development environment and a tested backup-and-restore process?
A separate development environment lets the team change code, configuration, and data structures without exposing visitors to unfinished work or accidental destructive operations. It should reproduce the relevant production versions and services while isolating external side effects such as email, payments, and outgoing integrations.
Backups need enough information to restore the site: its database, uploaded files, the matching code release and dependencies, and securely managed environment settings. Configuration exports alone do not preserve editorial content or uploaded assets.
Test restoration into an isolated environment and verify important user flows. A successful backup command does not establish recoverability. Before deployment, understand which database or content changes cannot be reversed merely by restoring an older code release, and plan recovery accordingly.
Drupal Interview Questions and Answers for Intermediate
The intermediate answers explain implementation choices and the conditions that make them safe. They trace data and access decisions through a request, identify cache dependencies, and separate reusable Drupal APIs from assumptions specific to one site's configuration.
41. Which files and namespaces would you create for a small Drupal 11 module with one permission-protected page and one reusable service?
Create modules/custom/office with office.info.yml, office.routing.yml, office.permissions.yml, and office.services.yml. Put the controller in src/Controller/ReportController.php, namespace Drupal\office\Controller, and the reusable service in src/Service/ReportBuilder.php, namespace Drupal\office\Service. Drupal maps the module's src directory to its Drupal\office namespace.
In office.routing.yml:
YAML example
Define that permission with a human-readable title in office.permissions.yml; merely naming it in the route does not create its administrative definition. The info file declares the module name, type: module, and a compatible core_version_requirement, such as ^11. Inject the service into the controller, return a render array, and rebuild discovery caches after adding routes or service definitions. A menu-link file is optional, not an access-control mechanism.
42. How would you inject an entity-type manager into a controller rather than call the global service locator throughout its methods?
Declare the dependency in the constructor and obtain it once in the controller factory. Methods then use the injected interface, making dependencies visible and allowing focused tests without repeatedly consulting \Drupal::service().
For src/Controller/ReportController.php, a controller implementing ContainerInjectionInterface can include this constructor and factory. Import that interface from Drupal\Core\DependencyInjection, EntityTypeManagerInterface from Drupal\Core\Entity, and ContainerInterface from Symfony's dependency-injection component:
PHP example
Its page method can call $this->entities->getStorage('node'); storage access still needs explicit authorization and cache-aware rendering. Keep substantial query or business logic in a separate service rather than turning the controller into an application layer. Drupal 11 also supports autowiring in relevant base classes, but an explicit factory makes the construction contract unambiguous.
43. How does a services.yml definition connect a service ID, a PHP class, and constructor arguments?
The service ID is the container lookup name; class identifies the implementation, and arguments supplies constructor parameters in order. A string beginning with @ references another service rather than passing that literal string.
In office.services.yml:
YAML example
src/Service/ReportBuilder.php should therefore declare the matching namespace and a constructor accepting EntityTypeManagerInterface followed by AccountProxyInterface, or compatible interfaces. Another service can depend on @office.report_builder; a controller factory can retrieve that same ID. Neither the machine-readable ID nor the PHP namespace is a URL.
Rebuild the container after changing definitions. Prefer constructor injection over storing the whole container, because consumers should expose the services they actually need. Tags and factories serve additional purposes and are not required merely to register an ordinary reusable class.
44. How would you load a bounded list of articles for display while making the entity query's access-check decision explicit?
Use an entity query with explicit accessCheck(TRUE), a bundle restriction, deterministic sorting, and a bounded range. For a public article list, publication status is an additional business filter, not a substitute for access checking.
Inside a service with an injected entity-type manager:
PHP example
The query returns IDs; loadMultiple() loads their entities without a separate load call in every iteration. Preserve the query's order when assembling output, and use view builders plus cacheable access results for presentation. Add list-level cache tags and the access/filter contexts affecting membership. Calling accessCheck(FALSE) is an explicit bypass appropriate only to a separately authorized trusted process, not a performance shortcut for visitor-facing lists.
45. How would you create or update a node through the Entity API while accounting for field values, validation, and operation-level access?
Obtain node storage from an injected entity-type manager. Before creating an article, check the node access handler's createAccess('article', $account); before updating an existing node, check its update access for the acting account. Check edit access for each field that external input may change, and allowlist those fields rather than copying an arbitrary request payload.
After those checks, the core write sequence is:
PHP example
For an update, load the entity and call set() on allowed fields before validation. Entity save() does not automatically perform user authorization or run every validation constraint for callers. Handle violations as useful field-level errors, respect moderation and revision policy, and verify the selected text format before accepting formatted text.
46. How would you render an entity in a view mode without losing access decisions, field presentation, or cache metadata?
Ask the entity-type manager for the appropriate view builder and pass the entity and view mode. The view builder uses configured field formatters, display settings, and render metadata; manually concatenating raw field values bypasses those responsibilities. Check entity access separately because obtaining a view builder does not itself grant permission to view an entity.
With injected entity-type manager and account services:
PHP example
Passing the access-result object to #access preserves its cacheability, including when output is suppressed. Keep the returned value as a render array so nested fields, configuration dependencies, and attached libraries can bubble normally. Choose the correct translation before rendering, and retain field access checks when adding custom presentation outside standard formatters.
47. When would you implement a custom field type, widget, or formatter, and which responsibility belongs to each?
A field type defines the stored data model: properties, storage schema, constraints, and what counts as an empty value. A widget defines how editors enter that data in a form. A formatter defines how existing field values become display output. They are separate plugin types, so a new display requirement rarely justifies inventing a new storage model.
For a structured geographic coordinate, a custom field type might store latitude and longitude with range constraints; a widget could provide two inputs or a map picker; a formatter could produce a map or accessible coordinate text. If core already supplies a suitable field type, implement only the missing widget or formatter.
Place plugins under the module's corresponding src/Plugin/Field/FieldType, FieldWidget, or FieldFormatter namespace. Verify attribute support for the plugin manager on the target release. Formatters should return render arrays with access, cacheability, and library attachments rather than pre-rendered HTML strings.
48. How would you define a simple custom block plugin with a PHP attribute in Drupal 11?
Place the class in office/src/Plugin/Block/OfficeNotice.php. Drupal's block plugin manager supports PHP attributes on the Drupal 11 baseline; the attribute supplies discovery metadata, while build() supplies renderable output.
PHP example
After rebuilding plugin discovery, an administrator can place this plugin as a configured block in a theme region. The plugin definition and that placement are different objects; declaring the class does not automatically display it everywhere. This example has no user-specific or external data. When real output depends on configuration, entities, permissions, or a remote response, supply the corresponding dependencies and cache contexts rather than retaining the simple example's assumptions.
49. How does dependency injection into a block plugin differ from constructing an ordinary service?
A block plugin is created by a plugin manager, which supplies its configuration array, plugin ID, and plugin definition. An ordinary container service is constructed from its service definition and does not have those plugin-instance inputs.
A portable explicit pattern is to implement ContainerFactoryPluginInterface in the block and add a factory with this shape:
PHP example
Import Symfony's ContainerInterface and Drupal's plugin factory interface. The constructor accepts those first three parameters plus EntityTypeManagerInterface, passes the first three to parent::__construct(), and stores the service. Do not instantiate the block as though it were an ordinary service or omit its configuration. Inject only required dependencies; obtaining a current-user service does not automatically declare the block's cache variation.
50. How does Drupal convert a route parameter into an entity, and why does successful conversion not prove the user may access it?
A route parameter converter replaces a matched identifier with the appropriate entity object before the controller runs. Explicit parameter options make that contract clear, and an entity access requirement independently specifies the permitted operation.
In a module's routing file:
YAML example
The controller can accept NodeInterface $node; it need not load the same numeric ID again. A nonexistent entity normally prevents successful conversion, but an existing unpublished node can still be forbidden to the requester. Therefore, existence and authorization remain separate checks. Add other route requirements when the feature needs a custom permission as well. Do not treat conversion as field-edit authorization, and do not reuse a view-protected route for a state-changing operation.
51. How should a custom access check return an AccessResult and preserve the dependencies of its decision?
Return an AccessResultInterface object rather than collapsing the decision to a Boolean. Its allowed, forbidden, or neutral state expresses the access decision, while cache contexts, tags, and max-age describe when that decision may be reused.
For a custom route check using an injected configuration factory:
PHP example
Import Drupal\Core\Access\AccessResult. The permission helper supplies permission-based variation; the configuration dependency invalidates the decision when the setting changes. Use andIf() or orIf() to compose results without discarding their metadata. An ownership rule also needs per-user variation and the entity dependency. Neutral means this check does not grant access; it is not equivalent to a positive grant. Preserve dependencies on denied paths too, and avoid using max-age zero as a blanket substitute for identifying them.
52. How would you implement a small FormBase form that rejects invalid input before any data is saved?
Extend FormBase in src/Form/QuantityForm.php, implement a unique getFormId(), and build a required number element plus a submit button in buildForm(). Give the number element #min => 1, #max => 100, and #step => 1, but enforce the domain rule server-side rather than trusting browser controls.
With FormStateInterface imported from Drupal\Core\Form, the validation method can be:
PHP example
Put persistence in submitForm(), using an injected storage/application service, not in buildForm() or the validation callback. Form API does not proceed to normal submission while validation errors remain. Protect the route with the required permission, and recheck operation-specific authorization before a sensitive write.
53. How would you build a configuration form with ConfigFormBase and distinguish editable configuration from read-only configuration?
Extend ConfigFormBase, implement getFormId(), and return the owned configuration names from getEditableConfigNames(). Build elements from those settings and call the parent's buildForm() to retain the standard actions. In a small office.settings form, the editable-name method returns ['office.settings'].
Its submit method can explicitly save a validated value:
PHP example
Here, config() returns editable configuration because the name is declared editable by this form. Elsewhere, the configuration factory's get() returns an immutable, override-aware object for reads, while getEditable() intentionally accesses mutable stored configuration. Do not save environment overrides back into shared configuration. Define defaults in config/install, schema in config/schema, and a restrictive route permission. If overriding the constructor on Drupal 11, preserve both configuration-factory and typed-configuration-manager dependencies.
54. How would you update a dependent form element with AJAX while preserving form state and server-side validation?
Add #ajax to the controlling element, giving it a callback and the HTML ID of a wrapper around the dependent element. During each form rebuild, derive the dependent options from $form_state->getValue() and server-side data; the callback returns the rebuilt subtree rather than constructing an unrelated response.
In the subclass's buildForm() method, configure the AJAX behavior and wrapper:
PHP example
Add this callback method to the same class, importing FormStateInterface:
PHP example
The region select belongs inside that container. Preserve valid selections, and clear a selected region when it no longer belongs to the chosen country. Final validation must reject forged country/region combinations even if the browser displayed only valid options. Do not save data inside the AJAX callback. Provide a usable non-JavaScript path and verify labels, errors, and focus after replacement.
55. How would you protect a custom state-changing route against CSRF, and why is a permission check alone insufficient?
A permission check answers whether an account may perform an operation; CSRF protection helps establish that a cookie-authenticated request was intentionally initiated through the application rather than forged by another site. Use Form API for ordinary browser writes, retain its token handling, and never perform state changes on GET.
For a custom authenticated JSON action, a route fragment can require both permission and the request-header token:
YAML example
A session-authenticated client obtains the token from /session/token and sends it as X-CSRF-Token with the session cookie. The header checker is not itself an authentication mechanism and does not protect every possible authentication scheme identically. Use the correct protection for the selected scheme, restrict authentication providers deliberately, validate inputs, and check entity/field access. A CSRF token never substitutes for those authorization checks.
56. How would you alter a specific form without editing its original module, using Drupal 11's supported hook mechanisms?
Use a targeted hook_form_FORM_ID_alter() implementation rather than editing the defining module or affecting every form indiscriminately. Drupal 11.1 introduced class-based module hooks; the Drupal 11.4 baseline supports a Hook attribute on a method in the module's src/Hook directory.
For office/src/Hook/ArticleFormHooks.php:
PHP example
Verify the actual form ID; add and edit forms may not share it. A supported procedural implementation in office.module is also possible, but do not register the same alteration twice. Preserve existing validation and submit handlers when extending behavior. Hook discovery, attribute support, and exceptional lifecycle hooks must be checked against the exact target core version, especially when maintaining Drupal 10 compatibility.
57. How would you move a new content type and view from development to production without copying production content backwards?
Export the development site's configuration, review the resulting YAML diff, and commit the content-type, field, display, and View configuration with its dependencies. Content types and Views are configuration entities; the article nodes shown by the View are content and are not moved by an ordinary configuration import.
Deploy the matching code and dependencies, run required database updates, import the reviewed configuration, rebuild caches, and verify representative production paths. Use a staging environment to catch missing modules, incompatible schema, and unintended deletions before release. The normal synchronization workflow assumes environments belonging to the same site, including matching site identity.
Do not overwrite production's database to install a content type. Likewise, a production database copy used for development must be authorized, sanitized where necessary, and treated separately from the configuration deployment. Reconcile legitimate production configuration changes before importing so that an export does not silently erase them.
58. How would you separate environment-specific endpoints and secrets from configuration that is exported to version control?
Keep portable behavior in exported configuration and environment-specific values in an explicit override layer. A non-secret endpoint may have a default in office.settings; deployment infrastructure can override it in settings.php without changing the synchronized YAML.
For example, after validating the environment variable during deployment:
PHP example
Normal configuration reads see the override, while configuration exports preserve the underlying stored value. This distinction explains why an administration form and runtime behavior can differ.
Obtain credentials from the hosting platform's secret facility or another approved credential provider, and inject a service that retrieves them when needed. Keep secrets out of exports, example defaults, logs, rendered settings, and repository history. Document which values are required in each environment, fail clearly when they are absent, and test credential rotation without exposing the new value.
59. What does configuration schema describe, and how does it support typed data, translation, and validation?
Configuration schema describes the shape and meaning of configuration values: mappings, sequences, scalar types, translatable strings, and applicable validation constraints. It lets Drupal interpret configuration as typed data instead of treating every YAML value as an unstructured string.
In office/config/schema/office.schema.yml:
YAML example
Corresponding defaults belong in config/install/office.settings.yml, not in the schema. The label type marks a short translatable string, while boolean describes a real Boolean value. Schema also supports configuration translation and validation tooling, and custom constraints can express stronger rules. A schema declaration alone does not mean every arbitrary set()->save() call has automatically run all validation. Test completeness and constraints through the relevant configuration validation workflow.
60. How would you choose among configuration, state, private temporary storage, and cache for different kinds of non-content data?
Choose storage by ownership, portability, and lifetime rather than by whichever API is easiest to call.
Storage | Suitable example | Important boundary |
|---|---|---|
Configuration | A portable report setting | Exportable; keep secrets out. |
State | The last successful local synchronization time | Environment-local operational data, not deployed settings. |
Private tempstore | A user's unfinished multi-step wizard | Temporary, owner-scoped data with expiration. |
Cache | A recalculable remote response | May disappear or become stale; never the only durable copy. |
Use injected configuration, state, tempstore, or cache services as appropriate. Private tempstore is not a general permanent-content store, and cache keys must account for authorization boundaries when cached data is user-specific. Define expiry and cleanup behavior instead of assuming temporary data lasts indefinitely. If information is durable business content that needs fields, ownership, revisions, or entity access, model it as an entity rather than forcing it into one of these stores.
61. How do Twig auto-escaping, the raw filter, and quoted HTML attributes affect the safety of a template?
Twig auto-escaping makes ordinary untrusted string values safe for their intended HTML output context. The raw filter bypasses that protection and must not be used to make user input โlook correct.โ Drupal render arrays and text-format processing are the appropriate route for intentionally formatted content.
In a Twig component template, with label and description supplied as plain strings:
Twig example
Quote attribute values: escaping a value does not make an unquoted attribute safe against every character that can alter HTML structure. Use Drupal's attribute objects and URL/link APIs when constructing more complex attributes or links. HTML escaping also does not validate URL schemes or make text safe inside arbitrary JavaScript or CSS contexts. Keep executable behavior in attached libraries and pass structured data through the supported settings mechanisms. Never add |raw simply to suppress visible escaping.
62. If preprocess code adds data from another entity or configuration object, how should its cache dependencies reach the rendered output?
Carry the dependency objects into a render array that actually participates in rendering, rather than passing only their scalar values to Twig. A related entity, configuration object, and access result can each contribute different invalidation or variation rules.
In preprocess code, this assumes $config, $related, and its $access result were obtained through injected services with the required access checks:
PHP example
Import Drupal\Core\Cache\CacheableMetadata and render {{ notice }} in the template. The access-result object retains its metadata even when the element is denied. If a condition prevents constructing or printing the child entirely, attach that condition's dependencies to the containing rendered element instead. Avoid assuming that loading an entity or reading configuration automatically invalidates every parent template that used one of its values.
63. How would you attach JavaScript behavior to both initial and AJAX-inserted markup without binding the same handler repeatedly?
Implement a Drupal.behaviors attachment rather than relying only on document-ready. Drupal invokes behaviors for the initial document and newly inserted markup; once() marks elements already initialized so repeated attachments do not duplicate handlers.
In office/js/notice.js:
JavaScript example
Declare the file in office.libraries.yml with dependencies on core/drupal and core/once, then attach that library to the relevant render array. The selector should identify an accessible interactive control if clicking changes behavior. Respect the supplied context rather than rescanning the whole page. Widgets that allocate timers, external listeners, or third-party instances also need appropriate detach cleanup when AJAX removes or moves their elements.
64. Why can adding a relationship to a View duplicate rows, and how would you choose between correcting the relationship, aggregation, or a different display?
A relationship changes the query's join cardinality. If one article references three taxonomy terms, joining those terms can produce three rows for that article. Adding another multivalue relationship can multiply the rows further; the duplicates are often a predictable relational result rather than a rendering bug.
First define the intended result: one row per article, one per article-term pair, or a summary per term. Correct an unintended relationship or constrain the related records when only one match is wanted. Aggregation is appropriate for a defined grouping and aggregate calculation, but every selected field must fit that grouping. DISTINCT cannot collapse rows whose selected related values genuinely differ.
A rendered-entity display or a separate related-content component may better represent multivalue data. Inspect the generated query, pager totals, sorting, and empty relationships. Do not hide duplicate markup while leaving an incorrect query and pagination in place.
65. How do a View's access setting and its data filters differ, and why must you preserve entity-access enforcement in its query and output?
A View's access setting controls who may reach that display, such as requiring a permission before viewing a report. Its filters control which records match, such as published articles in a category. Neither a display permission nor a publication filter necessarily implements every entity-access rule applying to those records.
Preserve Views' normal entity/query access integration and avoid disabling SQL rewriting or replacing the query with unchecked SQL merely to get more results. Relationships and custom query alterations need review because they can expose related information or change how access restrictions apply. Field-based displays also need scrutiny when a custom field handler reads data outside normal entity rendering.
Test the display as anonymous users and accounts with different permissions and grants, including unpublished or restricted content. Verify direct page and attachment displays, pager counts, and warm-cache behavior. Configuration that hides a link is not equivalent to protecting the View's route or output.
66. What cache context would a block need if its message depends on the current user rather than only their permissions?
Use the user cache context when the message differs by individual user ID. user.permissions can distinguish permission sets, but two accounts with identical permissions can still have different names, preferences, or assignments.
For a render array assembled by a service with the relevant account entity already loaded:
PHP example
Import CacheableMetadata from Drupal\Core\Cache. The context separates users; the entity dependency invalidates cached output when that user's displayed data changes. Those solve different problems. Add language or other dependencies if they also affect the result. Per-user variation reduces cache sharing, so isolate a small personalized component when practical rather than making unrelated page regions user-specific. Do not remove required variation merely to improve the hit rate.
67. Why might a cached list remain stale when a new matching entity is created, even if every displayed entity's cache tag was added?
Tags for currently displayed entities invalidate output when those entities change, but a newly created matching entity did not exist in the cached result. The list therefore needs a dependency representing the collection and its membership, including the empty-list case.
Use the entity type's list cache tags rather than guessing only individual IDs. Import Drupal\Core\Cache\CacheableMetadata for this service-method excerpt:
PHP example
This broad node-list dependency is safe but can invalidate more lists than necessary. Use supported bundle-specific or custom membership tags when their invalidation contract is defined and implemented correctly. Retain the displayed entities' own tags, filter-related dependencies, and access contexts as well. A list must refresh when membership changes because of insertion, deletion, publication, permissions, or relevant field updates; repeatedly clearing all caches only conceals an incomplete dependency model.
68. How do cacheability and attached assets bubble through nested render arrays, and what can go wrong when you render too early?
As Drupal renders children, it collects their cache contexts, cache tags, and max-age into the containing render operation. Attached libraries and settings also travel with the rendered output. Contexts and tags are combined, while the effective max-age is constrained by the shortest applicable lifetime.
Keeping an entity teaser, a custom notice, and their attachments as child render arrays lets the renderer perform that bookkeeping. Replacing them with concatenated HTML strings too early can lose the relationship between the output and its dependencies, particularly when rendering occurs in an isolated context and its bubbleable metadata is discarded. It can also interfere with placeholders and deferred work.
Return render arrays from controllers, blocks, and formatters whenever possible. If an integration genuinely requires a rendered string, use the correct render context and explicitly preserve the resulting bubbleable metadata on the eventual response. Rendering early is not inherently a cache fix or an optimization.
69. How do Internal Page Cache, Dynamic Page Cache, and render caching differ in the work they reuse?
Render caching reuses output for a component, such as an entity view or block, using its cache keys and metadata. It can avoid rebuilding that component even when Drupal still needs to handle the surrounding request.
Dynamic Page Cache reuses cacheable page responses across requests while respecting cache contexts and supporting placeholders for dynamic portions. It benefits both anonymous and authenticated traffic when the response is eligible. Highly personalized fragments can remain separate instead of preventing reuse of every surrounding element.
Internal Page Cache is an earlier whole-page cache primarily for eligible anonymous requests. It is not a general solution for arbitrary anonymous personalization: its page-cache behavior does not interpret all render cache contexts as separate anonymous page variants. Such variation needs a deliberate cache policy and appropriate handling.
These layers complement each other. Inspect the relevant response headers and component metadata when diagnosing a miss or leak; disabling every cache layer prevents learning which dependency or policy is wrong.
70. How would you describe a migration's source, process pipeline, destination, and source-ID definition?
A migration's source plugin reads external rows and defines their source IDs. The process section maps or transforms source properties into destination properties, and the destination plugin writes the resulting records. Source IDs must be stable and unique, including every component of a composite key; they are how the migration map recognizes an existing source record later.
A migration definition using a custom office_articles source plugin could contain:
YAML example
Here the source plugin, not this abbreviated YAML, implements its ID definition and row iterator. Test transformations, required fields, language, revision policy, and validation deliberately. Choose execution tooling compatible with the installed Migrate ecosystem; defining a migration does not itself schedule or run an import.
71. How would migration_lookup and migration dependencies preserve references when source and destination entity IDs differ?
migration_lookup resolves a source identifier through another migration's map table and returns the destination identifier it created. This preserves references even when source term 12 becomes destination term 87; copying the number 12 directly would point to the wrong entity or nothing.
In an article migration that depends on a taxonomy migration:
YAML example
The dependency establishes the prerequisite relationship, while the lookup performs the ID translation. no_stub: true avoids silently creating placeholder destination entities when no mapping exists. Define what missing references mean: skip the row, leave an optional field empty, or record an actionable failure. Composite IDs and multivalue fields need the correct input shape and possibly a sub_process pipeline. Verify migration maps and referenced entities rather than assuming run order alone establishes referential integrity.
72. How would a client request related resources and paginate a JSON:API collection without assuming one response contains every accessible item?
Request related resources with include, using the actual relationship machine names exposed for the resource type. Drupal's JSON:API collection endpoints use resource paths such as /jsonapi/node/article; a request can combine include=field_category with page[limit]=20. Related accessible objects appear in included, while relationships retain their resource identifiers.
Treat pagination links as authoritative: consume the returned page, follow links.next when present, and continue until there is no next link. Do not assume that the requested limit is the number returned or that one response contains the whole collection. Access filtering can produce a short page, and data can change between requests. A response excerpt can retain a next link even when data is empty:
JSON example
Deduplicate included resources by their (type, id) identity, handle missing or inaccessible relationships, and preserve authentication consistently across requests. Add a stable sort appropriate to the application and define how a long-running client handles concurrent changes. Use the JSON:API media type and inspect error responses instead of treating every body as a successful collection.
73. What must you verify before enabling authenticated JSON:API writes, including permissions, read-only mode, and the authentication method?
Confirm that JSON:API write operations are intentionally enabled; core's read-only mode blocks writes even when an account otherwise has entity permissions. Then verify bundle-specific create, update, and delete permissions, field-level edit access, text-format access, and any moderation rules for the intended integration account.
Choose and test an authentication mechanism rather than assuming JSON:API supplies one automatically. Session-cookie authentication requires the appropriate CSRF token for unsafe requests. HTTP Basic requires its authentication provider and TLS; bearer-token approaches require a compatible provider and careful token scope and storage. The protection requirements depend on how credentials are sent, so a token header and a session cookie are not interchangeable designs.
Send valid JSON:API documents with the expected media type, resource type, UUIDs, and relationship identifiers. Test unauthorized fields, malformed input, unpublished content, expired credentials, and error status codes. Grant the integration only the operations it needs; enabling writes should never mean granting an administrative role.
74. When would you move work from a page request into a queue worker, and what must happen before a claimed item is considered complete?
Move work into a queue when it is slow, retryable, or not required to finish the current response, such as synchronizing an entity to an external service. Enqueue a compact identifier and necessary version/context rather than a large serialized entity that may become stale.
A consumer claims an item with a lease, loads current data, performs the operation, and marks the item complete only after the required result is durably established. With the normal cron queue runner, a worker's successful return lets the runner delete the item; exceptions must not be swallowed into a false success. A custom consumer must delete the claimed item itself after success.
A crashed worker or expired lease can cause processing again, so design idempotent effects or use a durable deduplication key. Set bounded timeouts, distinguish retryable failures from permanent invalid input, and monitor queue age and failure rates. A queue is not a guarantee of immediate execution.
75. How does the Batch API help a user-triggered bulk operation, and how is its purpose different from a background queue?
Batch API divides a user-triggered operation into bounded steps across requests while showing progress and a final result. It suits an administrative action such as rebuilding selected records when doing all the work in a single request would exceed execution limits.
Register operations and a finished callback with batch_set(). Each operation receives a context containing results and, for multi-pass work, a sandbox that tracks progress. Process a limited chunk, update the cursor and completion fraction, and let the next request continue rather than looping over the entire dataset immediately.
A background queue decouples processing from the interactive workflow and requires an independent consumer. Batch progress in a browser does not guarantee that work continues if the workflow is abandoned, nor does it automatically give operations exactly-once behavior. Check permissions, preserve resumable state where required, and make repeated steps safe. Report partial failures honestly instead of presenting a completed progress bar as proof that every item succeeded.
76. How would you log a failed external request with useful context while avoiding credentials, personal data, and misleading success messages?
Use an injected, named logger channel and a stable message with structured placeholders. Record enough to correlate the failed attempt: a safe job ID, approved upstream name, error category, response status when available, elapsed time, and retry decision. Those fields are more useful than an unstructured โsomething failedโ message.
With a Psr\Log\LoggerInterface injected for the integration channel:
PHP example
Keep authorization headers, cookies, tokens, URL query secrets, response bodies, and unnecessary personal data out of logs. Raw exception messages can contain request details, so sanitize them rather than assuming they are safe. Log a retry only when one is actually scheduled, and log success only after the required operation succeeds. Give users a useful non-sensitive error while retaining a correlation ID for investigation.
77. How do database update hooks, post-update functions, configuration import, and Drush deploy fit into a release?
Database update hooks in a module's .install file perform versioned storage/schema changes and must work with the known prior state. Post-update functions in .post_update.php run after the database updates and are suited to data or entity changes that need the updated system APIs. Neither is a substitute for deploying the intended configuration snapshot.
Configuration import then applies reviewed exported configuration, including dependencies and deletions. Code and Composer dependencies must already match the release before these steps run. Drush 13's deployment command coordinates database updates, configuration import, cache rebuild, and deploy hooks for work that depends on the imported configuration, followed by cache warming on Drupal 11.2 and later. Verify the sequence for the installed Drush version.
Back up affected state, test the full sequence on a representative copy, and record failures before continuing. Changing default YAML in config/install does not automatically update existing active configuration. A failed mid-deployment update also does not imply that reverting code alone restores a coherent site.
78. When would you choose a unit, kernel, functional, or FunctionalJavascript test for a custom Drupal feature?
Choose the smallest test that exercises the behavior honestly. A unit test covers isolated PHP logic with controlled collaborators and no Drupal kernel. A kernel test boots Drupal services and selected modules, making it useful for entity storage, configuration schema, plugins, and service integration without a browser.
A functional test based on BrowserTestBase exercises HTTP routes, permissions, forms, and rendered HTML through a non-JavaScript browser. A FunctionalJavascript test based on WebDriverTestBase uses a real browser for behavior that requires JavaScript, such as AJAX replacements, client-side widgets, and focus changes.
For a permission-protected AJAX form, unit-test its pure validation helper, use a kernel test for storage rules where valuable, then cover denied requests and submission through functional tests and the dynamic interaction through a JavaScript test. Do not mock away the access, schema, or cache behavior under examination. Include warm-cache and multiple-account cases where output is personalized.
79. How would you select and render the appropriate entity translation while accounting for language fallback and cache variation?
Use the injected entity.repository service's getTranslationFromContext() rather than assuming the requested language exists and calling getTranslation() unconditionally. The repository considers the requested or current content language and Drupal's configured fallback candidates. Handle an unavailable result where the installed API permits one.
Check view access on the selected entity translation, then pass it and the intended language code to the entity view builder. Keep that access result and the entity's metadata attached to the render output. A translated label taken as a scalar loses those relationships unless they are reattached explicitly.
Vary by languages:language_content when the content-language context controls selection, and by interface language when interface text varies independently. If a route or custom negotiation input chooses the language, retain the relevant dependency too. Test an available translation, a missing translation with fallback, a restricted translation, and cached requests switching languages; the right text on an empty cache is not sufficient verification.
80. How would you investigate repeated entity loads or remote calls inside a render loop before adding more caching?
Measure the loop first: count entity queries and loads, record remote request counts and latency, and compare cold- and warm-cache paths. Repeated method calls are not necessarily repeated SQL queries because entity storage may already have an in-request cache; inspect actual I/O rather than guessing from the code alone.
Gather referenced IDs and use loadMultiple() when a bounded bulk load removes an N+1 pattern. Move invariant configuration reads or service calculations outside the loop, avoid loading the same entity again in preprocess, and use a remote bulk endpoint when its contract supports one. Keep network timeouts bounded and move nonessential external work out of rendering.
Then cache only the remaining expensive reusable result, with the correct authorization boundary, invalidation tags, variation, and expiry. Measure again to verify both reduced work and correct output. Adding persistent cache around an unbounded loop can hide the problem until every cache miss becomes a production incident.
Drupal Interview Questions and Answers for Experienced
The experienced answers weigh maintainability and operational risk alongside performance. They explain how to gather evidence, choose boundaries for custom code, and manage changes without assuming that a cache rebuild or a successful local request proves the design is correct.
81. When would you model a business object as a node bundle, a custom content entity, configuration, or an external record?
Model the object's lifecycle and ownership first, rather than starting with a table. A node bundle fits editorial material that benefits from established authoring, revisions, translations, moderation, and display tooling. A custom content entity fits a distinct business object, such as a service entitlement, whose operations and access rules do not match ordinary publishing; its administrative experience and integrations still need implementation.
Use configuration for deployable definitions, such as a fulfillment strategy or workflow settings, not for customer orders. A configuration entity is appropriate when multiple independently identified definitions need dependencies and administration; simple configuration suits a small settings object. Keep runtime counters and synchronization checkpoints out of exported configuration.
Retain an external record when another system owns the authoritative lifecycle. Drupal can store a stable identifier and an explicitly managed projection. Document synchronization, deletion, permission, revision, and outage behavior before choosing this boundary; avoiding duplication can be more valuable than forcing everything into nodes.
82. How would you design and test tenant-specific content access across entity pages, Views, JSON:API, and cached output?
Tenant isolation must be enforced below individual page controllers. Establish trusted tenant membership and an entity access policy, including create, update, delete, field access, and administrative exceptions. For node content, evaluate node grants for query filtering; a custom entity access handler alone does not automatically filter every collection query. Ensure Views, entity queries, JSON:API collections, relationship references, and direct entity requests apply equivalent restrictions.
Cache access results and rendered output by every relevant decision input. A custom tenant cache context requires a registered implementation; membership changes also need invalidation dependencies. Tenant identity alone is insufficient when permissions differ inside a tenant. Never trust an unvalidated request header to select another tenant.
Test two tenants with overlapping roles, an anonymous visitor, and a privileged account. Warm caches in both request orders, then test individual resources, listings, counts, exports, related entities, and denied responses. Revoking membership must remove access without waiting for a global cache clear.
83. How would you change a field or custom entity schema that already contains production data without assuming a cache rebuild performs the migration?
A cache rebuild refreshes definitions and discovery; it does not safely transform stored business data. Compare the installed schema with the proposed definition, inventory existing values, and rehearse the transition on a representative database copy with a verified restoration path.
Prefer an expand-and-contract change: add compatible storage, backfill in bounded batches, switch readers and writers, validate the result, then remove obsolete storage in a later release. Preserve translations, revisions, cardinality, and field references during the backfill. Changing a populated field's type in place is not generally a supported shortcut.
Use explicit update functions and the appropriate entity-definition update APIs for supported schema operations. Freeze the definitions needed by an update rather than assuming today's application classes match the intermediate database. Use post-updates for suitable entity-data work once schema updates are complete. Persist batch progress, make retries safe, and test both a fresh installation and upgrades from each supported prior schema.
84. How would you diagnose a moderation workflow where a translated draft unexpectedly changes the published experience in another language?
Trace the exact revision and translation being loaded, not just the node ID. Compare the default revision, latest revision, moderation state, language negotiation, and the revision affected by the translation edit. A preview route, a View configured for revisions, and the public canonical page may legitimately select different records.
Next inspect field translatability. A field shared across translations is not an independent value for each language, so editing it can affect the wider entity. Review the workflow's restrictions on editing shared fields, transition permissions, and custom save handlers. Check whether custom code incorrectly promotes a draft to the default revision or renders the latest revision publicly.
Reproduce with a published English and French entity, create a French-only draft, and compare public responses before and after each transition. Repeat with warm caches and both language orders. Assert that publication, shared-field behavior, and cache variation match the agreed editorial rules; do not mask a revision-selection defect by disabling caching.
85. How would you make scheduled or time-sensitive content become visible on time across render caches, anonymous page caches, and a CDN?
Treat the publication instant as an operational event as well as a cache lifetime. Store the intended time consistently, run a scheduler or worker frequently enough for the required tolerance, and have it perform the publication transition through the entity APIs. That change must invalidate entity and listing dependencies, including pages where the item was previously absent.
For output calculated directly from time, set its render-cache maximum age to the next relevant boundary, not an arbitrary long duration. However, a fragment's max-age does not by itself guarantee expiry in Internal Page Cache or a CDN. Configure and verify downstream response policy and tag-based purge or explicit invalidation for those layers.
Warm the anonymous page and CDN before the deadline, then request the same URL just after it. Measure scheduler delay and purge propagation separately. Add missed-job monitoring and safe retries; a precise timestamp in configuration cannot compensate for a scheduler that only runs when traffic arrives.
86. How would you reduce an exploding number of cache variants without combining outputs that different users are not allowed to share?
Measure which cache contexts create the variants and which fragments introduce them. Full-user, session, entire-query-string, and unrestricted cookie variation can multiply entries rapidly. Replace an overly broad context only after proving a narrower one captures every meaningful output and access difference. Permission-based variation is appropriate for permission-dependent output, but not for an account-specific balance or ownership decision.
For example, a directory filtered only by one query parameter can use url.query_args:department instead of varying by the complete query string. Normalize and validate the accepted department values to avoid unbounded combinations. Preserve language, tenant, and access dependencies when they still affect results.
Separate a personal notification counter from a broadly reusable page using an appropriate lazy builder and placeholder. Keep the counter's own access checks and metadata intact. Compare hit rates, cache size, and response time after the change, then run cross-user warm-cache tests. Fewer variants are not an improvement if they merge security boundaries.
87. An anonymous visitor sees another visitor's cookie-dependent content after the cache warms; how would you trace and repair the cache boundary?
First determine which layer returned the wrong response: CDN, reverse proxy, Internal Page Cache, Dynamic Page Cache, or a rendered fragment. Reproduce with two separate anonymous cookie jars and alternate which one warms the same URL. Record cache headers and the response body without logging sensitive cookie values.
A cookie cache context can distinguish render-cache variants, but Internal Page Cache assumes anonymous pages are shared and does not honor arbitrary render cache contexts. A CDN also needs its own explicit variation or bypass policy. Adding cookies:segment to a block therefore is not a complete repair.
For harmless personalization, consider a shared page shell with a separately fetched, appropriately cache-controlled fragment. Alternatively, bypass shared caching for the affected response or implement a carefully bounded, consistently configured variant at every shared layer. Recheck authorization independently of the cookie. Purge already contaminated entries and verify both visitor orders, missing cookies, changed cookies, and direct fragment requests.
88. How do allowed, forbidden, and neutral access results combine, and why must their cache metadata survive an andIf or orIf operation?
Drupal access results are three-valued decisions with cacheability, not ordinary booleans. Allowed grants access, forbidden is an explicit veto, and neutral supplies no grant. With andIf(), both operands must be allowed to produce allowed; absent a forbidden result, other combinations are neutral. With orIf(), either allowed result can grant access only when neither operand is forbidden. Forbidden dominates both operations.
The composition methods preserve the cacheability needed for the combined decision. Do not reduce results to booleans and reconstruct an allowed result without their contexts, tags, and maximum age. An ownership check, permission check, or membership dependency can otherwise disappear from cached output.
PHP example
Here the calling access checker already has the entity and account. Tests should cover all three outcomes and the returned metadata, including a denied result that later changes after a dependency update.
89. How would you modernize annotation-based plugins while checking whether their plugin managers support PHP attributes?
Convert plugins according to their discovery manager, not by replacing every annotation mechanically. Identify the plugin type, the module that provides its manager, the supported Drupal versions, and the attribute class expected by that manager. Attribute support is widespread in current core, but a contributed or custom manager may still use annotation discovery.
For a supported type, translate definition properties into the attribute constructor's actual parameter names and types. Preserve the plugin ID, derivative behavior, context definitions, dependencies, and translatable labels. Import the correct attribute namespace; a similarly named annotation class is not interchangeable. Leave unrelated documentation comments in place.
Clear discovery caches in a development environment, inspect the discovered definition, and instantiate the plugin through its manager. Compare configuration and runtime behavior before and after conversion. Add discovery tests across the module's declared compatibility range. If the manager needs modernization first, treat that as a separately tested compatibility change rather than silently dropping existing third-party plugins.
90. When should a reusable custom feature expose a plugin type instead of one service, a hook, or an event?
Expose a plugin type when the feature needs multiple discoverable implementations with a common contract and a meaningful selection mechanism. Shipping-rate calculators are a good example: each provider can have an ID, configuration, capabilities, and its own implementation while the checkout selects one or several providers.
A single injected service is simpler when there is one application responsibility and no need to discover interchangeable implementations. A hook fits an established Drupal extension point, often including alteration of supplied data. An event fits notification of an occurrence or a documented interception point. Neither automatically provides plugin discovery, configuration, or selection.
For a new plugin type, define a small interface, manager, discovery mechanism, dependency-injection approach, and configuration schema where applicable. Specify how missing plugins and incompatible configuration fail. Avoid making implementers depend on incidental internal objects. Test a second independent implementation early; it exposes whether the contract is genuinely extensible or merely mirrors the first implementation's details.
91. How would you design an event subscriber whose priority, side effects, and failures remain understandable alongside other modules' subscribers?
Give the subscriber one documented responsibility and register it through Drupal's service container with the event_subscriber tag. Inject collaborators instead of looking them up globally. Choose the event according to what data and guarantees exist at that lifecycle stage, and check whether it also fires for subrequests or repeated processing.
Symfony invokes higher-priority listeners first. Use a nondefault priority only to satisfy an explicit ordering requirement; inspect the other registered subscribers and test the resulting order rather than relying on module installation order. Stop propagation only when the event's contract permits taking exclusive control.
Keep slow remote calls out of latency-sensitive request events when asynchronous delivery is acceptable. Durable queued work needs idempotency and a clear relationship to the database commit. Define which failures should reject the operation and which should be logged for retry. Test duplicate events, another subscriber modifying the event, and collaborator exceptions, so failure behavior is not an accidental consequence of dispatch order.
92. When would service decoration be safer than replacing a core service definition, and how would you test the compiled container?
Decoration is useful when adding behavior around an existing service while preserving its contract, such as timing an integration client. Replacing the definition discards the original implementation and can conflict with another module's assumptions. A decorator receives the original as an inner service and delegates operations it does not intentionally change.
YAML example
This assumes portal.client exists and TracingClient implements its interface with matching constructor arguments. For a core service, first confirm the interface is an appropriate extension boundary and inspect existing decorators. Document decoration priority when order matters.
Unit-test delegation and failure propagation, then boot a kernel with the actual module set. Fetch the public service ID, assert the expected interface and wrapper behavior, and check for circular dependencies. A YAML parse alone cannot establish that container compilation, aliases, constructor wiring, and competing decorators work together.
93. How can lazy builders and placeholders isolate highly dynamic output, and what access and cacheability obligations still remain?
A lazy builder defers constructing a render subtree until rendering needs it. Placeholdering lets Drupal cache the surrounding reusable page while resolving a highly dynamic fragment separately; BigPipe can improve how eligible placeholders are delivered. This is useful for a per-account notification panel on otherwise shared documentation pages.
Use a trusted callback, such as a method explicitly declared through TrustedCallbackInterface, and pass supported scalar or null arguments. Avoid embedding a particular user's sensitive data in reusable placeholder markup or arguments. Resolve request-specific identity safely when building the fragment.
The callback still must check entity and field access and return a render array with correct cache contexts, tags, maximum age, and attachments. Denied and empty results also have dependencies. A placeholder is neither an authorization mechanism nor a guarantee that a CDN can safely cache the final personalized response. Test the complete page-cache path, direct access to any fragment endpoint, and repeated requests from different accounts before treating the shell as universally reusable.
94. How would you verify that a content update invalidates every necessary layer from entity rendering to the reverse proxy or CDN?
Start with one controlled content change and map every dependent representation: canonical page, teasers, Views listings, related-content blocks, language variants, JSON responses, and CDN objects. Warm them first and capture cache diagnostics. Entity view builders normally supply entity dependencies, but custom render code can lose them through early rendering or manual string assembly.
Check entity and configuration tags at the fragment and response boundary. Listings require list dependencies even when empty, because creating the first matching entity must invalidate the empty result. Verify that changing a referenced entity invalidates pages displaying that reference's values.
Then inspect the proxy integration: Drupal tags must be translated into the CDN's supported surrogate-key or purge mechanism. Drupal does not automatically control an arbitrary CDN. Observe purge delivery, retries, propagation latency, and headers rather than assuming a successful entity save proves freshness. Repeat for creation, update, unpublish, and deletion, and verify that purge failure cannot leave restricted content publicly available beyond the agreed safety window.
95. How would you diagnose a slow View with several relationships and filters while preserving access rules and validating the resulting query plan?
Separate SQL execution time from entity loading, access evaluation, rendering, and remote work triggered by field formatters. Capture the actual View configuration, generated query, parameters, count query, and a representative slow request. Compare cold and warm cache behavior without turning off access checks to manufacture a faster result.
Inspect the query plan on a safe representative database. Look for multiplied rows from relationships, unnecessary joins, expensive grouping or distinct operations, unselective filters, and sorts that cannot use an index. Match proposed indexes to the real predicates and ordering, accounting for their write cost. Use execution-based analysis only where its workload is safe and authorized.
Reduce unnecessary relationships or fields, improve pagination, and inspect repeated per-row entity loads. Keep node grants, language, revision, and publication constraints intact. Validate result identities and totals across roles before comparing latency again. If adding result caching, include its access and filter variation plus invalidation dependencies; cached incorrect results remain incorrect.
96. How would you design a custom JSON endpoint that validates input, checks entity and field access, handles transactions, and returns appropriate failures?
Define a narrow write contract: permitted HTTP methods, authentication mechanism, request size, accepted fields, and response shape. Reject malformed JSON and unknown or immutable fields rather than assigning the whole payload to an entity. For cookie-authenticated writes, apply the appropriate CSRF protection as well as authorization.
Check create or update access, field edit access, and access to referenced entities. Apply input transformations deliberately and validate entity constraints before saving; programmatic save() is not an automatic authorization or validation boundary. Use injected services and a database transaction for local changes that must succeed together. Roll back on failure, but do not assume that transaction undoes an email or remote API call; coordinate those through a durable outbox or equivalent design.
Return consistent failures: malformed input, unauthenticated or forbidden access, missing resources, validation violations, and concurrency conflicts should be distinguishable without exposing private details. Prevent shared caching of sensitive write responses, log a correlation identifier, and test retries, partial failures, and unauthorized field changes.
97. How would you make a queue worker safe when a lease expires or a retry repeats an external side effect?
Design for duplicate execution even when the queue normally processes each item once. A worker can finish a remote operation and crash before acknowledging the item, or another worker can claim it after the original lease expires. Increasing the lease reduces overlap but does not establish exactly-once delivery.
Assign a stable operation identifier and send it as the remote service's idempotency key when supported. Maintain a durable local record with a uniqueness constraint, status, attempts, and remote outcome. A timeout after submission is an unknown outcome: query or reconcile with the provider before blindly repeating a non-idempotent action.
Keep each job bounded, classify retryable failures, and use capped backoff with jitter and an operator-visible terminal failure state. A lock can reduce concurrent work but is not the final correctness guarantee, since locks expire. Acknowledge only after the required durable outcome is established. Test crashes before submission, after remote success, and before local completion recording.
98. How would you make a long-running import resumable, observable, and bounded in memory when the remote source fails intermittently?
Separate fetching, transformation, and persistence, with a durable checkpoint that advances only after the corresponding work is committed. Use stable source identifiers and a migration map or equivalent import ledger so a retry updates the same destination instead of creating duplicates. Retain enough source-version information to distinguish a repeated page from a genuine later update.
Fetch bounded pages or stream records rather than accumulating the full export. Process small batches, release references, and reset relevant entity storage caches where appropriate in a long-running process. Check that the HTTP client and source plugin do not secretly buffer the entire feed. Keep remote calls outside long database transactions.
Use timeouts, rate-limit handling, capped retries, and explicit failed-record quarantine with a replay path. Record processed, skipped, failed, and remaining counts, checkpoint age, batch duration, and memory high-water usage without logging secrets. Test interruption mid-page, expired cursors, duplicate delivery, and remote outages; restarting should resume predictably and produce the same reconciled result.
99. When would you choose high-water tracking versus track_changes, and how would you handle equal timestamps, out-of-order records, and deletions?
Use a high-water property when the source supplies a trustworthy increasing change value and can return records in the required order. Drupal's standard high-water comparison selects values above the saved boundary, so coarse timestamps and late-arriving changes can be missed. Sorting equal timestamps alone does not rescue an update that arrives later with the already-saved value.
Prefer a monotonic change sequence where possible. Otherwise implement and test an explicit overlap-and-deduplicate or compound-cursor strategy in the source integration; do not assume standard high-water configuration supplies those semantics.
Use track_changes when rescanning source rows and comparing their hashes is practical and more reliable than source timestamps. Exclude irrelevant volatile values from the tracked representation where the plugin design permits. Standard source configuration treats high_water_property and track_changes as mutually exclusive.
Neither approach automatically synchronizes deletions. Handle tombstones or perform a separately authorized reconciliation, distinguishing a genuinely deleted record from one missing because of permissions, pagination errors, or an incomplete source response.
100. Why is a migration rollback not equivalent to restoring a backup, and how would you protect editorial changes and external side effects?
A migration rollback invokes the destination plugin's rollback behavior for mapped records; it does not restore a point-in-time copy of the site. Depending on the destination and map state, it can delete imported entities or preserve existing ones. It does not generally reconstruct every previous field value, editorial revision, file state, or related business operation.
Before import, define which system owns each field and whether updates may overwrite local edits. Use destination overwrite restrictions where supported, retain source-to-destination mappings, and record a reconciliation report. Preserve editorial changes through snapshots, revisions, or a tested restoration process rather than assuming rollback is selective undo.
External effects need separate compensation or prevention: deleting an imported order cannot unsend a notification or reverse a provider's transaction. Suppress inappropriate side effects during migration and track legitimate ones idempotently. Rehearse rollback on a copy that includes post-import edits and shared references. For broad restoration, use coordinated, restore-tested database and file backups with an explicit recovery-point decision.
101. How would you scope a Drupal 7-to-11 migration so that content, redirects, files, access rules, and custom functionality are verified separately?
Treat Drupal 7-to-11 as a migration and rebuild, not a Composer version change. Inventory content types, fields, users, files, languages, revisions, aliases, redirects, access rules, integrations, and custom modules. Decide what to retain, redesign, archive, or replace before estimating the implementation.
Create separate acceptance tracks. Content needs counts, sampled values, relationships, translation and publication checks. Files need existence, checksums where appropriate, access behavior, and derivative regeneration. URLs need an alias and redirect map with representative crawl checks. Authorization needs role and tenant scenarios, not merely copied permission labels. Custom functionality needs independent behavioral tests because Drupal 7 APIs do not become compatible through data migration.
Build repeatable migrations with stable source identifiers and dependency ordering, then rehearse a full load and final delta. Plan write ownership, cutover, validation, and recovery with editors and operations. Keep the old source protected during transition; Drupal 7's ended community support is a reason to reduce exposure, not to skip migration verification.
102. How would you prepare a Drupal 10 codebase for Drupal 11 using compatibility checks, deprecation remediation, dependency review, and regression tests?
First bring the site onto a supported, fully updated Drupal 10 release and resolve pending database updates. Inventory custom code, contributed modules, themes, patches, Composer plugins, and integrations. Check the exact target Drupal 11 requirements against the production PHP, database, extensions, and tooling, not just the developer laptop.
Use Upgrade Status and deprecation-aware static analysis to find obsolete APIs, then review findings alongside automated tests. Replace removed APIs, review plugin discovery compatibility, and confirm supported releases of contributed dependencies. A permissive version constraint or automated compatibility patch is not evidence of functional compatibility.
Resolve the dependency set in a branch and preserve the resulting lock file. Rehearse deployment on a recent sanitized database copy, including schema updates and configuration changes. Exercise editorial workflows, translations, access, forms, integrations, and warm-cache behavior. Compare output and operational metrics with a baseline, document restoration or forward-fix options, and schedule the upgrade before the source release's support window closes.
103. How would you reconcile production configuration changes with version-controlled configuration without silently overwriting an editor's legitimate changes?
Capture production's active configuration before importing anything, and compare it with both the last deployed snapshot and the proposed release. This three-way comparison distinguishes legitimate production edits from intended code-branch changes. Review deletions and dependency changes as carefully as changed scalar values; a full import can remove configuration absent from the synchronization set.
Ask the responsible owner to resolve conflicting intent, then recreate or merge approved changes in the development workflow, export, review, and commit them. Avoid blindly committing a full production export, which can import unrelated drift. Check effective configuration separately from stored configuration because environment and language overrides can obscure the source of a value.
Rehearse the reconciled import on a representative copy and inspect the final diff. Establish ownership rules for settings editors may change at runtime versus deployable site structure. Frequently edited business content should usually be modeled as content rather than continually fighting configuration imports. Preserve the predeployment snapshot for audit and recovery.
104. After a deployment changes code, database schema, configuration, and files, what makes a rollback safe or unsafe?
A rollback is safe only when the restored code and all persistent state agree. Reverting a Git commit does not undo a column removal, transformed entity values, imported configuration, deleted files, or a message already sent to another system. Drupal update hooks are forward changes, not automatically reversible migrations.
Before deployment, identify irreversible steps and define a compatible recovery path. Expand-and-contract schema changes can preserve compatibility with the previous release; otherwise restoration may require a coordinated database and file snapshot plus the matching code artifact. Decide how to handle legitimate writes received after that snapshot. Maintenance mode alone does not stop queues, CLI jobs, or integrations.
Record completed deployment steps and stop dependent work on failure. Rehearse restore or forward-fix procedures, including configuration, workers, file availability, cache invalidation, and health checks. Resume traffic only after verifying access and critical workflows. For external effects, use reconciliation or compensating operations; a local backup cannot make those systems forget the deployment.
105. How would you design an external-service integration so credential rotation, timeouts, retries, and cache behavior can be changed safely?
Wrap the provider behind an injected client interface so controllers, forms, and workers do not own HTTP or credential policy. Keep nonsecret settings, such as timeouts and allowed endpoints, in typed configuration, while retrieving credentials from an approved secret mechanism or environment-specific override. Never commit secrets to configuration exports or include them in logs.
Support credential rotation deliberately: avoid indefinitely retaining old tokens in long-lived workers, define refresh behavior, and distinguish authentication failure from transient transport failure. Configure connection and overall timeouts, bounded retries, backoff, and provider rate limits. Retry writes only with suitable idempotency or reconciliation semantics.
Cache responses according to their ownership and freshness requirements. Include tenant, account, parameters, and provider identity where they affect data; a cache key containing only the endpoint can leak private results. Do not treat an error response as a valid empty success. Test rotation during processing, expired credentials, timeouts after submission, outage fallback, and invalidation after remote data changes.
106. How would you secure a feature that fetches a URL supplied by a user without allowing access to unintended internal or metadata endpoints?
Treat an untrusted URL as an SSRF boundary, not merely a valid string. Prefer accepting a provider identifier and resource ID, then constructing a URL from an allowlisted endpoint. If arbitrary URLs are essential, restrict schemes and ports, reject embedded credentials, and validate the parsed destination with a well-maintained URL and address implementation.
Block loopback, private, link-local, reserved, and metadata destinations across IPv4 and IPv6. Validate every redirect or disable redirects. DNS resolution can change between validation and connection, so a one-time hostname check is insufficient; use an appropriately constrained fetch service or egress proxy that enforces the policy at connection time, backed by network-level restrictions.
Apply connection, total-time, response-size, and decompression limits. Do not forward the user's session cookies or internal authorization headers. Fetch in an isolated context, validate the returned media type, and sanitize any displayed content. Test alternate address forms, DNS changes, redirects, oversized responses, and inaccessible hosts without probing real internal services.
107. Why is private file storage alone not a complete authorization design, and how would you test download access and cache behavior?
Private storage prevents ordinary public-file delivery only when the web server or object store is configured correctly. It does not decide which user may download a particular file. The Drupal download path must evaluate the applicable file, field, and parent-content rules, including unpublished content, shared references, and custom ownership policies.
Inspect the modules participating in hook_file_download() and any custom download controllers. That hook uses its documented headers, denial, and no-op return contract; it does not accept an AccessResult object. Custom response paths must still handle authorization and response caching deliberately. Ensure accelerated file delivery or signed object-store URLs do not bypass the intended checks or remain valid longer than acceptable.
Test the actual file URL as anonymous, authorized, unauthorized, and recently revoked users, not just whether a download link appears. Warm caches in both user orders and inspect Cache-Control, CDN behavior, range requests, and derivatives. Confirm the underlying private directory is inaccessible directly and avoid exposing sensitive filenames in error responses.
108. When would Drupal's Access Policy API help with dynamic permissions, and how must the policy declare the context of its decisions?
The Access Policy API helps when permissions depend on context beyond static role assignments, such as a trusted organization membership or operating window. It calculates permissions for an account and scope, so ordinary permission checks can use the resulting policy rather than scattering special cases throughout controllers.
Declare unconditional variation through getPersistentCacheContexts() and attach corresponding metadata to calculated permissions; AccessPolicyBase helps carry those contexts forward. Add conditional contexts and dependencies when the calculation needs them. Membership records and configuration need invalidation tags, while time-limited permissions need an appropriate lifetime or boundary invalidation. A custom context must have a real registered implementation.
Do not use user.permissions inside the permission calculation: it depends on the calculation itself and creates recursion. Likewise, policy-derived permissions are not a replacement for entity-specific ownership or field access. Test allowed and denied accounts, context changes, membership revocation, and warmed permission caches. Ensure a context change cannot reuse a permission set calculated for a different boundary.
109. How would you keep a decoupled frontend consistent with Drupal publication, permissions, relationships, and cache invalidation rather than treating JSON:API as a raw database export?
Define a content contract covering publication state, language, revision selection, resource UUIDs, relationships, and the identities under which requests run. JSON:API uses Drupal's entity and field access; it is not an unrestricted table export and cannot repair an insecure custom access handler. Keep write support disabled unless the application needs and secures it.
Model the frontend's empty, denied, missing, and unpublished states explicitly. Included relationships can have different access rules from the parent, and visible results may not fill the requested page size. Do not assume an integer database ID is the resource UUID or that a publicly cached API response can contain preview data.
Propagate content changes through every frontend cache, including CDN and build-time copies. Use authenticated, retryable invalidation notifications or a documented freshness strategy, and test unpublishing as carefully as publishing. Preview tokens, tenant membership, and user-specific data require isolated caching. Contract tests should cover related-entity changes, revoked access, translated content, and stale frontend output after a Drupal update.
110. A JavaScript widget breaks after several AJAX replacements; how would you investigate behavior attachment, once markers, detach cleanup, and stale state?
Reproduce several AJAX replacements and count widget instances, event listeners, timers, and outstanding requests. A behavior's attach() runs repeatedly and receives a context; code that scans the whole document or binds the same listener each time can duplicate work. Declare the library's core/drupal and core/once dependencies and use the current once() API rather than legacy jQuery helpers.
Store widget state against the actual element, not an ID that may be reused by replacement markup. Inspect whether replacement HTML carries stale once markers or whether initialization failed after marking an element. Clearing every marker globally is not a safe repair.
Implement detach() cleanup for the relevant lifecycle: destroy instances, remove external listeners, cancel timers and requests, and release references when content unloads. Do not confuse serialization with removal; form widgets may need to synchronize values instead of destroying themselves. Test replacement during an in-flight request so an old callback cannot update the new widget or steal focus.
111. How would you preserve keyboard access, labels, errors, focus, and progressive enhancement when customizing a complex Drupal form or theme component?
Preserve Form API's semantic structure before customizing its appearance: labels, descriptions, required indicators, validation errors, grouping, and stable associations between controls and help text. Render the actual form elements rather than recreating inputs from raw values in Twig. This also avoids losing hidden fields, tokens, submitted values, or library attachments.
Use native buttons, inputs, and links for their intended behavior. Complex widgets need documented keyboard interaction, visible focus, and correctly named controls. After AJAX updates, move focus only when necessary, preserve a sensible tab order, and announce relevant status or error changes without repeatedly interrupting screen-reader users. Avoid replacing the focused element without a deliberate recovery strategy.
Keep server-side validation authoritative and provide a usable non-JavaScript path where the feature allows it. Twig autoescaping should remain enabled; accessibility work is not a reason to concatenate unsafe markup. Test keyboard-only operation, screen readers, zoom, contrast, error recovery, and repeated AJAX updates alongside automated accessibility checks. Automated checks cannot establish that the interaction is understandable.
112. What regression tests would expose access or language leaks that only appear after another user has warmed the cache?
Build a request matrix in which users differ along one decision axis at a time: permission, ownership, tenant membership, content language, and interface language. Include anonymous sessions and privileged users. Request the identical URL first as one identity to warm caches, then as another, and reverse the order without clearing caches between requests.
Assert both permitted content and absence of forbidden titles, field values, links, counts, and related resources. Exercise entity pages, Views, JSON:API, denied responses, and initially empty listings. Then mutate a dependency: revoke membership, unpublish content, edit a translation, or create the first matching item. Verify the next request reflects that change.
Kernel tests can inspect access-result and render-array metadata directly. Functional tests should verify real response bodies and cache behavior with the relevant cache modules enabled. Add deployment-environment tests for proxy or CDN layers that the test browser does not reproduce. A cold-cache assertion alone will not expose a result incorrectly reused across identities.
113. How would you decide which service interactions can be mocked and which entity, schema, access, or cache behavior needs a kernel or browser test?
Mock boundaries whose behavior is outside the code under test, such as a remote client, clock, or notification transport. Keep the contract explicit and cover failures as well as successful calls. Avoid mocking the very Drupal behavior the test is intended to prove: a fabricated entity-access result cannot demonstrate that the real handler enforces ownership.
Test scope | Appropriate evidence |
|---|---|
Unit | Transformation logic, retry decisions, collaborator contracts |
Kernel | Service wiring, entity storage, schema, access metadata, plugin discovery |
Functional | Routes, authentication, forms, permissions, real HTTP responses |
FunctionalJavascript | AJAX lifecycle, browser state, keyboard and focus behavior |
Use the smallest layer that exercises the actual risk. An entity schema change needs installation and upgrade fixtures, not only mocked storage. Cache-leak fixes need multiple identities and warmed responses. Keep integration tests focused by enabling required modules and controlling external services, then retain a few end-to-end cases for the critical user journeys.
114. How would you resolve a Composer dependency conflict that blocks an urgent Drupal security update without deleting the lock file or bypassing platform requirements as a shortcut?
Identify the exact patched release required by the advisory, then inspect why the existing dependency graph excludes it. Check root constraints, contributed packages, patches, development dependencies, and the actual deployment platform. Preserve the lock file as the reproducible baseline; deleting it broadens the change and hides the original conflict.
In a development checkout, set TARGET_CORE_VERSION to the reviewed target release before these diagnostic commands.
Shell example
Resolve the specific blocker with a supported compatible dependency release or a reviewed alternative. Permit related dependency updates deliberately, inspect the lock-file diff, and keep core's coordinated packages consistent with the project's packaging approach. Do not bypass PHP requirements or security policy merely to satisfy the solver.
Build and test the resulting artifact, including database updates and critical access workflows, before deploying it. If compatibility prevents immediate remediation, document the exposure and obtain approval for an advisory-supported mitigation while completing the update path.
115. Why can copying configuration between independently installed sites fail or cause harm, and how would you handle UUIDs, dependencies, and site-specific ownership deliberately?
Full configuration synchronization is designed for environments representing the same site, not an arbitrary merge of two independently installed sites. Site UUID validation helps prevent accidental cross-site imports. Changing a UUID merely to bypass that check does not reconcile conflicting configuration identity, dependencies, content references, or ownership.
Inventory the desired shared feature and its dependency graph: modules, themes, field storage, bundles, Views, permissions, and any content dependencies. Separate these from site-owned settings such as identity, integrations, and editorial structure. A full synchronization set can delete configuration absent from the source, making a casual copy particularly risky.
For a new environment of the same site, use the supported configuration-based installation or cloning workflow. For independently owned sites, package reusable functionality deliberately through an appropriate module or recipe and review its application semantics. Test on a copy, inspect proposed additions, changes, and removals, and preserve site-specific decisions. Configuration schema improves validation and translation metadata but does not solve cross-site identity conflicts.
116. How would you prevent or detect lost updates when an editor and an integration modify the same Drupal entity concurrently?
Define which system owns each field and whether simultaneous changes should merge or conflict. An integration that loads an entity and later saves its entire stale copy can overwrite an editor's work, even when both saves are individually valid. Revisions provide history but are not, by themselves, an atomic concurrency check.
Carry an expected version or revision identifier with the write and compare it against the current persisted value inside a concurrency-control mechanism. A simple read-compare-save sequence still races unless competing writers participate in a suitable lock or atomic database condition. For an HTTP integration, an enforced precondition or version field can reject stale updates; do not assume every Drupal endpoint implements that contract automatically.
After acquiring a bounded lock, reload current data, update only integration-owned fields, validate, and save a new revision where appropriate. Locks protect only cooperating writers and can expire. Test two overlapping submissions, retries, editor conflicts, and lock expiry, then expose a clear conflict-resolution path instead of silently choosing the last writer.
117. When should you use route parameters, route alteration, or a route subscriber instead of generating a separate route for every content item?
Use a parameterized route when content items share the same handler and access model. Creating a route per record makes routing rebuilds track content churn and adds avoidable complexity. Path aliases can supply friendly URLs without turning every alias into a separate application route.
YAML example
This assumes the declared controller exists. Parameter conversion loads the node; _entity_access supplies the view check. The controller still needs appropriate field and additional report-specific access checks and cacheability.
Use route alteration or a route subscriber to modify existing route definitions during route building, for example to change a controller or requirement. Keep request-specific user decisions out of that build phase. Dynamic route providers fit genuine configuration-driven route structures, not ordinary entity enumeration.
118. How would you reduce a cache stampede around an expensive calculation without holding an unbounded lock or serving data outside its access boundary?
Cache the expensive result under a key that includes the exact data and access boundary it represents. On a miss, attempt a short, bounded lock for that same key, then recheck the cache after acquiring it because another worker may already have populated the value. Release the lock in a finally path and bound the calculation itself.
If lock acquisition fails, use a controlled wait-and-recheck, defer work, or return an acceptable degraded response. Do not let every request perform the calculation anyway. Background refresh and modest expiry jitter can reduce synchronized misses, but require durable scheduling and observability.
Serving stale data is acceptable only under an explicit freshness and authorization policy. Never reuse another tenant's value or ignore invalidation caused by revoked access. Attach data dependencies and preserve the result's cache contexts and maximum age. Measure lock contention, refresh duration, errors, and hit rate. Test worker crashes and lock expiry; an expired lock means overlapping calculations remain possible, so writes must still be safe.
119. How would you investigate an intermittent production-only Drupal failure using correlation, logs, timings, configuration differences, and a reproducible case?
Start with a narrow failure window and a correlation identifier that links the incoming request, application logs, database timings, queue jobs, and outbound calls. Record the release version, route, relevant operation, and exception chain without storing credentials, full cookies, or unnecessary personal data. Separate error rate from latency and resource saturation so unrelated slow requests do not become false leads.
Compare production with the nearest reproducible environment: effective configuration and overrides, PHP extensions, dependency lock, database version, cache and session backends, worker concurrency, proxy headers, and file permissions. Include deployment timing and cache state; an intermittent failure may require a warmed cache, a specific account, or overlapping jobs.
Build a minimal sanitized reproduction from the evidence and change one factor at a time. Use bounded, temporary diagnostic instrumentation with a removal plan rather than exposing verbose errors publicly. Add a regression test at the failing boundary, deploy the verified correction, and confirm the relevant error and latency signals recover.
120. What checks would you require in a Drupal module's CI and release pipeline before deploying changes to entity behavior, configuration, access, and caching?
Require a reproducible artifact from the reviewed lock file, dependency security checks, coding standards, static analysis, and tests on the supported PHP and database matrix. Distinguish a clean installation from an upgrade: both must succeed, with realistic preexisting entity data, translations, revisions, and configuration dependencies.
Exercise entity and field access, validation, route requirements, and negative cases. Cache tests should cover different users and languages, warm-cache ordering, initially empty lists, and invalidation after changes. Verify service and plugin discovery, configuration schema, configuration-import diffs, and any JavaScript interaction affected by the release.
Rehearse the deployment sequence on a representative copy. Database updates and post-updates run before configuration import; deploy hooks handle suitable work after import. Follow the installed Drush version's documented sequence, including supported cache warming, rather than inventing an order.
Finally require a tested recovery decision, protected secrets, operational checks, and an observable rollout. Smoke tests should verify critical workflows and authorization after deployment, with clear stop criteria for failures instead of treating a successful build as release completion.
Drupal Documentation and Further Reading
Examples target Drupal 11.4 unless an answer states another requirement. Use a compatible PHP version, Composer dependency set, and contributed-module release; Drupal 11 requires PHP 8.3 or later within its supported compatibility range. Earlier Drupal releases and prerelease branches can differ in APIs and requirements. Examples may be file or method excerpts and require the stated module, services, permissions, fields, and configuration. Source review and syntax checks do not establish a working Drupal installation or verified runtime behavior; test changes in the intended site environment.
Use these curated references to verify Drupal APIs, configuration behavior, rendering, caching, access control, and development workflows. Match API documentation and change records to the site's core release, and check contributed-module requirements separately.
Similar Posts
