Drupalwoo ☉

Creating a Custom Drupal VBO Action for Bulk Operations

Editors regularly need to change more content than a handful of forms can comfortably handle: tagging campaign pages, moving articles into review, correcting a shared field, or preparing records for migration. Views Bulk Operations (VBO) supplies the selection interface, while a custom VBO action supplies the repeatable business rule. The result is a controlled workflow instead of a one-off administrative script.

This guide covers plugin structure, entity access, confirmation, execution and feedback for Drupal 10 and 11 projects using the Views and VBO modules. It also considers queues, testing and deployment. Keep VBO unchanged and place custom behaviour in a small custom module, so upgrades remain predictable and the same action can be reused across several Views.

When a Custom VBO Action Adds Value

VBO already includes useful actions for publishing, unpublishing, deleting, assigning ownership and adding taxonomy terms. If the desired operation maps cleanly to one of these, configuration is safer than new code. Bundled actions also inherit tested access checks, translations, confirmation patterns and queue handling.

Custom work becomes worthwhile when a rule spans fields, such as validating an event date before changing status, tagging content by audience, or recording a reason in an audit log. It is also useful when two sites need the same non-standard operation. The action should encode one clear business outcome rather than becoming a miniature scripting console.

Before coding, inspect the View and the entities it returns. Confirm content types, bundles, field definitions, revision settings, moderation constraints and permissions. A focused contract will make the action predictable for editors, developers and support teams.

Defining the Bulk Operation Contract

Start with the selection itself. A View may expose content through relationships or aggregation, so list the entity types and bundles that can reach the action. Decide whether ineligible items should be hidden, shown but skipped, or rejected before execution. Skipping with a clear reason is often kinder than silently changing a subset.

Define metadata such as the action label, target entity type, confirmation text and any operator input. Then define execution rules: required fields, access checks, idempotency, whether existing values are preserved, and what each result reports. A repeated run should produce the same safe outcome, not duplicate taxonomy terms, notices or revisions.

Choose the operating window before choosing the code. Australian teams commonly hand work between Sydney, Melbourne and Brisbane offices, and daylight-saving changes alter Sydney and Melbourne offsets twice yearly while Brisbane remains on ACST. Trigger scheduled jobs from the configured site time rather than a hard-coded UTC hour, and coordinate bulk runs with ordinary Australian business hours and publishing handoffs.

Building the Module and Action Plugin

Create a custom module and keep it separate from contributed code. Teams that need the underlying module pattern can follow this custom module walkthrough first. Add only the dependencies required by the action, including VBO if the site does not already provide it, then give the module a machine name that reflects its purpose, such as editorial_bulk.

Place the action in the plugin directory expected by the installed VBO release. The following skeleton uses the common ViewsBulkOperationActionBase; on an older branch, copy the namespace and base class from a bundled VBO action. The metadata defines where the action appears and requires confirmation before the operator commits.

<?php

namespace Drupal\editorial_bulk\Plugin\views_bulk_operation;

use Drupal\node\NodeInterface;
use Drupal\views_bulk_operations\Plugin\views_bulk_operation\ViewsBulkOperationActionBase;

/**
 * @ViewsBulkOperation(
 *   id = "mark_editorial_review",
 *   label = @Translation("Mark for editorial review"),
 *   type = "node",
 *   confirm_type = "All selected content",
 *   confirm_title = @Translation("Mark selected content for editorial review"),
 * )
 */
final class MarkEditorialReview extends ViewsBulkOperationActionBase {

  public function execute($entity, $context) {
    if (!$entity instanceof NodeInterface ||
        !$entity->hasField('field_editorial_review')) {
      return $this->t('Skipped @id: the review field is missing.', [
        '@id' => $entity->id(),
      ]);
    }

    if (!$entity->access('update')) {
      return $this->t('Skipped @title: update access was denied.', [
        '@title' => $entity->label(),
      ]);
    }

    if ((bool) $entity->get('field_editorial_review')->value) {
      return $this->t('Skipped @title: it is already marked.', [
        '@title' => $entity->label(),
      ]);
    }

    $entity->set('field_editorial_review', TRUE);
    $entity->save();

    return $this->t('Marked @title for editorial review.', [
      '@title' => $entity->label(),
    ]);
  }

}

The method deliberately uses the entity API, checks update access and skips an entity that is already marked. field_editorial_review must be a Boolean field on every eligible node type. If the action needs a reason or target, expose VBO’s action form, validate it and pass only the cleaned value into the execution context.

