Skip to main content
FreeAn audit of your Drupal siteA written audit of your Drupal site, within three business days
All articles

Backend & EngineeringOct 29, 202610 min read

GDPR access and erasure requests as plugins

Eric ZsigmondCo-Founder & Senior Frontend Engineer

Sooner or later, someone writes to a site and asks for a copy of everything it holds about them. Or they ask for all of it to be erased. On a Drupal site that data rarely lives in one place. The account is in core, event registrations sit in a custom table, orders in their own entity, uploads in the file system. Answering well means asking every one of those places the same two questions, the same way, within a deadline.

We built a module for this, tilizy/privacy (machine name tilizy_privacy, GPL-2.0-or-later), and we use it on our own platform. It is not published on drupal.org, so this article focuses on the pattern: one shared workflow, many small plugins, and how you would write a plugin for your own data. The examples follow the module's current main branch, which requires Drupal 11.3 and PHP 8.3.

What the person is entitled to, in plain terms

Two articles of the GDPR drive this work. Article 15, the right of access, lets a person ask whether you process their personal data and, if you do, receive a copy of it along with information such as the purposes, the recipients and how long it will be kept. Article 17, the right to erasure, lets them ask you to erase it, and you must do so when one of the grounds in Article 17(1) applies, for example when the data is no longer needed for its purpose or the person withdraws the consent it was based on. Erasure is not absolute: Article 17(3) lists exceptions, for example when you must keep data to comply with a legal obligation or for the establishment, exercise or defense of legal claims. Article 12(3) sets the pace: answer without undue delay and within one month of receiving the request. That period can be extended by two further months for complex or numerous requests, if you tell the person within the first month and say why.

This is our plain-language summary of the Regulation, not legal advice. Which data you must hand over and which you may keep is a decision for you and your data-protection advisor. What the module gives you is a place to record that decision for each data source, and a workflow that applies it the same way every time.

One plugin per data source

The module defines a plugin type, PersonalDataSource. Its manager discovers classes in src/Plugin/PersonalDataSource/ of every enabled module. Each plugin knows one store of personal data and answers four calls, all keyed by the person's user ID: find() is a cheap count, export() returns the records, erase() applies an erasure strategy, and previewErase() is a dry run that the base class implements for you.

The module ships one plugin itself, core_user, for the account fields. Everything else belongs to the module that owns the data. That is the point of the design: the people who wrote the registration table know which columns are personal, which can be cleared and which must stay.

Here is the start of a plugin for a custom table, my_module_event_registration. The attribute declares the source and the strategies it supports. The constructor injects the database connection; the base class's own create() passes no services, so a plugin that needs one overrides it.

<?php

declare(strict_types=1);

namespace Drupal\my_module\Plugin\PersonalDataSource;

use Drupal\Core\Database\Connection;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\tilizy_privacy\Attribute\PersonalDataSource;
use Drupal\tilizy_privacy\Plugin\PersonalDataSource\PersonalDataSourceBase;
use Drupal\tilizy_privacy\ValueObject\EraseContext;
use Drupal\tilizy_privacy\ValueObject\EraseResult;
use Drupal\tilizy_privacy\ValueObject\PersonalDataReport;
use Drupal\tilizy_privacy\ValueObject\PersonalDataSummary;
use Symfony\Component\DependencyInjection\ContainerInterface;

#[PersonalDataSource(
  id: 'my_module_event_registration',
  label: new TranslatableMarkup('Event registrations'),
  description: new TranslatableMarkup('Events the person registered for, with phone and dietary notes.'),
  category: 'events',
  strategies: ['delete', 'anonymize'],
  default_strategy: 'anonymize',
  weight: 20,
)]
class EventRegistrationDataSource extends PersonalDataSourceBase {

  public function __construct(
    array $configuration,
    string $plugin_id,
    array $plugin_definition,
    private readonly Connection $database,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
    return new static($configuration, $plugin_id, $plugin_definition, $container->get('database'));
  }

Notice strategies and default_strategy. A reviewer can pick any declared strategy for a given request; the default applies when they do not. The id is a stable contract: it names the source's folder in the export archive and the key under which the reviewer's choice is stored on the request. weight sets the order in the archive and on the review form.

Finding and exporting the records

find() runs every time the review form renders and again before erasure, so it should be one indexed count, not an entity load. export() returns a PersonalDataReport with the records, optional files and free-form metadata.

  public function find(int $uid): PersonalDataSummary {
    $count = (int) $this->database->select('my_module_event_registration', 'r')
      ->condition('r.uid', $uid)
      ->countQuery()
      ->execute()
      ->fetchField();
    return new PersonalDataSummary($this->getPluginId(), $count);
  }

