4

When I create a node like this:

$nodeSetup = [
  'nid' => NULL,
  'type' => $bundle,
  'uid' => $uid,
  'revision' => 0,
  'status' => 1,
  'body' => ['format' => 'full_html', 'value' => Xss::filter($body)],
];
$_node = Node::create($nodeSetup);

the body value and format work fine. But, when I load an existing node, how can I set the body value keeping the format? This didnt work:

$_node->body->format = 'full_html';
$_node->body->set('format', 'full_html');
$_node->save();

2 Answers 2

12

The following worked for me,

$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$node->body->value = 'body';
$node->body->format = 'full_html';//omitting this will retain existing format
$node->save();
2
  • $node->body->format = 'full_html'; didnt work for me. But, when the node was created with that format in the first place, $node->body->value = 'body'; works. But using the ->set() function seems to overwrite the format setting. Very strange and 0 documented...
    – Alex
    Commented Oct 20, 2017 at 10:34
  • 3
    @Alex, the answer seems OK to me, you can set properties of the field one at a time. set() is applied on the entity, not the field. If you want to set a field, use setValue() to set all properties at once and for this you provide an array (like you did already when creating the node).
    – 4uk4
    Commented Oct 20, 2017 at 11:50
7

Kstack's solution works. Another option is to supply the value and format together in an array like so:

$node = \Drupal::entityTypeManager()->getStorage('node')->load(1);
$node->body->setValue(['value' => 'body', 'format' => 'full_html']);
$node->save();

Your Answer

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

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