Drupalwoo ☉

Building a custom Drupal module with an AJAX table

Large Drupal sites rarely need every content list to reload the page. A custom module can place a filtered table on an editorial screen, request fresh rows asynchronously, and replace only the table region. Editors keep a stable page while Drupal continues to handle permissions, rendering and accessible table markup.

A reliable implementation separates a service that queries eligible nodes, a controller that prepares the page, and a Form API form that supplies the AJAX trigger and replacement command. Drupal 10.3 and 11 include the JavaScript needed for this pattern, so the example uses little custom JavaScript and remains independent of Views.

This example lists published node titles, content types and update times. It assumes the access content permission and returns at most 25 rows, a useful default for teams spread across Australian offices and contributors working remotely. The same conventions suit councils, universities and not-for-profit publishers that expect a Drupal module to remain maintainable after handover.

Setting up the module skeleton

Choose ajax_table as the machine name. Drupal derives the Drupal\ajax_table namespace from it, so the service, route, form and library names must match. Keep the feature in a module rather than a theme override; it can then be enabled per site or shared in a multi-site installation.

Create ajax_table.info.yml in the module root and add a separate services file:

name: 'AJAX table'
type: module
description: 'Filters published content without a page reload.'
package: Custom
core_version_requirement: ^10.3 || ^11

Place configuration files in the module root and namespaced classes under src/. The directories should include Controller, Form, Service and css. Register the data service so Drupal can inject it into the form:

services:
  ajax_table.data:
    class: Drupal\ajax_table\Service\TableDataService
    arguments:
      - '@entity_type.manager'
      - '@date.formatter'

Enable the module with drush en ajax_table -y, then run drush cache:rebuild. The route and library definitions will be added as the implementation takes shape.

Isolating the content query

Put database work in TableDataService so the controller and form do not need to know how rows are selected. This creates one dependable entry point for future filters, pagination, CSV exports or a View integration.

The following excerpt belongs in src/Service/TableDataService.php:

public function contentTypes(): array {
  $options = [];
  foreach ($this->entityTypeManager->getStorage('node_type')->loadMultiple() as $id => $type) {
    $options[$id] = $type->label();
  }
  asort($options);
  return $options;
}

public function publishedRows(?string $bundle = null, int $limit = 25): array {
  $storage = $this->entityTypeManager->getStorage('node');
  $query = $storage->getQuery()
    ->accessCheck(TRUE)
    ->condition('status', 1)
    ->sort('changed', 'DESC')
    ->range(0, $limit);

  if ($bundle) {
    $query->condition('type', $bundle);
  }

  $rows = [];
  $types = $this->contentTypes();
  foreach ($storage->loadMultiple($query->execute()) as $node) {
    $rows[] = [
      'title' => $node->label(),
      'type' => $types[$node->bundle()] ?? $node->bundle(),
      'updated' => $this->dateFormatter->format($node->getChangedTime(), 'short'),
    ];
  }
  return $rows;
}

The Entity Query API escapes values and avoids hand-built SQL. Calling accessCheck(TRUE) applies entity access, while the published condition limits this version to content visible through the normal access model. The 25-row range bounds the response size; add pagination before increasing it.

The date formatter should use Drupal’s configured timezone. Sydney and Melbourne change between AEST and AEDT, while Perth stays on AWST, so a browser offset is the wrong basis for editorial timestamps. A configured site timezone gives predictable results; offer a timezone choice if teams genuinely work across different regions.

Registering the page and controller

Expose the table through a stable administrative route. Keep the access requirement on the route, while the data service continues to apply entity-level access.

ajax_table.page:
  path: '/admin/content/ajax-table'
  defaults:
    _controller: '\Drupal\ajax_table\Controller\TableController::page'
    _title: 'AJAX table'
  requirements:
    _permission: 'access content'
  options:
    _admin_route: TRUE

The controller creates the form and attaches the module’s CSS library. Cache metadata reflects the fact that its output depends on permissions and recently changed nodes.

public function page(): array {
  $build['table_form'] = $this->formBuilder()->getForm(TableForm::class);
  $build['#attached']['library'][] = 'ajax_table/ajax_table';
  $build['#cache']['contexts'][] = 'user.permissions';
  $build['#cache']['tags'][] = 'node_list';
  $build['#cache']['max-age'] = 0;
  return $build;
}

Do not create an unrestricted public endpoint and rely on hidden buttons. The access content permission is suitable for published content; create a dedicated permission if editors need unpublished rows or sensitive metadata. The node_list cache tag invalidates cached results when content changes, while the short cache lifetime reduces stale results after publication or editing.

Enabling table updates with Form API

Use a select and a submit button as the AJAX trigger. The filter remains outside the replacement region, so the refreshed table does not remove the controls required to run another query. The wrapper ID must match both the Form API configuration and the ReplaceCommand selector.

