I'm trying to just change the parent paragraph of an already existing child/sub paragraph by using setParentEntity function but it does not work.
Sample code as below
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;
//Load all paragraphs_page nodes
$nids = \Drupal::entityQuery('node')->condition('type','paragraphs_page')->execute();
$nodes = Node::loadMultiple($nids);
foreach ($nodes as $node) {
$paras = $node->field_paragraphs->getValue();
foreach ($paras as $para) {
$paragraph_entity = Paragraph::load($para['target_id']);
if (!empty($paragraph_entity) && $paragraph_entity->getType() == 'old_wrapper') {
// Create the wrapper para first to get the id
$paragraph = Paragraph::create([
'type' => 'new_wrapper',
'field_title' => $paragraph_entity->field_title->getValue(),
]);
$paragraph->save();
$tiles = $paragraph_entity->get('field_tiles')->entity;
$tiles->setParentEntity($paragraph, 'field_tiles');
$paragraph->set('field_tiles', $tiles);
$paragraph->save();
}
}
}
$node->save();
The intent here is not create new/duplicate child paragraphs and just attach the existing ones to the new parent