開発者向けサンプル集
A comprehensive collection of well-documented example modules demonstrating Drupal's core APIs and features for developers to learn from.
examples
インストール
composer require 'drupal/examples:^4.0'
概要
Examples for Developers プロジェクトは、Drupal の機能と API を実演することを目的とした、動作するサンプルモジュール一式を提供します。各サブモジュールはシンプルで、詳細なドキュメントが付いており、変更しやすいように設計されており、開発者が Drupal の内部動作を素早く理解できるよう支援します。
このプロジェクトは、Form API、Field API、Entity API、Render API、Plugin API、Database API(DBTNG)、Cache API、Queue API、File API、REST API、Events、Hooks、テーマ、JavaScript 統合など、幅広い Drupal コア機能をカバーしています。本番環境向けのソリューションを提供するのではなく、これらのモジュールは豊富なインラインドキュメントとコードコメントを備えた教育リソースとして機能します。
有効化すると、親モジュールはツールバーに「Examples」項目を追加し、有効化されているすべてのサンプルサブモジュールへのクイックアクセスを提供します。各サンプルモジュールには通常、その目的を説明する説明ページとデモページへのリンクが含まれています。
Features
- 主要な Drupal API を実演する 33 個の独立したサンプルサブモジュール
- 有効化されているすべてのサンプルへのクイックナビゲーションを提供するツールバー統合
- AJAX フォーム、マルチステップフォーム、モーダルダイアログを含む包括的な Form API サンプル
- RGB カラー値用のカスタムフィールドタイプ、ウィジェット、フォーマッタを使用した Field API デモ
- 完全な CRUD 操作を備えた Config Entity と Content Entity の作成サンプル
- 空のブロック、設定可能なテキストブロック、大文字変換ブロックを含む Block プラグインサンプル
- クエリ、挿入、更新、高度な操作のための Database API(DBTNG)サンプル
- 適切なキャッシュ使用パターンを示す Cache API デモ
- キューワーカーを使用した Queue API と Cron hook のサンプル
- イベントのディスパッチとサブスクライブのための Event システムサンプル
- カスタム hook の定義と呼び出しを含む Hook 実装サンプル
- Sandwich プラグインを使用したカスタム Plugin タイプ定義サンプル
- カスタム URI スキームのための Stream wrapper 実装サンプル
- hook_mail と hook_mail_alter を使用したメール送信と変更のサンプル
- リモート Drupal インスタンスとの通信のための REST クライアントサンプル
- render array と alter hook を実演する Render API サンプル
- カスタムテンプレートと preprocess 関数を使用したテーマサンプル
- ライブラリ定義と Drupal behaviors を使用した JavaScript 統合サンプル
- インタラクティブなテーブルインターフェースのための Tabledrag と Tablesort サンプル
- 長時間実行操作のための Batch API サンプル
- ページネーション付きコンテンツ表示のための Pager サンプル
- ユーザーセッションストレージを実演する Session 処理サンプル
- カラー化機能を備えた Image effect プラグインサンプル
- Node アクセスとフィールドパーミッションのサンプル
- PHPUnit テストフレームワークのサンプル
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.
Technical Details
Admin Pages 35
/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.
/examples/batch_example
Form demonstrating batch operations with options for selecting batch size and running batch processing.
/examples/block-example
Overview page explaining block creation with links to the block administration page where example blocks can be placed.
/examples/cache-example
Form demonstrating cache operations including storing, retrieving, and clearing cached data.
/examples/config-entity-example
List page displaying all Robot configuration entities with options to add, edit, and delete robots.
/admin/config/form-api-example/config-simple-form
Settings form demonstrating simple translatable configuration storage.
/content_entity_example_contact/list
List page displaying all Contact content entities with options to add, edit, view, and delete contacts.
/admin/structure/content_entity_example_contact_settings
Settings page for the Contact entity type configuration.
/examples/cron-example
Form for testing cron functionality with interval configuration and manual cron execution.
/examples/dbtng-example
Overview page displaying database entries with subpages for adding, updating, and advanced queries.
/examples/dbtng-example/add
Form for adding new database entries demonstrating insert operations.
/examples/email-example
Form for sending test emails demonstrating hook_mail implementation.
/examples/events-example
Form demonstrating event dispatching and subscription with configurable event type.
/examples/field-example
Overview page explaining the RGB color field implementation with links to content type configuration.
/examples/field-permission-example
Overview page explaining field-level permissions with links to permissions configuration.
/examples/file_example
Form demonstrating File API operations including reading, writing, and managing files across different stream wrappers.
/examples/form-api-example
Overview page with links to various Form API demonstrations including simple forms, input elements, containers, AJAX, and modals.
/examples/hooks-example
Overview page explaining hook implementations with links to demonstrate hook_node_view and hook_form_alter.
/examples/image-example/styles
Form for testing image effects including the custom colorize effect with color picker.
/examples/js-example
Overview page with links to JavaScript demonstrations including colors/weighting and accordion examples.
/examples/menu-example
Overview page demonstrating menu system features with links to various menu examples including restricted access, tabs, URL arguments, and callbacks.
/examples/node-type-example
Overview page explaining node type creation via configuration with links to content type administration.
/examples/page-example
Overview page demonstrating basic page creation with links to simple page and arguments page examples.
/examples/pager-example
Paginated table demonstration showing how to display large datasets across multiple pages.
/examples/plugin-type-example
Overview page explaining custom plugin type definition with demonstration of Sandwich plugins.
/examples/queue_example
Form demonstrating Queue API operations including adding items, claiming items, and processing queues.
/examples/render-example
Overview page with links to render array building examples and alter hook demonstrations.
/examples/rest-getting-started
Overview page explaining REST client setup with links to configuration and node operations.
/examples/rest-client-settings
Form for configuring REST client connection to remote Drupal instance.
/examples/session_example
Form demonstrating session storage with fields that persist values in user session.
/examples/stream_wrapper_example
Overview page explaining custom stream wrapper implementation for session-based file storage.
/examples/tabledrag-example
Overview page with links to various tabledrag demonstrations including simple rows, nested hierarchies, and roots/leaves patterns.
/examples/tablesort-example
Demonstration of sortable table with clickable column headers for dynamic sorting.
/examples/testing-example
Overview page explaining PHPUnit testing framework with links to test demonstrations and documentation.
/examples/theming_example
Overview page with links to theming demonstrations including list theming and form theming examples.
権限 19
Hooks 18
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 6
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 4
- 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.