Skip to main content

Drupal Node 常用操作

Submitted by admin on Mon, 02/10/2020 - 08:39

Node相關

讀取所有特定類別的node

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

 

在node上面的field_tag新增term ID

$node->field_tags[] = '2';
$node->field_tags->appendItem([target_id => '1']);     #這兩種都可以

 

移除重複的entity reference

$node->field_entityreference[] = $some_nid;
$node->field_entityreference->setValue(array_unique($node->field_entityreference->getValue()));

 

node revision相關

$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);    //讀取node
\Drupal::entityManager()->getStorage('node')->revisionIds($node);        //讀取這個node的所有revision

$node_revision = \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);   //讀取某個特定revision內容

//更新revision的timestamp以及log並存成最新版revision
$node_revision->vid = null;
$node_revision->revision_timestamp = time();
$node_revision->revision_log = "my log message";
$node_revision->save();

 

NID相關

//拿一個node的nid
$node->id();  // 123

//從nid拿node
$nid = 123;     // example value
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$node = $node_storage->load($nid);

 

多重條件檢索node以及操作內容

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article'),
  ->condition('field_foo', 42);
$nids = $query->execute();
$nodes = $node_storage->loadMultiple($nids);
 
foreach ($nodes as $n) {
  echo $n->title->value;  
 
  // do whatever you would do with a node object (set fields, save, etc.)
  $n->set('title', "this is a test");
  $n->save();
}

 

Get and set field

#get
$node->get('title')->value;           // "Lorem Ipsum..."
$node->get('created')->value;         // 1510948801
$node->get('body')->value;            // "The full node body, <strong>with HTML</strong>"
$node->get('body')->summary;          // "This is the summary"
// a custom text field
$node->get('field_foo')->value;       // "whatever is in your custom field"
// a file field
$node->get('field_image')->target_id; // 432 (a managed file FID)

#set
$node->set('title', "Moby");
$node->set('body', array(
'summary' => "Book about a whale",
'value' => "Call me Ishmael...",
'format' => 'basic_html',
));
$node->save();    //set後不要忘記這個!

 

刪除node

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

// one
$nid = 42;      // example value
$node = $node_storage->load($nid);
$node->delete();
 
// multiple
$nids = [21,12,45,67];  // example value
$nodes = $node_storage->loadMultiple($nids);
$node_storage->delete($nodes);
 
// multiple, loading one at a time to avoid "out of memory" errors - may be slow
$nids = [21,12,45,67];  // example value
foreach($nids as $nid)
{
  $node = $node_storage->load($nid);
  $node->delete();
}

 

File相關

從file id拿file

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

 

從node裡面拿file entity

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

 

讀取file的資訊

$file->getFileUri();   // "public://file123.jpg"
// if you want the URL without Drupal's custom scheme, you can translate it to a plain URL:
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();              // 432

 

append image by uri

use Drupal\node\Entity\Node;
use Drupal\file\Entity\File;

  $node = Node::load(1);
  $uri = 'public://image.jpg';

  // check first if the file exists for the uri    
  $files = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties(['uri' => $uri]);
  $file = reset($files);

  // if not create a file
  if (!$file) {
    $file = File::create([
      'uri' => $uri,
    ]);
    $file->save();
  }

  $node->field_image[] = [
    'target_id' => $file->id(),
    'alt' => 'Alt text',
    'title' => 'Title',
  ];

  $node->save();