Examples for Developers
examples
A comprehensive collection of well-documented example modules demonstrating Drupal's core APIs and features for developers to learn from.
Overview
The Examples for Developers project provides a set of working example modules intended to demonstrate Drupal's features and APIs. Each submodule is designed to be simple, well-documented, and modification-friendly, helping developers quickly understand Drupal's inner workings.
The project covers a wide range of Drupal core functionality including Form API, Field API, Entity API, Render API, Plugin API, Database API (DBTNG), Cache API, Queue API, File API, REST API, Events, Hooks, Theming, JavaScript integration, and more. Rather than providing production-ready solutions, these modules serve as educational resources with extensive inline documentation and code comments.
When enabled, the parent module adds an "Examples" toolbar item that provides quick access to all enabled example submodules. Each example module typically includes a description page explaining its purpose and links to demonstration pages.
Install
composer require 'drupal/examples:^4.0'
Features
- 33 self-contained example submodules demonstrating major Drupal APIs
- Toolbar integration providing quick navigation to all enabled examples
- Comprehensive Form API examples including AJAX forms, multistep forms, and modal dialogs
- Field API demonstration with custom field type, widgets, and formatters for RGB color values
- Config Entity and Content Entity creation examples with full CRUD operations
- Block plugin examples including empty, configurable text, and uppercase transformation blocks
- Database API (DBTNG) examples for querying, inserting, updating, and advanced operations
- Cache API demonstration showing proper cache usage patterns
- Queue API and Cron hook examples with queue workers
- Event system examples for dispatching and subscribing to events
- Hook implementation examples including defining and invoking custom hooks
- Custom plugin type definition example with Sandwich plugins
- Stream wrapper implementation example for custom URI schemes
- Email sending and altering examples using hook_mail and hook_mail_alter
- REST client example for communicating with remote Drupal instances
- Render API examples demonstrating render arrays and alter hooks
- Theming examples with custom templates and preprocess functions
- JavaScript integration examples with library definitions and Drupal behaviors
- Tabledrag and tablesort examples for interactive table interfaces
- Batch API example for long-running operations
- Pager example for paginated content display
- Session handling example demonstrating user session storage
- Image effect plugin example with colorize functionality
- Node access and field permission examples
- PHPUnit testing framework examples
Use Cases
Learning Drupal's Form API
Developers can enable form_api_example to see working implementations of various form elements, AJAX forms, multistep forms, and modal dialogs. The extensive inline comments explain each Form API feature.
Creating Custom Field Types
The field_example module demonstrates the complete process of creating a custom field type (RGB color) with multiple widget variants and formatters. Developers can use this as a template for their own field implementations.
Implementing Custom Entities
The config_entity_example (Robot) and content_entity_example (Contact) modules provide complete working examples of both entity types with forms, list builders, access control, and administrative interfaces.
Understanding the Plugin System
The plugin_type_example demonstrates creating a custom plugin type (Sandwich) with plugin manager, discovery, and annotations. Combined with block_example and field_example, developers learn the full plugin ecosystem.
Database Operations with DBTNG
The dbtng_example module shows proper database API usage for insert, update, select, and complex join operations without writing raw SQL queries.
Event-Driven Architecture
The events_example demonstrates the Symfony event dispatcher pattern in Drupal, showing how to create, dispatch, and subscribe to events for decoupled code architecture.
Cron and Queue Processing
Combined use of cron_example and queue_example demonstrates background processing patterns for long-running tasks that shouldn't block user requests.
Custom Stream Wrappers
The stream_wrapper_example shows how to implement custom URI schemes (session://) for alternative file storage backends.
REST API Integration
The rest_example provides a working REST client demonstrating how to communicate with remote Drupal instances, useful for headless Drupal implementations.
Understanding Drupal Hooks
The hooks_example module demonstrates implementing existing hooks, defining custom hooks with alter patterns, and invoking hooks - fundamental to Drupal's extensibility model.
Tips
- Enable only the specific example modules you need to study rather than all at once to reduce complexity.
- Read the inline code comments extensively - they explain not just what the code does but why certain patterns are used.
- Use the API documentation at api.drupal.org/api/examples for cross-referenced HTML documentation of all examples.
- Experiment by modifying the example code to understand how changes affect behavior - the examples are designed to be modification-friendly.
- Check the *.api.php files in hooks_example and plugin_type_example for documentation on defining custom hooks and plugins.
- Use the testing_example module to learn proper test writing patterns including unit tests, kernel tests, and functional tests.
- The batch_example is particularly useful when building import/migration functionality that processes large datasets.
- For REST API development, the rest_example provides a complete client implementation pattern for communicating with external Drupal sites.
Dependencies
Related Projects
Parent module integrates with Drupal's admin toolbar to provide Examples menu item with links to all enabled submodules.
Field example integrates with Field UI for adding custom RGB field to content types.
Image example integrates with Image module to provide custom colorize image effect.
REST example integrates with RESTful Web Services module for remote API communication.
REST example uses Views for node listings on remote server.
REST example uses HAL module for hypermedia format in REST responses.
Config simple example integrates with Config Translation for translatable configuration.
Admin Pages
| Title | Path | Description |
|---|---|---|
| AJAX Example | /examples/ajax-example |
Overview page with links to various AJAX form demonstrations including simplest example, submit-driven AJAX, dependent dropdowns, dynamic form sections, and wizard forms. |
| Demo of batch processing | /examples/batch_example |
Form demonstrating batch operations with options for selecting batch size and running batch processing. |
| Block Example | /examples/block-example |
Overview page explaining block creation with links to the block administration page where example blocks can be placed. |
| Cache Example | /examples/cache-example |
Form demonstrating cache operations including storing, retrieving, and clearing cached data. |
| Config Entity Example | /examples/config-entity-example |
List page displaying all Robot configuration entities with options to add, edit, and delete robots. |
| Config Simple Example Settings | /admin/config/form-api-example/config-simple-form |
Settings form demonstrating simple translatable configuration storage. |
| Contact list | /content_entity_example_contact/list |
List page displaying all Contact content entities with options to add, edit, view, and delete contacts. |
| Contact settings | /admin/structure/content_entity_example_contact_settings |
Settings page for the Contact entity type configuration. |
| Cron Example | /examples/cron-example |
Form for testing cron functionality with interval configuration and manual cron execution. |
| DBTNG Example | /examples/dbtng-example |
Overview page displaying database entries with subpages for adding, updating, and advanced queries. |
| Add entry | /examples/dbtng-example/add |
Form for adding new database entries demonstrating insert operations. |
| Email Example | /examples/email-example |
Form for sending test emails demonstrating hook_mail implementation. |
| Events Example | /examples/events-example |
Form demonstrating event dispatching and subscription with configurable event type. |
| Field Example | /examples/field-example |
Overview page explaining the RGB color field implementation with links to content type configuration. |
| Field Permission Example | /examples/field-permission-example |
Overview page explaining field-level permissions with links to permissions configuration. |
| File Example | /examples/file_example |
Form demonstrating File API operations including reading, writing, and managing files across different stream wrappers. |
| Form API Examples | /examples/form-api-example |
Overview page with links to various Form API demonstrations including simple forms, input elements, containers, AJAX, and modals. |
| Hooks Example | /examples/hooks-example |
Overview page explaining hook implementations with links to demonstrate hook_node_view and hook_form_alter. |
| Image Example | /examples/image-example/styles |
Form for testing image effects including the custom colorize effect with color picker. |
| JavaScript Example | /examples/js-example |
Overview page with links to JavaScript demonstrations including colors/weighting and accordion examples. |
| Menu Example | /examples/menu-example |
Overview page demonstrating menu system features with links to various menu examples including restricted access, tabs, URL arguments, and callbacks. |
| Node Type Example | /examples/node-type-example |
Overview page explaining node type creation via configuration with links to content type administration. |
| Page Example | /examples/page-example |
Overview page demonstrating basic page creation with links to simple page and arguments page examples. |
| Pager Example | /examples/pager-example |
Paginated table demonstration showing how to display large datasets across multiple pages. |
| Plugin Type Example | /examples/plugin-type-example |
Overview page explaining custom plugin type definition with demonstration of Sandwich plugins. |
| Queue Example | /examples/queue_example |
Form demonstrating Queue API operations including adding items, claiming items, and processing queues. |
| Render Example | /examples/render-example |
Overview page with links to render array building examples and alter hook demonstrations. |
| REST Example: Getting started | /examples/rest-getting-started |
Overview page explaining REST client setup with links to configuration and node operations. |
| Connect to a remote Drupal site | /examples/rest-client-settings |
Form for configuring REST client connection to remote Drupal instance. |
| Session Example | /examples/session_example |
Form demonstrating session storage with fields that persist values in user session. |
| Stream Wrapper Example | /examples/stream_wrapper_example |
Overview page explaining custom stream wrapper implementation for session-based file storage. |
| Tabledrag Overview | /examples/tabledrag-example |
Overview page with links to various tabledrag demonstrations including simple rows, nested hierarchies, and roots/leaves patterns. |
| TableSort Example | /examples/tablesort-example |
Demonstration of sortable table with clickable column headers for dynamic sorting. |
| Testing Example | /examples/testing-example |
Overview page explaining PHPUnit testing framework with links to test demonstrations and documentation. |
| Theming Example | /examples/theming_example |
Overview page with links to theming demonstrations including list theming and form theming examples. |
Permissions
| Permission | Description |
|---|---|
|
Create and edit Robot configuration entities. |
|
Permission to delete Contact content entities. |
|
Permission to create new Contact content entities. |
|
Permission to view Contact content entities. |
|
Permission to edit Contact content entities. |
|
Permission to administer Contact entity settings. |
|
Permission to view field note values on own content. |
|
Permission to edit field note values on own content. |
|
Permission to view field note values on any content. |
|
Permission to edit field note values on any content. |
|
Permission to configure field note field settings. |
|
Permission to access File Example demonstration pages. |
|
Permission to view private files in File Example demonstrations. |
|
Permission to view temporary files in File Example demonstrations. |
|
Permission to view session files in File Example demonstrations. |
|
Bypass access control when accessing menu example restricted pages. Marked as restricted. |
|
Allow users to access the simple page demonstration. |
|
Allow users to access the page with URL arguments demonstration. |
|
Allow user to edit any Testing Example content authored by any user. Marked as restricted. |
Hooks
| Hook | Description |
|---|---|
hook_toolbar |
Adds Examples toolbar item with links to all enabled example modules. |
hook_block_view_alter |
Modifies block output; example changes block labels to uppercase if they contain the word 'uppercase'. |
hook_cron |
Implements cron processing; executes background tasks at specified intervals. |
hook_mail |
Defines email templates; sets message subject and body based on email key. |
hook_mail_alter |
Alters outgoing emails; adds a site signature to all email messages. |
hook_entity_field_access |
Controls field access permissions based on operation, field, account, and entity ownership. |
hook_file_download |
Controls file download permissions; checks user permission for private, temporary, or session files. |
hook_help |
Provides module help text displayed on admin/help pages. |
hook_node_view |
Processes node view; tracks node view count in session and invokes custom hooks. |
hook_form_alter |
Modifies forms; example alters user login form to change username field description. |
hook_hooks_example_count_incremented |
Custom hook implementation demonstrating how modules can define and invoke their own hooks. |
hook_image_effect_info_alter |
Alters image effect information; modifies descriptions of image effects. |
hook_theme |
Defines theme implementations including templates and variables. |
hook_preprocess_page |
Preprocesses page render array; can move breadcrumbs, reverse sidebars, show debug info. |
hook_preprocess_block |
Preprocesses block render array; can wrap blocks with additional markup. |
hook_preprocess_form_element_label |
Preprocesses form element labels; adds strong formatting based on data attributes. |
hook_node_access |
Node access control; restricts update/delete operations based on permissions and authorship. |
hook_sandwich_info_alter |
Custom alter hook for Sandwich plugin definitions; modifies plugin descriptions. |
Troubleshooting
Ensure the parent 'Examples for Developers' module is enabled. The toolbar module must also be enabled as it's a required dependency.
Check that the user has appropriate permissions. Many example pages require 'access content' permission, while entity examples require specific permissions like 'administer robots' or 'view contact entity'.
Ensure JavaScript is enabled in the browser. Some AJAX examples have 'nojs' variants demonstrating graceful degradation. Check browser console for JavaScript errors.
Verify the remote Drupal site has REST and HAL modules enabled with proper authentication. The remote site must allow Basic Auth for the REST example to work.
After enabling field_example, clear caches. The RGB field type should appear when adding fields to content types.
The colorize effect requires PHP GD library with imagefilter() function. Check PHP configuration and ensure GD extension is loaded.
Security Notes
- The examples are intended for learning purposes on development sites. Some examples intentionally demonstrate simplified patterns that may need additional security hardening for production use.
- The REST example stores credentials in configuration - in production, use more secure credential storage mechanisms.
- Field permission example demonstrates proper field-level access control patterns that should be applied when creating custom fields with sensitive data.
- The file_example demonstrates stream wrapper access control - always implement proper access checks when creating custom stream wrappers.