Lập trình cập nhật một nút


19

Tôi có thể tạo một nút bằng mã sau đây:

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

Nhưng nếu tôi có ID nút, làm thế nào tôi có thể chỉnh sửa một nút?


những gì bạn muốn chỉnh sửa? lĩnh vực nào
— Yusef

Câu trả lời:


23

Bạn có thể thử mã này

<?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();

Câu trả lời này không phải là cách hay, câu trả lời của Ivan là câu trả lời hay
— Kevin

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

và như đã sửa đổi, ví dụ như trường tùy chỉnh: es. lĩnh vực_mycustomfield ???
— BOES

hoặc $node = \Drupal::entityManager()->getStorage('node')->load($nid);
— JF Kiwad


1

Bạn có thể sử dụng API của Thực thể để thực hiện các cập nhật.

$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);
  }
}

0

Phương pháp cũ hoạt động quá đối với tôi:

$node=node_load($nid);
print_r($node->body->format);
$node->body->format='full_html';
print_r($node->body->format);
$node->save();
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookie và Chính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.