Skip to content

Instantly share code, notes, and snippets.

@rwohleb
Created November 20, 2019 04:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwohleb/63fc3866a6a7da7caf582eae327ddac5 to your computer and use it in GitHub Desktop.
Save rwohleb/63fc3866a6a7da7caf582eae327ddac5 to your computer and use it in GitHub Desktop.
Drupal 8: Convert text field to paragraph
<?php
use Drupal\Core\Utility\UpdateException;
use Drupal\paragraphs\Entity\Paragraph;
/**
* Convert news,blog,event body field to paragraphs.
*/
function custom_util_post_update_convert_newsblogevent_body(&$sandbox) {
$bundles = [
'news',
'blog',
'event',
];
foreach ($bundles as $bundle) {
if ($nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => $bundle])) {
$body_field = 'field_' . $bundle . '_body';
$content_field = 'field_' . $bundle . '_content';
foreach ($nodes as $node) {
// Make sure we actually have both fields.
if ($node->hasField($body_field) && $node->hasField($content_field)) {
// Don't try to migrate the body if the content field already has paragraphs in it.
if (!$node->get($body_field)->isEmpty() && $node->get($content_field)->isEmpty()) {
$paragraph = Paragraph::create(['type' => 'formatted_text']);
$paragraph->set('field_formatted_text_body', $node->get($body_field)->first()->getValue());
$paragraph->isNew();
$paragraph->save();
$content = [
[
'target_id' => $paragraph->id(),
'target_revision_id' => $paragraph->getRevisionId(),
]
];
$node->set($content_field, $content);
$node->save();
}
}
else {
throw new UpdateException('Either body field or content field is missing for ' . $bundle);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment