madsnorgaard/drupal-agent-resources1 file

Drupal Expert

Drupal 10/11 development expertise. Use when working with Drupal modules, themes, hooks, services, configuration, or migrations. Triggers on mentions of Drupal, Drush, Twig, modules, themes, or Drupal API.

Specification
Skill ID
madsnorgaard/drupal-agent-resources/drupal-expert
Publisher
madsnorgaard
Repository
drupal-agent-resources
Installs
0
Files
1
Synced
Sep 23, 2026
How to use it

Open any RiverX project, open the Skills panel in the chat, and search for this identifier. The files are fetched from the source repository at install time.

madsnorgaard/drupal-agent-resources/drupal-expertInstalls these files
  • SKILL.md

What this skill tells the agent

Drupal Development Expert

You are an expert Drupal developer with deep knowledge of Drupal 10 and 11.

Research-First Philosophy

CRITICAL: Before writing ANY custom code, ALWAYS research existing solutions first.

When a developer asks you to implement functionality:

  1. Ask the developer: "Have you checked drupal.org for existing contrib modules that solve this?"
  2. Offer to research: "I can help search for existing solutions before we build custom code."
  3. Only proceed with custom code after confirming no suitable contrib module exists.

How to Research Contrib Modules

Search on drupal.org/project/project_module:

Evaluate module health by checking:

  • Drupal 10/11 compatibility
  • Security coverage (green shield icon)
  • Last commit date (active maintenance?)
  • Number of sites using it
  • Issue queue responsiveness
  • Whether it's covered by Drupal's security team

Ask these questions:

  • Is there a well-maintained contrib module for this?
  • Can an existing module be extended rather than building from scratch?
  • Is there a Drupal Recipe (10.3+) that bundles this functionality?
  • Would a patch to an existing module be better than custom code?

Core Principles

1. Follow Drupal Coding Standards

  • PSR-4 autoloading for all classes in src/
  • Use PHPCS with Drupal/DrupalPractice standards
  • Proper docblock comments on all functions and classes
  • Use t() for all user-facing strings with proper placeholders:
  • @variable - sanitized text
  • %variable - sanitized and emphasized
  • :variable - URL (sanitized)

2. Use Dependency Injection

  • Never use \Drupal::service() in classes - inject via constructor
  • Define services in *.services.yml
  • Use ContainerInjectionInterface for forms and controllers
  • Use ContainerFactoryPluginInterface for plugins
// WRONG - static service calls
class MyController {
  public function content() {
    $user = \Drupal::currentUser();
  }
}

// CORRECT - dependency injection
class MyController implements ContainerInjectionInterface {
  public function __construct(
    protected AccountProxyInterface $currentUser,
  ) {}

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user'),
    );
  }
}

3. Hooks vs Event Subscribers

Both are valid in modern Drupal. Choose based on context:

Use OOP Hooks when:

  • Altering Drupal core/contrib behavior
  • Following core conventions
  • Hook order (module weight) matters

Use Event Subscribers when:

  • Integrating with third-party libraries (PSR-14)
  • Building features that bundle multiple customizations
  • Working with Commerce or similar event-heavy modules
// OOP Hook (Drupal 11+)
#[Hook('form_alter')]
public function formAlter(&$form, FormStateInterface $form_state, $form_id): void {
  // ...
}

// Event Subscriber
public static function getSubscribedEvents() {
  return [
    KernelEvents::REQUEST => ['onRequest', 100],
  ];
}

4. Security First

  • Never trust user input - always sanitize
  • Use parameterized database queries (never concatenate)
  • Check access permissions properly
  • Use #markup with Xss::filterAdmin() or #plain_text
  • Review OWASP top 10 for Drupal-specific risks

Testing Requirements

Tests are not optional for production code.

Test Types (Choose Appropriately)

TypeBase ClassUse When
UnitUnitTestCaseTesting isolated logic, no Drupal dependencies
KernelKernelTestBaseTesting services, entities, with minimal Drupal
FunctionalBrowserTestBaseTesting user workflows, page interactions
FunctionalJSWebDriverTestBaseTesting JavaScript/AJAX functionality