Return one result per entity so VBO can aggregate skipped, successful and failed items in the operation summary. After enabling the module, clear caches and edit the target View to expose the Bulk Operations field. Plugin discovery, action configuration and View settings are separate layers, so a visible action can still be missing from the dropdown if its target type or configuration does not match.

Choosing a Safe Execution Strategy

The right execution method depends on how many entities change and how quickly editors need feedback. Small operations can finish in the request; large ones should run through Drupal’s queue or a batch so the web worker does not exhaust its time limit. The practical choices differ in scale and recovery:

Approach Suitable workload Main strength Main limitation Operator feedback
Bundled VBO action Routine mass updates Proven and configurable Limited to supplied operations Built-in summary
In-process custom action Small or medium selections Immediate result and simple logic Long requests can time out VBO result list
Queued custom action Large or slow imports Survives navigation and separates work Requires cron and queue monitoring Queue and result status
Administrator script Exceptional migrations Full control outside the interface Weak selection controls and auditing Script-specific log

Queueing changes the user experience rather than the action’s rules. Store the operation ID and selected entity IDs in a queue item, reload each entity when the worker runs it, and re-check access because permissions may have changed. A missed cron run can occur during maintenance windows, so expose the queue state and provide a controlled retry path.

Use transactions around each entity or small chunk, not one enormous transaction that locks rows for the whole import. Make the operation idempotent, log a stable identifier with each failure and send operators to a report rather than presenting a wall of exceptions. Repeated processing of the same selection should skip work already completed.

Securing Access and Sensitive Content

VBO’s selection form does not remove the need for authorisation. Use the action’s access mechanism to determine which roles may invoke it, and repeat an entity-level update check inside execute(). Respect published-state, ownership and moderation constraints. CSRF protection and form tokens come from Drupal, while custom routes still require the standard permission, validation and trusted-token pattern.

Personal information needs a different level of care. Where the Privacy Act 1988 and Australian Privacy Principles apply, bulk publishing or sharing records should be limited to a legitimate purpose, accurate data, appropriate security and controlled disclosure. Do not place titles, email addresses or reasons in public logs. The TFOSORCIM community site offers a useful external reference when teams compare how open-source communities document decisions and responsibilities.

Commercial email is a separate risk. A Drupal action that sends messages must honour the Spam Act 2003, including consent, sender identification and a functional unsubscribe mechanism, and apply suppression lists. Australian project budgets are also commonly expressed in Australian dollars, with 10% GST applying to many taxable services; that affects approval thresholds for paid tools, data services and third-party integrations used during a bulk run.

Testing Behaviour, Performance and Recovery

Test the plugin as code, not only through the View. A kernel test can create published and unpublished nodes, a missing-field case and an inaccessible node, then assert the success, skip and failure results. Run the operation twice to prove idempotency. Add tests for empty labels, long labels, Unicode content and entities whose translations or revisions differ.

Benchmark against production-like data, including real field combinations and a selection large enough to expose timeouts. Watch database queries, memory use, cache invalidation and queue throughput rather than relying on average response time. One deliberately failed item should not prevent other entities from processing, and the final report must identify exactly which items need attention.

Content changes can carry commercial consequences. If a bulk action alters prices, availability claims or promotions, Australian Competition and Consumer Commission guidance and the Australian Consumer Law may be relevant to the final public wording. Have the owner approve a representative preview and retain an audit record, especially when the same View feeds campaigns, retail pages or partner feeds.

Deploying and Maintaining the Action

Package the module in Git, pin compatible versions of Drupal, Views and VBO, and review contributed changes before deployment. Keep the action’s configuration in Drupal’s configuration management where possible, but distinguish exported View changes from PHP code. Test imports on a staging copy made from sanitised production data, then deploy during a coordinated content freeze.

Prepare a runbook that records the View and filters used, item counts, expected field changes, queue commands, monitoring checks, rollback steps and the support contact. Take database and file backups where the operation is irreversible. A rollback may mean restoring records, restoring a field, or re-running an inverse action, so test that path rather than assuming an undo button exists.

The Australian Drupal market includes boutique studios, university teams and not-for-profit organisations, often serving .com.au or .org.au sites with mixed hosting and staffing arrangements. A documented action lets a small internal team hand work to another maintainer without relying on tribal knowledge. Keep ownership with the business owner, review permissions after staff changes, and schedule recurring checks against Australian daylight-saving and office handover patterns.