Computed Field

Allows administrative users to add dynamically-computed fields to entity types, where field values are generated by developer-created plugins.

computed_field
17,827 sites
88
drupal.org

インストール

Drupal 10, 9, 8 v3.0.0
composer require 'drupal/computed_field:^3.0'

概要

Computed Field モジュールは、Drupal エンティティにデータベースに保存されるのではなく動的に計算される値を持つフィールドを作成するための堅牢なフレームワークを提供します。これにより、開発者はエンティティの既存データ、関連エンティティ、またはその他のロジックに基づいて値を生成する computed field プラグインを作成できます。

computed field は Drupal の Field システムとシームレスに統合され、保存されるフィールドと同じ field type およびフォーマッターを使用します。これにより、サイト構築者は文字列フォーマッター、エンティティ参照フォーマッター、またはその他の互換性のある表示形式など、使い慣れたウィジェットを使用して計算値を表示できます。

モジュールは2つのアタッチモードをサポートしています:自動アタッチ(プラグインがコード内でターゲットのエンティティタイプ/バンドルを宣言する)と、設定によるアタッチ(サイト管理者がUIを通じてフィールドを作成する)です。Computed Field UI サブモジュールは、コードなしで computed field を作成・管理するためのユーザーフレンドリーなインターフェースを提供します。

主要な機能として lazy builder システムがあり、ホストエンティティとは異なるキャッシュ要件を持つフィールドを処理します。これにより、外部データに依存したり複雑なキャッシュ依存関係を持つ計算値が、ページキャッシングのパフォーマンスに影響を与えることなく正しくレンダリングされます。

Features

  • カスタムプラグインロジックから動的な値を生成する computed field を作成
  • あらゆる Drupal field type(string、entity_reference、text、link、image など)をサポートし、既存のフォーマッターを再利用可能
  • プラグインアノテーションによる自動フィールドアタッチ - コードで宣言されたフィールドが指定されたエンティティタイプとバンドルに自動的に追加される
  • 管理 UI を通じた設定可能なフィールドアタッチ - サイト構築者がコーディングなしで computed field を作成可能
  • 現在のエンティティを参照しているエンティティを検索する組み込みの Reverse Entity Reference プラグイン
  • 異なるキャッシュコンテキストを持つ動的に計算された値の適切なキャッシングのための lazy builder サポート
  • Field UI との完全な統合 - computed field が「表示の管理」インターフェースで保存されたフィールドと並んで表示される
  • base field(全バンドル)とバンドル固有フィールドの両方をサポート
  • レガシーアノテーションと並行してモダンなプラグイン定義のための PHP 8 attribute サポート
  • 柔軟なフィールド設定のための設定フォームを持つ configurable プラグイン

Use Cases

Display related content automatically

Use the built-in Reverse Entity Reference plugin to automatically display content that references the current entity. For example, show all articles by an author on their user profile, or display all products in a category without maintaining the relationship manually.

Calculate derived values

Create computed fields that calculate values from other fields on the entity. Examples include full name from first/last name fields, total price from quantity and unit price, or age calculated from a birthdate field.

Display contextual information

Show information that depends on the current request context, like the current user, time, or request parameters. Use lazy builders to ensure proper caching while still displaying dynamic content.

Aggregate data from related entities

Compute statistics or aggregations from related entities, such as average rating from review entities, total order amount from line items, or comment count. The lazy builder system handles cache invalidation when related content changes.

Format complex output

Use the computed_render_array field type to return complete render arrays when the output requires complex markup, embedded views, or other elements that don't fit standard field formatters.

Automatic field attachment across bundles

Developers can create computed field plugins that automatically attach to specific entity types and bundles through annotation configuration, ensuring consistent functionality across the site without manual setup per bundle.

Tips

  • Use SingleValueTrait for plugins that return a single value - it simplifies implementation by letting you implement singleComputeValue() instead of building the full array structure
  • For plugins with complex caching needs, return TRUE from useLazyBuilder() and provide proper cache metadata in getCacheability() to ensure correct cache invalidation
  • Set no_ui: TRUE in your plugin annotation/attribute to prevent it from appearing in the admin UI dropdown - useful for plugins that should only be attached automatically
  • Automatic plugins can use the 'dynamic' property and override attachAsBaseField()/attachAsBundleField() methods for complex attachment logic based on existing fields
  • The computed_render_array field type gives you full control over output when standard formatters aren't sufficient
  • Remember that computed fields are read-only and don't appear on entity forms - they're purely for display purposes

Technical Details

Admin Pages 4
Add computed field /admin/structure/types/manage/{bundle}/fields/add-computed-field

Form to create a new computed field on a content type. Allows selecting a computed field plugin, configuring its settings (if available), and setting the field label and machine name.

Edit computed field /admin/structure/types/manage/{bundle}/fields/computed/{computed_field}

Edit form for modifying an existing computed field's settings including its label and plugin configuration.

Delete computed field /admin/structure/types/manage/{bundle}/fields/computed/{computed_field}/delete

Confirmation form to delete a computed field from the entity bundle.

Computed fields /admin/reports/fields/computed

Report listing all computed fields configured on the site, showing their entity type, bundle, and plugin information.

権限 1
Administer Computed field entities

Allows users to create, edit, and delete computed field configurations through the admin UI. This is a restricted permission due to its significant administrative impact.

Hooks 1
hook_computed_field_info_alter

Allows modules to alter computed field plugin definitions before they are cached. Can be used to modify plugin properties, change classes, or remove plugins from discovery.

Troubleshooting 5
Computed fields don't appear in Views

Apply the core patch from https://www.drupal.org/project/drupal/issues/3349739 for automatic base field declaration in Views. Bundle fields require manual Views integration as there's no core support yet.

Field values not updating when related content changes

Ensure your plugin implements useLazyBuilder() returning TRUE and getCacheability() returning proper cache tags. The lazy builder system handles cache invalidation based on the metadata you provide.

Computed fields not appearing in the field list

This is a known Drupal core issue (https://www.drupal.org/project/drupal/issues/3045509). Bundle fields are not included in the field map. The fields still function correctly for display purposes.

Plugin configuration not saving

Ensure your plugin class implements both ConfigurableInterface and PluginFormInterface. Check that buildConfigurationForm(), validateConfigurationForm(), and submitConfigurationForm() are properly implemented.

Delete operation leaves orphaned display settings

This is tracked in https://www.drupal.org/project/drupal/issues/3016895. Manually remove the field from view displays after deletion if needed.

Security Notes 4
  • The 'administer computed_field entities' permission is restricted and should only be granted to trusted administrators
  • Computed field plugins have full access to the entity they're attached to - ensure plugin code properly sanitizes output
  • When implementing plugins that query other entities, use accessCheck(TRUE) on entity queries to respect access permissions
  • Be cautious with plugins that expose data from related entities - ensure appropriate access checks are in place