以编程方式更新节点


19

我可以使用以下代码创建一个节点:

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

但是,如果我具有节点ID,该如何编辑节点?


您要编辑什么?哪个领域?
Yusef

Answers:


23

您可以尝试此代码

<?php
use Drupal\node\Entity\Node;

$node = Node::load($nid);
//set value for field
$node->body->value = 'body';
$node->body->format = 'full_html';
//field tag
$node->field_tags = [1];
//field image
$field_image = array(
    'target_id' => $fileID,
    'alt' => "My 'alt'",
    'title' => "My 'title'",
);
$node->field_image = $field_image;

//save to update node
$node->save();

此答案不是好方法,Ivan答案是好答案
凯文(Kevin)

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

并修改为例如自定义字段:es。field_mycustomfield ???
BOES

$node = \Drupal::entityManager()->getStorage('node')->load($nid);
JF Kiwad,


1

您可以使用实体的API执行更新。

$node = Node::load($id);

if ($node instanceof NodeInterface) {
  try {
    $node->set('title', 'My Title');
    $node->set('field_textfield', 'My textfield value');
    $node->save();
  }
  catch (\Exception $e) {
    watchdog_exception('myerrorid', $e);
  }
}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.