Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Practice: A Drupal Developer Review

Test your Drupal knowledge with code review exercises on themes, modules, access, security and deployment, plus an interview-style question set and a runnable review checklist.

This final lesson is practice. Read each snippet as a code reviewer: what is wrong, why does it matter, and how do you fix it? The problems come from the themes, modules, security and deployment chapters. Drupal cannot run on this site, so the snippets are read-only; the last TryIt turns a review checklist into a small linter in JavaScript that you can extend.

Exercise 1: a template

HTML
<div class="teaser">
  <h2>{{ label }}</h2>
  <div>{{ node.body.value|raw }}</div>
</div>

Problems: |raw prints the stored body without escaping, which opens cross-site scripting if an editor or attacker controls the body; {{ attributes }} is missing on the outer element, so classes from modules are lost; the title lacks a link. Fix: print {{ content.body }}, which applies the text format's filtering; use <article{{ attributes }}> and link the label with {{ url }}. See Twig basics.

Exercise 2: a preprocess function

PHP
function sunrise_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['author_count'] = \Drupal::database()
    ->query("SELECT COUNT(*) FROM node_field_data WHERE uid = " . $node->getOwnerId())
    ->fetchField();
}

Problems: a database query per rendered node (a list of 50 teasers runs 50 queries); string concatenation in SQL; the result is not cacheable metadata-aware, so the count may be stale. Fix: compute it once per request in a service with static caching or cache the value with a tag, use placeholders, or show it through a View. See preprocess and performance.

Exercise 3: a route

YAML
mymodule.delete:
  path: '/mymodule/delete/{id}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\Main::delete'
  requirements:
    _access: 'TRUE'

Problems: public access to a destructive action; deletion on GET with no CSRF token; the id is not restricted. Fix: _permission or _entity_access: 'node.delete', _csrf_token: 'TRUE', id: '\d+', and ideally a confirmation form (ConfirmFormBase). See routes.

Exercise 4: a block

PHP
public function build() {
  $name = \Drupal::currentUser()->getDisplayName();
  return ['#markup' => "Hello $name"];
}

Problems: output depends on the current user but declares no cache context, so one user's name may be served to others; the display name is concatenated into #markup; static \Drupal:: call in a class. Fix: '#markup' => $this->t('Hello @name', ['@name' => $name]), add getCacheContexts() { return ['user']; }, inject current_user. See plugins and caching.

Exercise 5: access

PHP
function mymodule_node_access($node, $op, $account) {
  if ($node->bundle() == 'secret' && !$account->hasPermission('view secret')) {
    return FALSE;
  }
  return TRUE;
}

Problems: hooks must return AccessResult objects, not booleans; returning TRUE/allowed for every other node can override restrictions from other modules (an allow overrides neutral, but should never be given blindly); no cache metadata. Fix: return AccessResult::forbiddenIf(...)->cachePerPermissions() for the secret type and AccessResult::neutral() otherwise. See access control.

Exercise 6: deployment

A teammate changed a view on production and then deployed from Git; the change disappeared. Cause: configuration lives in the database, and drush config:import replaced it with the older YAML. Fix: treat Git as the source of truth, make changes in development, export, review the diff and deploy with drush deploy; use config:status to detect drift; protect production settings with Config Split or read-only overrides. See deployment.

A checklist as a linter

Reviewers repeat the same checks. This stand-in scans code strings for several of the mistakes above. Run it, then add your own rules.

Node.js Stand-in: a tiny Drupal code-review linter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real projects use PHPCS with the Drupal standards, PHPStan with mglaman/phpstan-drupal and Twig linting (drush twig:lint style tools) for this, but the mechanism is the same: encode the review you keep repeating.

Question bank

Answer these aloud, as in an interview. Short model answers follow.

  1. What is the difference between configuration and content? Configuration describes site structure and settings and is exportable; content is created by users and lives in each environment's database.
  2. How does Drupal pick a Twig template? It builds a list of suggestions from specific to general and uses the first existing file in the theme chain, then modules, then core.
  3. When do you use a hook and when an event subscriber? Use whichever the API documents: entities, forms and themes use hooks; request handling, routing and configuration use events.
  4. What does a service container give you? Lazily created, shared objects declared in YAML and injected through constructors, replaceable and testable.
  5. Name the three parts of cache metadata. Tags (dependencies), contexts (variations) and max-age (time).
  6. How are permissions assigned? To roles; users receive roles; user 1 and the administrator role bypass checks.
  7. How do you prevent SQL injection? Use the query builder or placeholders; never concatenate input.
  8. What does drush deploy run? updatedb, config:import, cache:rebuild and deploy:hook.
  9. Why can access be denied when no module says no? Neutral results mean denied; someone must allow it.
  10. How would you speed up a slow Views page? Tag-based caching, fewer fields and relationships, indexed filters, pagers, loadMultiple instead of N+1 loads, a CDN for anonymous traffic.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which problem is most serious in a template that prints node.body.value|raw?

    Raw output bypasses escaping and text-format filtering.
  2. 2. Which fix belongs in a block that depends on the current user?

    The context keeps one visitor's version from being served to another.
  3. 3. A config change made on production vanishes after deploy. What is the likely cause?

    Exported files are the source of truth for import.
  4. 4. What is the safest way to build a delete link?

    Destructive actions need access checks, CSRF protection and confirmation.

Summary

  • Review for escaping, placeholders, access requirements, cache metadata and injected services.
  • Treat Git as the source of truth for configuration and deploy with drush deploy.
  • Encode repeated review checks as lint rules.
  • You now have the building blocks to theme, extend, secure, cache and deploy a Drupal site; return to the track page for the earlier chapters.

Next: Back to the Drupal tutorial