logo

パレット - カラフルに🎨

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

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

Scroll
03/10/2019, by Ivan

エンティティのフィールド値を取得するのはかなり簡単ですが、これを行う方法はいくつかあります。カスタムコードでフィールド値を扱う最善の方法を見ていきましょう。フィールドの扱いに関する最新情報は、いつでも公式ウェブサイトで確認できます:

https://www.drupal.org/docs/8/api/entity-api/working-with-the-entity-api

この記事では、値を扱う例を見ていきます。 

特定のフィールドがどう動作するかを覚える必要はありません。いつでもこのページに戻って思い出せます。時間が経つにつれ、ますますドキュメントを参照するようになり、Drupal でフィールドを扱うのがいかに簡単かに気づくでしょう。それまでは、このページをブックマークして、いつでもチートシートを手元に置けます。

ノードの操作

nid でノードを読み込む:

$nid = 234;
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$node = $node_storage->load($nid);

ノード ID を取得する:

$node->id();

ノード/エンティティのバンドルを取得する:

$node->bundle();
$entity->getType(); 

フィールド値を取得する:

$node->get('title')->value;
$node->get('created')->value;
$node->get('body')->value;
$node->get('body')->summary;
$node->get('field_foo')->value;
$node->get('field_image')->target_id;

値を取得するのに短い記法を使うこともできます:

$node->title->value;
$node->created->value;
$node->body->value;
$node->body->summary;
$node->field_foo->value;
$node->field_image->target_id;

フィールド値による特定のノードの読み込み:

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article'),
  ->condition('field_terms', 42);
$nids = $query->execute();
$nodes = $node_storage->loadMultiple($nids);

foreach ($nodes as $node) {
  print $node->title->value;
  $node->set('title', "New title for node");
  $node->save();
}

フィールドの値を変更する:

$node->set('title', "New title");
$node->set('body', array(
'summary' => "Teaser",
'value' => "Long text",
'format' => 'basic_html',
));
$node->save();

また、単一の値を持つフィールドには、短い記法を使えます:

$node->title = 'New title';
$node->field_text = 'text';

複数のフィールドの値を取得する:

$nids = \Drupal::entityQuery('node')->condition('type', 'album')->execute();
$nodes = Node::loadMultiple($nids);

$data = array();
foreach($nodes as $node) {
  $photo = array();
  foreach($node->get('field_image')->getValue() as $file){
    $fid = $file['target_id']; // get file fid;
    $photo[] = \Drupal\file\Entity\File::load($fid)->getFileUri();
  }

  $data[] = array(
    'album_name' => $node->get('field_album_name')->getValue(),
    'place' => $node->get('field_place')->getValue(),
    'author' => $node->get('field_author')->getValue(),
    'photo' => $photo,
  );
}

ファイルフィールドの操作

ファイルは reference フィールドを通じて他のエンティティに追加され、これらのフィールドにアクセスすると、ファイル ID を取得し、その ID からファイル情報を取得できます。

ID でファイルを取得する:

$fid = 42;
$file_storage = \Drupal::entityTypeManager()->getStorage('file');
$file = $file_storage->load($fid);

ノードフィールドからファイルオブジェクトを取得する:

$file = $node->field_image->entity;

ファイルオブジェクトのいくつかのフィールドを取得する:

$file->getFileUri();   // "public://file123.jpg"
// You can transform to file URL from URI: file_url_transform_relative(file_create_url($file->getFileUri()));
// "/sites/default/files/public/file123.jpg"
$file->filename->value;   // "file123.jpg"
$file->filemime->value;   // "image/jpeg"
$file->filesize->value;   // 63518  (size in bytes)
$file->created->value;    // 1511206249  (Unix timestamp)
$file->changed->value;    // 1511234256  (Unix timestamp)
$file->id();

file_managed テーブルから利用できるファイルプロパティの値は、次のように表示できます:

echo $file->uid->target_id;               // 1
echo $file->uid->value;                   // It doesn't work! Use target_id.
echo $file->uid->entity->name->value;
echo $file->uid->entity->timezone->value; // "Asia/Omsk"

Entity Reference フィールドの操作

reference フィールドから複数の値を取得し、foreach を通じて処理できます:

foreach ($node->field_my_entity_reference as $reference) {
  print $reference->target_id;
  print $reference->entity->title->value;
}

entity reference の複数値フィールドを変更する:

$nids = [3,4,5,6];
$node->set('field_my_entity_reference', $nids);
$node->save();

既存の値に entity reference フィールドの新しい値を追加する:

$nids = [3,4,5,6];   // example value
foreach ($nids as $nid) {
  $node->field_my_entity_reference[] = [
    'target_id' => $nid
  ];
}
$node->save();

フィールドの古い値と新しい値を比較する

FieldItemListInterface(すべてのフィールドの背後にあるクラス)には equals() メソッドがあります:

/**
 * Implements hook_entity_update().
 */
function mymodule_entity_update(\Drupal\Core\Entity\EntityInterface $entity) {
  // Make sure the entity actually has the field.
  if (!$entity->hasField('field_wikipage_access') || !isset($entity->original)) {
    return;
  }

  $new_values = $entity->get('field_wikipage_access');
  $old_values = $entity->original->get('field_wikipage_access');

  // Fast boolean: changed or not?
  if ($new_values->equals($old_values)) {
    return;  // Nothing changed, bail early.
  }

  // …otherwise continue (see below).
}

paragraph の操作

$my_paragraph = null;

foreach ($node->get('field_paragraph_reference') as $paragraph) {
  if ($paragraph->entity->getType() == 'your_paragraph_type') {
    $my_paragraph = $paragraph->entity;
  }
}

if (!empty($my_paragraph)) {
  print $my_paragraph->field_somefield->value;

  print $my_paragraph->title->value;  // It doesn't work!
}
else {
  print "The node doesn't have this paragraph type.";
}

paragraph のタイプを取得する:

$my_paragraph->getType();

これらの例は、フックとエンティティオブジェクトを扱うカスタムモジュールを書くために、今後使っていきます。