Drupal is a registered trademark of Dries Buytaert
drupal 11.3.7 Update released for Drupal core (11.3.7)! drupal 11.2.11 Update released for Drupal core (11.2.11)! drupal 10.6.7 Update released for Drupal core (10.6.7)! drupal 10.5.9 Update released for Drupal core (10.5.9)! cms 2.1.1 Update released for Drupal core (2.1.1)! drupal 11.3.6 Update released for Drupal core (11.3.6)! drupal 10.6.6 Update released for Drupal core (10.6.6)! cms 2.1.0 Update released for Drupal core (2.1.0)! bootstrap 8.x-3.40 Minor update available for theme bootstrap (8.x-3.40). menu_link_attributes 8.x-1.7 Minor update available for module menu_link_attributes (8.x-1.7). eca 3.1.1 Minor update available for module eca (3.1.1). layout_paragraphs 2.1.3 Minor update available for module layout_paragraphs (2.1.3). ai 1.3.3 Minor update available for module ai (1.3.3). ai 1.2.14 Minor update available for module ai (1.2.14). node_revision_delete 2.0.3 Minor update available for module node_revision_delete (2.0.3). moderated_content_bulk_publish 2.0.52 Minor update available for module moderated_content_bulk_publish (2.0.52). klaro 3.0.10 Minor update available for module klaro (3.0.10). klaro 3.0.9 Minor update available for module klaro (3.0.9). layout_paragraphs 2.1.2 Minor update available for module layout_paragraphs (2.1.2). geofield_map 11.1.8 Minor update available for module geofield_map (11.1.8).

views_code

No security coverage
View on drupal.org

Views Code

A developer utility module that lets you use Views as a query builder for custom code. Create a view with the Views UI, add a "Code" display, and execute it programmatically to get raw PHP arrays, JSON, JSONL, or delimited text (CSV/TSV) — no rendered markup, no HTTP response, no route.

The Problem

Drupal developers frequently need structured data from the database. The standard approaches all have trade-offs:

Approach Speed Output Works in code? Site builder configurable? Entity Query + Entity::load() Slow (full entity load) Entity objects Yes No Views Fast (SQL) Rendered HTML No (needs page/block) Yes Views Data Export Fast (SQL) CSV/JSON/XML files Sort of (HTTP) Yes Direct DB queries Fastest Raw arrays Yes No Views Code Fast (SQL) Arrays / JSON / CSV Yes Yes

Views Code bridges the gap: you get the speed of a SQL query, the flexibility of the Views UI (filters, sorts, relationships, contextual filters — all configurable by site builders), and clean data output ready for use in your code.

Quick Start

  1. Add a Code display to any view
  2. Add the fields you want as data columns
  3. Configure filters, sorts, and contextual filters as needed
  4. Execute in your code:
$data = \Drupal::service('views_code.manager')->execute('my_view', 'code_1');
// Returns:
// [
//   ['title' => 'Hello World', 'nid' => '1', 'status' => '1'],
//   ['title' => 'Another Post', 'nid' => '2', 'status' => '0'],
// ]

Service API

All methods are available via the views_code.manager service (Drupal\views_code\ViewsCodeManager):

// Dependency injection (recommended).
use Drupal\views_code\ViewsCodeManager;

class MyService {
  public function __construct(
    protected readonly ViewsCodeManager $viewsCode,
  ) {}

  public function getArticles(): array {
    return $this->viewsCode->execute('articles', 'code_1');
  }
}

Available Methods

Method Returns Description execute() array PHP array of rows (with optional limit/offset) json() string JSON string jsonl() string JSON Lines (one object per line) delimited() string CSV/TSV/pipe-delimited text render() array|string Uses display's configured format first() ?array First row or NULL pluck() array Flat array of one column count() int Row count

Pagination

// Limit and offset.
$page1 = $manager->execute('my_view', 'code_1', [], [], 25, 0);
$page2 = $manager->execute('my_view', 'code_1', [], [], 25, 25);

// Batch processing.
$offset = 0;
do {
  $batch = $manager->execute('my_view', 'code_1', [], [], 500, $offset);
  foreach ($batch as $row) { /* process */ }
  $offset += 500;
} while (count($batch) === 500);

Performance (Raw Values Mode)

Enable Raw Values in the style settings to bypass the field rendering pipeline. Benchmarked with 10,000 nodes and 9 fields:

Method Cold Cached Memory Entity Query + loadMultiple 2.14s — 272 MB Views Code (rendered) 16.23s 12.81s 39 MB Views Code (raw) 4.56s 1.58s 6 MB Direct DB query 0.04s — 12 MB

Style Plugin Options

  • Output Format — PHP Array, JSON, JSONL, or Delimited (CSV/TSV/pipe)
  • Raw Values (Fast Mode) — Bypass field rendering for maximum performance
  • Delimited Settings — Configurable delimiter, enclosure, and header row
  • Processing — Strip HTML, trim whitespace, decode HTML entities

Drush Commands

# Table output (default).
drush vce my_view code_1

# JSON output.
drush vce my_view code_1 --format=json

# JSON Lines.
drush vce my_view code_1 --format=jsonl

# CSV/delimited.
drush vce my_view code_1 --format=delimited

# With contextual filters.
drush vce my_view code_1 Singer --format=json

# Write to file.
drush vce my_view code_1 --format=json --output-file=/tmp/data.json

# Count results.
drush vcc my_view code_1

Real-World Use Cases

  • Queue workers — Fetch items to process without entity loading overhead
  • API controllers — Return JSON responses backed by configurable Views queries
  • Migrations — Use pluck() to gather related entity IDs
  • Data exports — Generate CSV/JSON files via Drush or cron
  • Block plugins — Render data lists with minimal memory usage
  • Batch processing — Process large datasets in chunks with limit/offset

Hooks

hook_views_code_data_alter() — Alter collected data before it's returned to calling code. See views_code.api.php for documentation.

Example Module

Enable views_code_example for a working demo with a users view and block plugin:

drush en views_code_example

Credits

This module was developed with assistance from Anthropic Claude Opus 4.6.

Activity

Total releases
1
First release
Feb 2026
Latest release
1 month ago
Release cadence
Stability
0% stable

Releases

Version Type Release date
1.0.x-dev Dev Feb 27, 2026