Skip to content

Instantly share code, notes, and snippets.

@jmolivas
Created September 24, 2019 17:10
Show Gist options
  • Save jmolivas/f0c41255cd02e34e3409584130c91931 to your computer and use it in GitHub Desktop.
Save jmolivas/f0c41255cd02e34e3409584130c91931 to your computer and use it in GitHub Desktop.
Code snippet to merge several paragraphs fields into a single field.
<?php
$nodeManager = \Drupal::entityTypeManager()->getStorage('node');
$nodes = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties([
'type' => 'landing'
]);
$fields = [
'field_landing_top',
'field_landing_highlighted',
'field_landing_middle',
'field_landing_bottom',
];
foreach ($nodes as $node) {
echo 'Updating node ' . $node->id() . ' - ' . $node->label() . PHP_EOL;
foreach ($fields as $field) {
echo 'Syncing field ' . $field . PHP_EOL;
if ($node->hasField($field)) {
$paragraphs = $node->get($field)->referencedEntities();
if (!empty($paragraphs)) {
foreach ($paragraphs as $paragraph) {
$node->field_components[] = [
'target_id' => $paragraph->id(),
'target_revision_id' => $paragraph->getRevisionId(),
];
echo $paragraph->id() . ' - ' . $paragraph->getType() . PHP_EOL;
}
}
// Unset paragraph data
$node->$field = [];
}
}
$node->save();
}
// use with Drupal Console
// copy file to `console/snippet/` directory
// drupal ahoy drupal snippet --file=console/snippet/merge_landing_paragraphs.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment