0

I am trying to resave a number of nodes to apply the text format changes to the body field. I’ve written a drush command to do this. The command does update the text format, but the text in the body field remains unprocessed.

public function saveNode() {
    $result = $this->entityTypeManager->getStorage('node');
    foreach ($result as $node) {
        $node->save();
      }
    }
  }

If I manually edit and save the node the text in the body field is correctly processed, but not when saved programmatically.

Notes: By "unprocessed" I mean the body field is still showing faulty HTML. If I manually edit and save the node the faulty HTML is fixed.

3
  • What do you mean by "unprocessed"? Text field value is not processed until the field is rendered, so if you are doing something unusual like saving rendered field output, you need to render the field first. Aug 10, 2022 at 15:18
  • Changing the text format won't update the text in the database, if that's what you're expecting. Filters are applied on render, not for storage
    – Clive
    Aug 10, 2022 at 15:19
  • For an example of applying the renderer, see this answer: drupal.stackexchange.com/a/293716/5147 Aug 10, 2022 at 15:20

1 Answer 1

1

I’m not sure that I understand what you code is doing. Something like this might work.

$html_format = 'full_html';
$type = 'some_type';

$nodes = \Drupal::entityTypeManager()
            ->getStorage('node')
            ->loadByProperties([
                'type' => $type,
            ]);

foreach ($nodes as $node) {

    $current_body_data = $node->get('body')->getValue();
    $current_body_value = $current_body_data[0]['value'];

    $new_body_data = [
            'value' => $current_body_value,
            'format' => $html_format,
        ];
    
    $node->set('body', $new_body_data);

    $node->save();

}

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.