Inject the service into TableForm using constructor injection and ContainerInterface::create(). The main form structure can then remain concise:

public function buildForm(array &$form, FormStateInterface $form_state): array {
  $bundle = (string) $form_state->getValue('bundle', '');
  $rows = $this->tableData->publishedRows($bundle ?: null);

  $form['filters'] = [
    '#type' => 'details',
    '#title' => t('Filter table'),
    '#open' => TRUE,
    'bundle' => [
      '#type' => 'select',
      '#title' => t('Content type'),
      '#options' => ['' => t('All content types')] + $this->tableData->contentTypes(),
    ],
    'actions' => [
      '#type' => 'actions',
      'refresh' => [
        '#type' => 'submit',
        '#value' => t('Refresh rows'),
        '#ajax' => [
          'callback' => '::ajaxRefresh',
          'wrapper' => 'ajax-table-wrapper',
        ],
      ],
    ],
  ];

  $form['table_wrapper'] = [
    '#attributes' => ['id' => 'ajax-table-wrapper'],
    'table' => $this->table($rows),
  ];

  return $form;
}

Build the semantic table in a reusable method with a header, caption and empty-state message. On submission, rebuild that table using the selected content type and return an AjaxResponse:

public function ajaxRefresh(array &$form, FormStateInterface $form_state): AjaxResponse {
  $bundle = (string) $form_state->getValue('bundle', '');
  $form['table_wrapper']['table'] = $this->table(
    $this->tableData->publishedRows($bundle ?: null)
  );

  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand(
    '#ajax-table-wrapper',
    $form['table_wrapper']
  ));
  return $response;
}

This uses Drupal’s Ajax framework instead of a raw XMLHttpRequest request. The form build ID and token are handled by Form API, and Drupal replaces the wrapper without reloading the controller page. If JavaScript is unavailable, the same form performs a normal POST and rebuilds the table through the standard form-processing path.

Styling and enhancing the table

Attach a small library for presentation. The wrapper can scroll horizontally on narrow screens while the table retains the semantics expected by assistive technology.

ajax_table:
  version: 1.x
  css:
    theme:
      css/ajax-table.css: {}

The stylesheet should provide readable spacing, visible focus states and adequate colour contrast. A caption and properly associated header cells give screen-reader users context before they encounter the rows.

If custom JavaScript is required, define a Drupal behavior and use event delegation for controls inside replaced markup. Avoid binding a click handler directly to every row because those nodes are discarded after each refresh. Drupal’s behavior lifecycle offers a safer extension point, while the table caption and header cells provide the context needed for keyboard and screen-reader navigation.

Use Australian English in interface strings, such as organisation, authorised and colour, unless the site’s translation glossary says otherwise. Content is different: a title such as “Planning the arvo workshop” should appear as the author wrote it. Drupal’s escaping and sanitisation processes must preserve that informal wording without interpreting it as HTML.

Connecting the table to site workflows

Link the route from the content menu or an administration dashboard, and give it a clear page title and breadcrumb. A module-owned route is easier to move between environments than a hard-coded dashboard block. If the table must appear inside another editorial form, include the same Form API form as a component instead of nesting forms, since a browser region cannot contain multiple form elements.

Australian Drupal projects are often maintained by a local agency or an internal platform team after handover. Public-sector, university and not-for-profit clients benefit from code that follows core conventions because upgrades and staff turnover are normal. A small service with predictable routes is easier to support than a theme-specific JavaScript workaround, especially across several council, university or campaign sites.

Keep responses small and make the table usable over slower links. A 25-row limit, server-side filtering and horizontal overflow help teams in regional New South Wales, tropical Queensland and remote communities, where connectivity can vary considerably. Test responsive behaviour with browser zoom, a keyboard and a phone. These conditions favour server-side queries and progressive enhancement over downloading every node and filtering it in the browser.

Securing, testing, and deploying the module

The service deliberately exposes no contact details. If author emails, custom fields or unpublished titles are added later, review the Australian Privacy Act 1988 and the relevant state or territory privacy rules for the organisation. Least-privilege roles and accurate cache contexts matter more than concealing fields with CSS.

Security controls

Test the module as an editor and as a user without access. Check the empty result, a filter that returns rows, a long title, content edited between requests and an expired form token. A functional or browser test can submit the form and assert that the replacement contains the expected table heading.

Deployment checks

During rollout, enable the module on a non-production site first and verify entity labels and date formatting with representative Australian content. Compare the AJAX and non-AJAX responses, then follow the project’s normal Composer, database and cache deployment workflow. The finished module keeps filtering local, preserves Drupal’s security model and gives support teams a maintainable extension point.