  public function export(int $uid): PersonalDataReport {
    $rows = $this->database->select('my_module_event_registration', 'r')
      ->fields('r', ['id', 'event_id', 'phone', 'dietary_notes', 'created'])
      ->condition('r.uid', $uid)
      ->execute();
    $records = [];
    foreach ($rows as $row) {
      $records[] = [
        'id' => (int) $row->id,
        'type' => 'event_registration',
        'fields' => [
          'event_id' => (int) $row->event_id,
          'phone' => $row->phone,
          'dietary_notes' => $row->dietary_notes,
          'created' => (int) $row->created,
        ],
      ];
    }
    return new PersonalDataReport(
      sourceId: $this->getPluginId(),
      records: $records,
      meta: ['lawful_basis' => 'contract', 'retention' => 'Until the event has taken place.'],
    );
  }

The record shape is a convention, not enforced: an id, a type and a fields map. The meta array is copied verbatim into the archive's manifest, which makes it the natural place to describe this source: its retention period, which Article 15 asks you to give alongside the data, and its lawful basis. Leave out what the person would never see in the product, such as password hashes or internal tokens; the bundled user plugin excludes the password hash for that reason. To include files, pass a files list with an absolute path per file, and the packager copies each one into the source's folder in the archive.

Erasure strategies: delete, anonymize, transfer, retain

The module knows four strategies. They describe different outcomes, and a source declares only the ones it can honestly perform.

  • delete removes the records.
  • anonymize keeps the record but removes what identifies the person. The bundled user plugin works this way: the username becomes deleted-{uid}, the email is cleared and the account is blocked, because user IDs are referenced across many modules and a hard delete could leave orphans.
  • transfer reassigns ownership to a reserved account. On install the module creates a blocked gdpr_anonymous user and stores its ID in the anonymous_uid setting; plugins read it from the erase context instead of hard-coding it.
  • retain keeps the data and records why.

For the registration table, delete and anonymize both make sense. One removes the rows; the other keeps attendance counts and clears the personal columns.

  public function erase(int $uid, string $strategy, EraseContext $ctx): EraseResult {
    $this->assertSupportsStrategy($strategy);

    $affected = match ($strategy) {
      'delete' => $this->database->delete('my_module_event_registration')
        ->condition('uid', $uid)
        ->execute(),
      'anonymize' => $this->database->update('my_module_event_registration')
        ->fields(['uid' => $ctx->anonymousUid, 'phone' => NULL, 'dietary_notes' => NULL])
        ->condition('uid', $uid)
        ->execute(),
    };

    $ctx->logger->info('Event registrations: @strategy for request @rid.', [
      '@strategy' => $strategy,
      '@rid' => $ctx->requestId,
    ]);

    return new EraseResult(
      sourceId: $this->getPluginId(),
      strategy: $strategy,
      recordsAffected: (int) $affected,
      note: $strategy === 'delete'
        ? 'Registrations deleted.'
        : 'Registrations kept for attendance counts; phone and notes cleared.',
    );
  }

}

assertSupportsStrategy() throws UnsupportedStrategyException for anything the attribute does not declare. The interface asks for exactly that: fail loudly rather than return quietly as if the data were gone. The note appears in the request's audit log and in the completion email to the person, so write it for both readers.

Retaining is a strategy like the others, with one convention, documented on EraseResult: the note cites the legal reason. Orders are a typical case, since invoices often have to be kept for a period set by tax law. A plugin for an order entity can offer transfer and retain, with retain as the default.

#[PersonalDataSource(
  id: 'acme_order',
  label: new TranslatableMarkup('Orders'),
  category: 'billing',
  strategies: ['transfer', 'retain'],
  default_strategy: 'retain',
)]
class OrderDataSource extends PersonalDataSourceBase {

  // Constructor, create(), find() and export() follow the same pattern,
  // with entity_type.manager injected instead of the database.

  public function erase(int $uid, string $strategy, EraseContext $ctx): EraseResult {
    $this->assertSupportsStrategy($strategy);
    $storage = $this->entityTypeManager->getStorage('acme_order');
    $ids = $storage->getQuery()->accessCheck(FALSE)->condition('uid', $uid)->execute();

    if ($strategy === 'retain') {
      return new EraseResult($this->getPluginId(), $strategy, count($ids),
        'Kept: invoices must be stored for the period required by tax law.');
    }

    foreach ($storage->loadMultiple($ids) as $order) {
      $order->set('uid', $ctx->anonymousUid);
      $order->save();
    }
    return new EraseResult($this->getPluginId(), $strategy, count($ids),
      'Orders reassigned to the reserved account; order rows kept.');
  }

}

