This project is not covered by Drupal’s security advisory policy.
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
- Add a Code display to any view
- Add the fields you want as data columns
- Configure filters, sorts, and contextual filters as needed
- 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_exampleCredits
This module was developed with assistance from Anthropic Claude Opus 4.6.
Project information
- Project categories: Content display, Developer tools, Integrations
- Created by chadmandoo on , updated
This project is not covered by the security advisory policy.
Use at your own risk! It may have publicly disclosed vulnerabilities.

