Drupal 8 : Programmatically create a node with Paragraph fields.

To create a node which has a paragraph field you must create a Paragraph Item and respective object has to be referenced to the field. If this is a multiple add more field you can just loop this with the appendItem() for multiple items.

Sample code:

$node // Object of a node.
 
$paragraph = Paragraph::create([
  'type' => 'paragraph_machine_name',
  'paragraph_field_1' => 'value1',
  'paragraph_field_2' => 'value2',
  'paragraph_field_3' => 'value3',
]);
 
$paragraph->save();
 
$node->paragraph_field_referenced->appendItem($paragraph);
 
$node->save();
Category: