logo

パレット - カラフルに🎨

Palette — ビジュアルページビルダー、デザインの専門知識は不要です。

ライブデモ パレットをダウンロード

Scroll
09/05/2020, by maria

汎用エンティティのAPIメソッドを扱います

  • Entity::create()
  • Entity::load()
  • Entity::save()
  • Entity::id()
  • Entity::bundle()
  • Entity::isNew()
  • Entity::label()

より具体的なAPIは、特定の章で説明します。

チェック

// Make sure that an object is an entity.
if ($entity instanceof \Drupal\Core\Entity\EntityInterface) {
}

// Make sure it's a content entity.
if ($entity instanceof \Drupal\Core\Entity\ContentEntityInterface) {
}
// or:
if ($entity->getEntityType()->getGroup() == 'content') {
}

// Get the entity type or the entity type ID.
$entity->getEntityType();
$entity->getEntityTypeId();

// Make sure it's a node.
if ($entity instanceof \Drupal\node\NodeInterface) {
}

エンティティから情報を取得する / Entityメソッド

識別子、バンドル、リビジョンIDなどの情報をエンティティから取得するためのいくつかの一般的なメソッドが利用可能です。詳細はEntityInterfaceのドキュメントを参照してください。

// Get the ID.
$entity->id();

// Get the bundle.
$entity->bundle();

// Check if the entity is new.
$entity->isNew();

// Get the label of an entity. Replacement for entity_label().
$entity->label();

// Get the URL object for an entity.
$entity->toUrl();

// Get internal path, path alias if exists, for an entity.
$entity->toUrl()->toString();

// Create a duplicate that can be saved as a new entity.
$duplicate = $entity->createDuplicate();

エンティティの作成

// You can use the static create() method if you know the entity class.
$node = Node::create([
  'type' => 'article',
  'title' => 'The node title',
]);

// Use the entity type manager (recommended).
$node = \Drupal::entityTypeManager()->getStorage('node')->create(['type' => 'article', 'title' => 'Another node']);

// Or use the procedural wrapper (deprecated).
$node = entity_create('node', [
  'title' => 'My node',
  'body' => 'The body content. This just works like this due to the new Entity Field
          API. It will be assigned as the value of the first field item in the
          default language.',
]);

フィールドタイプのアノテーションからのデフォルト設定は、欠落しているトップレベルのキーにのみ追加されます。深いマージは実行されません。

オブジェクト指向コードでは、静的メソッドEntity::create()の使用を避けてください。代わりに依存性注入を使用してエンティティタイプマネージャーを注入し、$this->entityTypeManager->getStorage($entity_type)->create()でエンティティを作成してください。これにより、コードが適切に分離され、モジュールでテストできることが保証されます。

IDEでの検出を容易にするため、エンティティストレージインターフェースをプロパティに割り当てることもできます。例:$this->nodeStorage = $this->entityTypeManager->getStorage('node'); エンティティを作成するには、$this->nodeStorage->create()を使用できます。

読み込み

// Use the static method
$node = Node::load(1);

// Deprecated.  Dynamic entity type, entity_load() now loads a single entity, the 7.x entity_load() has been renamed to entity_load_multiple().
$entity = entity_load($entity_type, $id);

// Using the storage controller (recommended).
$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load(1);

// Load multiple entities, also exists as entity_load_multiple().
$entities = \Drupal::entityTypeManager()->getStorage($entity_type)->loadMultiple([1, 2, 3]);

// Load entities by their property values.
$entities = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'article']);

エンティティを更新するには、読み込んでから変更を加えて保存します。

オブジェクト指向コードでは、静的メソッドEntity::load()の使用を避けてください。代わりに依存性注入を使用してエンティティタイプマネージャーを注入し、$this->entityTypeManager->getStorage($entity_type)->load($entity_id)でエンティティを読み込んでください。これにより、コードが適切に分離され、モジュールでテストできることが保証されます。

エンティティの保存

// To save an entity.
$entity->save();

これは新しいエンティティと既存のエンティティの両方で機能し、エンティティ自体が新しいかどうかを追跡します。デフォルトでは、コンテンツエンティティの場合、これはIDを持つかどうかによって決まります。IDを持つエンティティを新しいエンティティとして保存するには(例:何かをインポートする場合)、isNewフラグを適用できます。

// The following will attempt to insert a new node with the ID 5, this will fail if that node already exists.
$node->nid->value = 5;
$node->enforceIsNew(TRUE);
$node->save();

エンティティの削除

// Delete a single entity.
$entity = \Drupal::entityTypeManager()->getStorage('node')->load(1);
$entity->delete();

// Delete multiple entities at once.
\Drupal::entityTypeManager()->getStorage($entity_type)->delete([$id1 => $entity1, $id2 => $entity2]);

アクセス制御

acces()メソッドを使用すると、誰がエンティティに対して何ができるかを確認できます。このメソッドはさまざまな操作をサポートしており、標準的な操作はview、update、delete、createです。createは少し特別です。以下を参照してください。

アクセスチェックはアクセスコントローラーに委譲されます。(TODO:リンクを追加)

// Check view access of an entity.
// This defaults to check access for the currently logged in user.
if ($entity->access('view')) {

}

// Check if a given user can delete an entity.
if ($entity->access('delete', $account)) {

}

作成アクセスを確認するとき、通常はエンティティがまだ存在しません。誰かが作成できるかどうかを確認するためだけにエンティティを作成するのはコストのかかる操作です。したがって、作成アクセスはアクセスコントローラーで直接確認する必要があります。

\Drupal::entityTypeManager()->getAccessControlHandler('node')->createAccess('article');

エンティティが既に存在する場合、$entity->access('create')も機能します。これは、他の操作がアクセスコントローラーのaccess()メソッドに転送するのと同様に、createAccess()メソッドに転送するだけです。

注記。 一部のオンラインガイドでは\Drupal::entityManager()が使用されていますが、8.xでは非推奨となり、9.xで削除される予定です。したがって、\Drupal::entityManager()の代わりに\Drupal::entityTypeManager()を使用できます。