LoginSignup
3
4

More than 5 years have passed since last update.

Drupal8で記事(node)などエンティティ(entity)の情報を取得する方法 其の一

Last updated at Posted at 2017-09-29

Drupalでモジュールなどを開発する際に、ユーザ情報や記事情報など必要なオブジェクトを取得し操作を行なう事がある。こう言った各種情報を取得する方法をメモする。

Entity(エンティティ)

DrupalではEntity(エンティティ)という言葉があちこちで登場する。Drupalで扱われる記事(node)やユーザ(user)、タクソノミ(taxonomy)などは エンティティ と呼ばれている。要するに記事情報であろうとユーザ情報であろうと、これらは全てエンティティ。そのエンティティが記事なのかユーザなのかは エンティティタイプ の違い。(だと、解釈している)。

\Drupal::entityManager()->getStorage()

Drupalでエンティティを取得するには \Drupal::entityManager()->getStorage($entity_type)を利用する。記事(node)を扱う場合には

$node_storage = \Drupal::entityManager()->getStorage('node');
//続いて、取得したStorageを利用して記事(node)IDに『1』を持つ記事を取得する。↓↓
$node = $node_storage->load(1); 

もしくは、\Drupal::entityManager()->getStorage()を使わずに以下のようにしても良い?むしろこう書くべきなのかもしれない。

use \Drupal\node\Entity\Node;
$node = Node::load(1);

EntityType

今までに使ったモノだけ列挙しておく。これ以外にもあるだろう…。

種類 名称
ユーザ user
コンテンツ node
コンテンツタイプ node_type
タクソノミ taxonomy_term

記事(node)

$node = $node_storage->load(1);とすることで$nodeには記事(node)のオブジェクトが格納されている。

本文とタイトルを操作する

記事(node)オブジェクトの値を操作する場合、自身で作成・追加したフィールドと本文やタイトルなどの項目は扱い方が異なる。

タイトルと本文に値をセットするには、このような記述を行う。

//本文を設定
$node->body->value = "本文";
$node->body->format = "full_html";

//タイトルを設定/取得
$node->setTitle("title");
echo $node->getTitle();  //output:"title"

自身で追加したフィールド

自身でフィールドを追加した場合は、次のような記述となる。

// (マシンネームが)field_text_1というフィールドに"textvalue"という文字列を設定する
//$node->set($name, $value, $notify = TRUE);

$field_name = "field_text_1";
$field_value = "textvalue";

$node->set( $field_name, $field_value);
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4