Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: A Notes Module from Scratch

Build a complete custom Drupal module: info file, permission, route, controller, form, service, block plugin, cache tags and a test plan, with a JavaScript stand-in of the whole flow.

In this project you write one coherent module, tutorial_notes, that uses most of the module chapter: a permission, a route and controller, a form, a service holding the logic, a block and cache tags. Notes are stored in a small custom database table, which also shows the Schema API. Drupal cannot run on this site, so the code is for your local Drupal and shown read-only; the TryIt blocks are JavaScript stand-ins of the data flow so you can check the logic first.

The plan

Piece Purpose
tutorial_notes.info.yml Declare the module
tutorial_notes.permissions.yml add notes, view notes
tutorial_notes.install Create the tutorial_notes table
src/NoteRepository.php (service) Insert and read notes, invalidate cache
src/Form/NoteForm.php Add a note
src/Controller/NotesController.php List notes on /notes
src/Plugin/Block/RecentNotesBlock.php Show the latest notes

Step 1: info and permissions

YAML
# tutorial_notes.info.yml
name: Tutorial Notes
type: module
description: 'Store short notes and list them.'
package: Custom
core_version_requirement: ^10 || ^11
YAML
# tutorial_notes.permissions.yml
add notes:
  title: 'Add notes'
view notes:
  title: 'View notes'

Step 2: the table

PHP
<?php

/**
 * Implements hook_schema().
 */
function tutorial_notes_schema(): array {
  $schema['tutorial_notes'] = [
    'description' => 'Short notes.',
    'fields' => [
      'id' => ['type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE],
      'uid' => ['type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0],
      'body' => ['type' => 'varchar', 'length' => 255, 'not null' => TRUE],
      'created' => ['type' => 'int', 'not null' => TRUE, 'default' => 0],
    ],
    'primary key' => ['id'],
    'indexes' => ['created' => ['created']],
  ];
  return $schema;
}

The schema is read when the module is installed; later changes need an update hook (deployment).

Step 3: the service

YAML
# tutorial_notes.services.yml
services:
  tutorial_notes.repository:
    class: Drupal\tutorial_notes\NoteRepository
    arguments: ['@database', '@current_user', '@datetime.time', '@cache_tags.invalidator']
PHP
<?php

namespace Drupal\tutorial_notes;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Session\AccountInterface;

class NoteRepository {

  public const CACHE_TAG = 'tutorial_notes_list';

  public function __construct(
    protected Connection $database,
    protected AccountInterface $currentUser,
    protected TimeInterface $time,
    protected CacheTagsInvalidatorInterface $invalidator,
  ) {}

  public function add(string $body): int {
    $id = $this->database->insert('tutorial_notes')
      ->fields([
        'uid' => $this->currentUser->id(),
        'body' => mb_substr(trim($body), 0, 255),
        'created' => $this->time->getRequestTime(),
      ])
      ->execute();
    $this->invalidator->invalidateTags([self::CACHE_TAG]);
    return (int) $id;
  }

  public function latest(int $limit = 10): array {
    return $this->database->select('tutorial_notes', 'n')
      ->fields('n')
      ->orderBy('created', 'DESC')
      ->range(0, $limit)
      ->execute()
      ->fetchAll();
  }

}

Parameters go through the query builder, so there is no injection risk (security). Saving a note invalidates the list tag, so cached pages and blocks refresh.

Node.js Stand-in: repository with limit, trimming and invalidation

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.

Step 4: the form

YAML
# tutorial_notes.routing.yml
tutorial_notes.add:
  path: '/notes/add'
  defaults:
    _form: '\Drupal\tutorial_notes\Form\NoteForm'
    _title: 'Add a note'
  requirements:
    _permission: 'add notes'

tutorial_notes.list:
  path: '/notes'
  defaults:
    _controller: '\Drupal\tutorial_notes\Controller\NotesController::list'
    _title: 'Notes'
  requirements:
    _permission: 'view notes'
PHP
<?php

namespace Drupal\tutorial_notes\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\tutorial_notes\NoteRepository;
use Symfony\Component\DependencyInjection\ContainerInterface;

class NoteForm extends FormBase {

  public function __construct(protected NoteRepository $notes) {}

  public static function create(ContainerInterface $container): static {
    return new static($container->get('tutorial_notes.repository'));
  }

  public function getFormId(): string {
    return 'tutorial_notes_add';
  }

  public function buildForm(array $form, FormStateInterface $form_state): array {
    $form['body'] = ['#type' => 'textarea', '#title' => $this->t('Note'), '#required' => TRUE, '#maxlength' => 255, '#rows' => 3];
    $form['actions']['submit'] = ['#type' => 'submit', '#value' => $this->t('Save note')];
    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state): void {
    if (mb_strlen(trim($form_state->getValue('body'))) < 3) {
      $form_state->setErrorByName('body', $this->t('Write at least three characters.'));
    }
  }

  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->notes->add($form_state->getValue('body'));
    $this->messenger()->addStatus($this->t('Note saved.'));
    $form_state->setRedirect('tutorial_notes.list');
  }

}

See the Form API for the lifecycle.

Step 5: controller and block

PHP
// NotesController::list()
public function list(): array {
  $rows = array_map(fn($n) => [$n->id, $n->body, \Drupal::service('date.formatter')->format($n->created, 'short')], $this->notes->latest(50));
  return [
    '#type' => 'table',
    '#header' => ['ID', $this->t('Note'), $this->t('Added')],
    '#rows' => $rows,
    '#empty' => $this->t('No notes yet.'),
    '#cache' => ['tags' => [NoteRepository::CACHE_TAG], 'contexts' => ['user.permissions']],
  ];
}

In a real class inject date.formatter rather than calling \Drupal::service(). The block (see plugins) calls latest($this->configuration['limit']) and declares the same cache tag, so adding a note refreshes both the page and the block.

Node.js Stand-in: one tag refreshes both page and block

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.

Step 6: test it

  • Manual: enable with drush en tutorial_notes, grant add notes to a role, log in as that role (drush uli), add notes, check the list, then visit as anonymous and expect "Access denied".
  • Unit test: construct NoteRepository with a mocked connection (DI) and assert trimming and tag invalidation.
  • Kernel test: boot the module with the real schema ($this->installSchema('tutorial_notes', ['tutorial_notes'])), add notes and read them back.
  • Standards: phpcs --standard=Drupal,DrupalPractice modules/custom/tutorial_notes.

Improvements to attempt

  1. Let users delete their own note with a CSRF-protected route.
  2. Move storage to a content entity type so Views, fields and access work out of the box.
  3. Add a REST/JSON endpoint with a serialization-friendly controller.
  4. Write an update hook adding a priority column.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does NoteRepository::add() invalidate a cache tag?

    Anything carrying the tag is refreshed after the data changes.
  2. 2. How are values written to the table safely?

    The query builder uses placeholders internally.
  3. 3. Which route key shows a form instead of calling a controller?

    _form points to a form class.
  4. 4. What is a good next step to get Views and fields for notes?

    Entities integrate with fields, Views, access and revisions.

Summary

  • A real module combines permissions, a schema, a service, a route, a form and a block.
  • Put logic in an injected service; keep controllers and forms thin.
  • Invalidate a shared cache tag when data changes and add it to everything that displays it.
  • Test with roles, unit and kernel tests and coding standards.
  • Entities are the natural next step for richer features.

Next: Practice: A Drupal Developer Review