How to create paragraph programmatically Drupal 8/9/10
— Drupal — 1 min read
In one of projects which I worked on I had to manually add the paragraph field via code due to the complex structure that was maintained in earlier version of site (Drupal 7). Have a look at the below code to see how I added the paragraphs programamatically
use Drupal\paragraphs\Entity\Paragraph;
$para = [ 'type' => 'text', 'field_text' => array( "value" => "test content", "format" => "basic_html" ),];$paragraph = Paragraph::create($para);$paragraph->save();
Lets see how to add the above created paragraph to a node
$node->set('field_mypara', [ 'target_id' => $paragraph->id(), 'target_revision_id' => $paragraph->getRevisionId(),]);
Here "field_para" corresponds to the machine name of paragraph field in the content type
The above example was of paragaph with text field, now lets see how to add other types of field to the paragraph prgramatically
Paragraph with Link field
$para = [ 'type' => 'link', 'title' => 'Example with Link', 'field_link' => [ 'uri' => $link['url'], 'title' => $link['title'], ],]
$para['field_link_type'] = ['target_id' => $ID];
$link_paragraph = Paragraph::create($para);$link_paragraph->save();
Paragraph with a taxonomy field reference
$para = [ 'type' => 'referece', 'title' => 'Example with taxonomy reference', 'field_type' => ['target_id' => $ID],]
$reference_paragraph = Paragraph::create($para);$reference_paragraph->save();
In the above example $ID is the taxonomy term ID.
Paragraph with image field $para = [ 'type' => 'image', 'field_media' => array( 'target_id' => $drupalMedia->id(), )];$image_paragraph = Paragraph::create($para );$image_paragraph->save();
Hope this helps !!!