6

How do I save the format used for a node body?

I am using the following code, but it doesn't work.

$article = Node::create(array('type' => 'article'));
$article->setTitle($node->title);
$article->set('body', "My body...");
$article->setPublished(TRUE);
$article->body->format = 'full_html';
$article->save();

How can I achieve this?

EDIT:

Fixed:

Right code:

$article = Node::create(array('type' => 'article'));
$article->setTitle($node->title);
$article->body->value = $node->body;
$article->body->format = 'full_html';
$article->setPublished(TRUE);
$article->save();
  • 2
    Clarify "does not work", what did you expect and what happens? this looks fine to me, setting the body twice, once with set() and once directly is a bit strange, I'd suggest either pass both value and format to set() or use body->vlue = 'My body'.. – Berdir Feb 4 '15 at 18:22
  • I would also not use the Node class directly. The class handling the node entity could be different. There is entity_create(). – kiamlaluno Feb 4 '15 at 19:58
  • @Berdir My Post was edited :( the line what does not work is $article->body->format = 'full_html'; when I save the node everything were saved except body->format. – rpayanm Feb 4 '15 at 21:29
  • have a look at this link will answer your question stackoverflow.com/questions/24172791/… – DEVARAJ JOHNSON Feb 5 '15 at 16:47
  • Please don't incorporate the answer into the question. Please add a full answer and mark it as accepted. – leymannx Jan 27 '17 at 8:35
3

// $node is supposed to be previously defined node object.

$article = Node::create(array(
  'type'     => 'article',
  'langcode' => 'en,
  'title'    => $node->title->value,
  'body'     => ['value' => $node->body->value, 'format' => 'full_html'],
  'status'   => 1,
));
$article->save();

This is the code if in case, anyone wants it.

1

You left out ->value: it should be $article->setTitle($node->title->value); but also $node->body->value I think. This likely throws an exception as a result and then something it eats it up so you don't get an error but it's not working indeed.

  • $node is a object stdClass that I created. – rpayanm Feb 7 '15 at 0:12
0

For an existing node, you can set the body with format simply as follows:

$node->body = array('format' => 'full_html', 'value' => $body);
$node->save();

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.