26

I can create a node using the following code:

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

But if I have the node ID, how can I edit a node?

1
  • 1
    what you want to edit? which field?
    – Yuseferi
    Sep 1, 2016 at 5:16

4 Answers 4

32

You can try this code

<?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();
3
  • 2
    This answer is not the good way, Ivan answer is the good answer
    – Kevin
    May 16, 2018 at 22:10
  • 3
    I don't think any of these answer the original question very well. Is it possible to take an array of values (like in Node::create) and update an existing node? Or, do you need to go through each array item and ->set() fields as the answers above seem to suggest?
    – liquidcms
    Sep 23, 2020 at 19:03
  • 1
    @liquidcms a entity have method toArray return an array of property values, keyed by property name ($node->toArray()). You can use for each and set value for value for the field you want to update.
    – MrD
    Sep 24, 2020 at 4:12
8
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
0
8

You can use the Entity's API to perform the updates.

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

Old method works too for me:

$node=node_load($nid);
print_r($node->body->format);
$node->body->format='full_html';
print_r($node->body->format);
$node->save();
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.