Drupal 8 set body field format when invalid format is present
For whatever reason, you've got nodes in Drupal 8 that have body fields without a format. In my case, D6 content migrating to D7 with no corresponding input filter caused my issue. No matter how you got here, you now have to fix it. If you have devel enabled, you can execute this PHP to iterate over all nodes of a given type that do not have a valid input filter.
$nids = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('type', 'blogpost')
->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
$filter_formats = array_keys(filter_formats());
$body_example = '';
$warning_text = '<blockquote class="warning">NOTE: This is a very old migrated blog post. It may have incorrect formatting.</blockquote>';
$adjusted_nids = array();
foreach ($nodes as $nid => $node){
if(!in_array($node->body->format, $filter_formats)){
$node->body->value = $warning_text . $node->body->value;
$node->body->format = 'full_html';
$node->save();
$adjusted_nids[] = $nid;
}
}
dpm($adjusted_nids);
So the above code fetches all nodes of a given content type (in my case: blogpost). Then you iterate over them, checking if their body format is in the list of existing filter formats on your site. If a filter format is set that does not exist on your site, it changes it to the "full_html" format, and adds a warning blockquote above it, which I added some basics CSS to as well.
blockquote.warning{
display:block;
background-color:yellowgreen;
font-color:#FFF;
padding: 5px;
text-align: center;
margin:5px 0px;
}
There is also a DPM output at the end of the PHP code. Given you will likely run this from Devel execute PHP, I figured it was safe to leave. Remove that if it's a problem, but if you can log the affected NID's so you can review how they are altered.
Comments
This was really helpful for…
This was really helpful for me as well moving a bunch of old D6 content forward! Thanks!