20

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?

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

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();
| improve this answer | |
  • This answer is not the good way, Ivan answer is the good answer – Kevin May 16 '18 at 22:10
6
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
| improve this answer | |
  • and as modified for example the custom field: es. field_mycustomfield ??? – BOES Jan 19 '16 at 20:42
  • or $node = \Drupal::entityManager()->getStorage('node')->load($nid); – JFK Jan 25 '19 at 18:25
2

node_load is deprecated in Drupal 8.x, will be removed before Drupal 9.0. Use \Drupal\node\Entity\Node::load().

Ref https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/node_load/8.3.x

| improve this answer | |
1

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);
  }
}
| improve this answer | |
0

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();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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