I would like to programatically populate a paragraph field with a default value for one of my content types.
I came up with the following solution:
use \Drupal\Node\NodeInterface;
use \Drupal\paragraphs\Entity\Paragraph;
function my_site_node_create(NodeInterface $node) {
switch ($node->getType()){
case 'my_content_type':
$paragraph = Paragraph::create([
'type' => 'references', // paragraph type machine name
'field_references_title' => [ // paragraph's field machine name
'value' => 'Some examples of what we have done' // body field value
],
]);
$paragraph->save();
$node->set('field_paragraphs_content', [
[
'target_id' => $paragraph->id(),
'target_revision_id' => $paragraph->getRevisionId(),
],
]);
break;
}
}
This code seems to work but im worried I might be creating useless Paragraph-entities when the user doesn't save this node (because of the '$paragraph->save()').
How can I avoid this?