Created
November 20, 2019 04:11
-
-
Save rwohleb/63fc3866a6a7da7caf582eae327ddac5 to your computer and use it in GitHub Desktop.
Drupal 8: Convert text field to paragraph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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