27 October 2022

Create and add paragraphs programmatically to nodes. After trying to use migrate and feeds. Including migration from field collection to paragraphs or ECK. The final solution for me was to do it manually. Migrate mixed up all of the content. Feeds imported the Paragraphs nicelp

Source code viewer
  1. $csv = <<<END
  2. nid,my_field_value_1,my_field_value_2,my_field_value_3
  3. nid,my_field_value_1,my_field_value_2,my_field_value_3
  4. END;
  5.  
  6. // Split rows into an array.
  7. $rows = str_getcsv($csv, "\n");
  8. foreach($rows as &$row) {
  9. // Get values from a row.
  10. $row = str_getcsv($row, ",");
  11.  
  12. // Create new paragraph based on the input.
  13. $paragraph = \Drupal\paragraphs\Entity\Paragraph::create([
  14. 'type' => 'my_paragaph_type',
  15. 'field_value_1' => $row[1],
  16. 'field_value_2' => $row[2],
  17. 'field_value_3' => $row[3],
  18. ]);
  19. $paragraph->save();
  20.  
  21. // Add it to nodes existing paragraphs list.
  22. $node = \Drupal\node\Entity\Node::load((int) $row[0]);
  23. $current = $node->get('field_my_paragraph_reference')->getValue();
  24. $current[] = [
  25. 'target_id' => $paragraph->id(),
  26. 'target_revision_id' => $paragraph->getRevisionId(),
  27. ];
  28. $node->set('field_my_paragraph_reference', $current);
  29. $node->save();
  30. }
  31.  
Programming Language: PHP