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?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityYou 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();
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);
}
}
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();