The retained rows are reported as records affected, so the audit log shows that the source held data and that it was kept on purpose, not overlooked.

How the request workflow uses the plugins

A request is a content entity, data_subject_request, with a type (access or erasure) and a status that moves from received to in review, approved and fulfilled, or ends as rejected or cancelled. The module provides the permission (request own data, granted to authenticated users on install), the access rules and the staff screens. The form a person uses to file a request belongs to your application, behind a route that requires that permission, and it creates the entity:

use Drupal\tilizy_privacy\Entity\DataSubjectRequest;

$request = $this->entityTypeManager->getStorage('data_subject_request')->create([
  'type' => DataSubjectRequest::TYPE_ERASURE,
  'subject_uid' => $account->id(),
  'requester_uid' => $account->id(),
  'notify_email' => $account->getEmail(),
  'reason' => $form_state->getValue('reason'),
]);
$request->save();

On first save, the entity sets its deadline from the sla_days setting, 30 by default. The email snapshot matters for erasure: the completion message still needs an address after the user plugin has cleared the account's own.

Staff work from the queue at /admin/people/gdpr-requests. The review form calls every plugin's find() and shows the record counts; for an erasure request it adds a strategy select for each source that holds data. Fulfillment is refused until a reviewer checks "Identity verified", and a verification method, when entered, goes into the audit log. On approval, the form hands the work to the module's services. Condensed from RequestReviewForm:

// Access request: every source exports, then one archive and one link.
$reports = $this->reportBuilder->build($request->getSubjectUid());
$this->packager->package($reports, (string) $request->uuid(), $request->getSubjectUid());
$token = $this->tokens->mint($request);

// Erasure request: every source applies its strategy.
$results = $this->eraseRunner->run($request, (int) $this->currentUser()->id());
$failed = array_filter($results, static fn ($r) => $r->failed);

For an access request, ReportBuilder calls export() on every source and ExportPackager writes a ZIP under private://tlz_gdpr/exports/. The archive holds a manifest.json that lists every source, empty ones included so the person sees what was checked, plus a data.json and a files/ folder for each source that returned data. The person receives a download link by email. Set its lifetime with the export_ttl_days setting, as short as your users can work with, because the archive holds everything the site knows about them. Cron removes the archive after the link has expired.

For an erasure request, EraseRunner walks the sources in weight order, skips any whose find() returns zero, and calls erase() with the reviewer's choice or the default. One failing source does not stop the others, but it does stop the request from closing. If any result is marked failed, the request stays approved, the audit log records it, and nobody is told their data is gone while some of it remains.

Requests that should not be fulfilled leave in one of two ways, and the module keeps them apart. Reject, on the review form, is a decision on substance, for example when identity could not be verified. Cancel, a separate confirmation form, is for duplicates and withdrawn requests. Cron sends staff reminders 7 days and 1 day before the deadline and on the day itself, once per threshold, and drush privacy:status reports open, overdue and due-soon counts without any personal details.

Limits and trade-offs

  • Completeness depends on plugins. The workflow exports and erases only what a plugin covers. A new table without a plugin is invisible to it, so we treat "does this store personal data, and where is its plugin?" as a review question for every feature.
  • Erasure runs synchronously. The runner works inside the approval request. That suits sources with indexed updates; a source with very large volumes needs a queue worker around it.
  • Export errors are recorded, not fatal. If one source's export() throws, the archive is still built and that source's manifest entry carries the error. Test each plugin so this stays rare.
  • Core account cancellation joins in. When an administrator cancels an account through core and reassigns its content to the anonymous user, the module runs the same plugin sweep from hook_user_cancel(), without a request entity. Your plugins should behave on that path too. When a person asks for erasure, handle it as a request, so every source is covered and the audit log shows what was done.
  • The module does not decide the law. Strategies record and apply decisions. Making them stays with you.

Test every plugin against synthetic records: the export is complete, and each declared strategy, retain included, does what its note says. A kernel test with a real database is the right level for that; we explained why in Kernel tests vs unit tests in Drupal.

Data-subject requests are one part of privacy work and consent is another; we covered that side in why we ship our own cookie consent on every Drupal project. If you would like help mapping where personal data lives on your site and writing the plugins for it, get in touch.

Written by

Eric Zsigmond

Co-Founder & Senior Frontend Engineer

Frontend engineer with deep expertise in Drupal theming, component-driven architecture, and modern JavaScript frameworks. Builds fast, accessible interfaces using React, SDX, and Tailwind. Obsessive about performance, pixel-perfect implementation, and clean markup. Almost every pixel on this page is his work.

Enjoyed this article?

If this resonated, imagine what we could do working together on your Drupal site.