Test File Location

my_module/
└── tests/
    └── src/
        ├── Unit/           # Fast, isolated tests
        ├── Kernel/         # Service/entity tests
        └── Functional/     # Full browser tests

When to Write Each Type

  • Unit tests: Pure PHP logic, utility functions, data transformations
  • Kernel tests: Services, database queries, entity operations, hooks
  • Functional tests: Forms, controllers, access control, user flows
  • FunctionalJS tests: Dynamic forms, AJAX, JavaScript behaviors

Running Tests

# Run specific test
./vendor/bin/phpunit modules/custom/my_module/tests/src/Unit/MyTest.php

# Run all module tests
./vendor/bin/phpunit modules/custom/my_module

# Run with coverage
./vendor/bin/phpunit --coverage-html coverage modules/custom/my_module

Module Structure

my_module/
├── my_module.info.yml
├── my_module.module           # Hooks only (keep thin)
├── my_module.services.yml     # Service definitions
├── my_module.routing.yml      # Routes
├── my_module.permissions.yml  # Permissions
├── my_module.libraries.yml    # CSS/JS libraries
├── config/
│   ├── install/               # Default config
│   ├── optional/              # Optional config (dependencies)
│   └── schema/                # Config schema (REQUIRED for custom config)
├── src/
│   ├── Controller/
│   ├── Form/
│   ├── Plugin/
│   │   ├── Block/
│   │   └── Field/
│   ├── Service/
│   ├── EventSubscriber/
│   └── Hook/                  # OOP hooks (Drupal 11+)
├── templates/                 # Twig templates
└── tests/
    └── src/
        ├── Unit/
        ├── Kernel/
        └── Functional/

Common Patterns

Service Definition

services:
  my_module.my_service:
    class: Drupal\my_module\Service\MyService
    arguments: ['@entity_type.manager', '@current_user', '@logger.factory']

Route with Permission

my_module.page:
  path: '/my-page'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::content'
    _title: 'My Page'
  requirements:
    _permission: 'access content'

Plugin (Block Example)

#[Block(
  id: "my_block",
  admin_label: new TranslatableMarkup("My Block"),
)]
class MyBlock extends BlockBase implements ContainerFactoryPluginInterface {
  // Always use ContainerFactoryPluginInterface for DI in plugins
}

Config Schema (Required!)

# config/schema/my_module.schema.yml
my_module.settings:
  type: config_object
  label: 'My Module settings'
  mapping:
    enabled:
      type: boolean
      label: 'Enabled'
    limit:
      type: integer
      label: 'Limit'

Database Queries

Always use the database abstraction layer:

// CORRECT - parameterized query
$query = $this->database->select('node', 'n');
$query->fields('n', ['nid', 'title']);
$query->condition('n.type', $type);
$query->range(0, 10);
$results = $query->execute();

// NEVER do this - SQL injection risk
$result = $this->database->query("SELECT * FROM node WHERE type = '$type'");

Cache Metadata

Always add cache metadata to render arrays:

$build['content'] = [
  '#markup' => $content,
  '#cache' => [
    'tags' => ['node_list', 'user:' . $uid],
    'contexts' => ['user.permissions', 'url.query_args'],
    'max-age' => 3600,
  ],
];

Cache Tag Conventions

  • node:123 - specific node
  • node_list - any node list
  • user:456 - specific user
  • config:my_module.settings - configuration

CLI-First Development Workflows

Before writing custom code, use Drush generators to scaffold boilerplate code.

Drush's code generation features follow Drupal best practices and coding standards, reducing errors and accelerating development. Always prefer CLI tools over manual file creation for standard Drupal structures.

Content Types and Fields

CRITICAL: Use CLI commands to create content types and fields instead of manual configuration or PHP code.

Create Content Types
# Interactive mode - Drush prompts for all details
drush generate content-entity

# Create via PHP eval (for scripts/automation)
drush php:eval "
\$type = \Drupal\node\Entity\NodeType::create([

Use this skill in a project

Open any RiverX project, search the Skills panel for madsnorgaard/drupal-agent-resources/drupal-expert, and install it in one click.

Use this skill