In the D7 version a new paragraph could programmatically be created by using something like this:

$node = node_load(...);
$entity = entity_create('paragraphs_item', array('field_name' => 'name_of_field_in_node', 'bundle' => 'name_of_paragraph_bundle'));
$entity->setHostEntity('node', $node);
$entity->save();

Mentioned here: https://www.drupal.org/node/2395131

Basically this still works (use "type", instead of "bundle"), but there is no setHostEntity(). Anyone knows how to link the paragraph with the parent/host entity?

Issue fork paragraphs-2707017

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

derMatze created an issue. See original summary.

killua99’s picture

What I know is, now paragraphs on Drupal 8 use entity_reference_revisions maybe you want to take a look in there.

Check how entity_reference_revisions link the paragraphs with the entity who is using it. Remember not only Content Type could use paragraphs.

derMatze’s picture

Meanwhile I found a solution:
First create the paragraph, than add the paragraph to the corresponding node/entity.

$paragraph = Paragraph::create([
'type' => 'paragraph_type_name',
'field_text' => array(
    "value"  =>  '...content...',
    "format" => "full_html"
	),
]);
$paragraph->save();	

$node = entity_load('node', $nid);
$node->field_content = array(
  array(
	  'target_id' => $paragraph->id(),
	  'target_revision_id' => $paragraph->getRevisionId(),
  )
);
Arla’s picture

Status: Active » Fixed

That indeed looks like the standard way to do it.

You can also use appendItem and/or pass the entire Paragraph entity as the value:

$node->field_content->appendItem($paragraph);

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

vijaycs85’s picture

Thanks @derMatze for raising this issue and the solution... landing here from google search :)

bkeller’s picture

Landed here from Google as well, and had to modify a bit to get it to work for my purposes.
I'm using paragraphs with just a text field and an optional image, and a node can have multiple paragraphs attached.
Maybe this will help someone else...

use Drupal\paragraphs\Entity\Paragraph;  // Don't forget to use a little Class...

/**
 * Create a New Paragraph and attach it to it's node
 * @param int $nid
 *  The node id this paragraph should be attached to
 * @param longtext $content
 *  The body text of the paragraph
 * @param int fid
 *  The file id if any, or FALSE
 * 
 */
function CUSTOM_MODULE_create_paragraph($nid, $content, $fid = FALSE) {
  $node = entity_load('node', $nid);
  $paragraph = Paragraph::create(['type' => 'PARAGRAPH_TYPE',]);
  $paragraph->set('TEXT_FIELD_NAME', $content); 
  if ($fid) {
    $file = file_load($fid);
    $paragraph->set('IMAGE_FIELD_NAME', $file);
  }
  $paragraph->isNew();
  $paragraph->save();	
    
  // Grab any existing paragraphs from the node, and add this one 
  $current = $node->get('NODE_FIELD_NAME')->getValue();
  $current[] = array(
      'target_id' => $paragraph->id(),
      'target_revision_id' => $paragraph->getRevisionId(),
    );
  $node->set('NODE_FIELD_NAME', $current);
  $node->save();
}
nitin.k’s picture

Please use below namespace..

use Drupal\paragraphs\Entity\Paragraph;

ben.hamelin’s picture

#7 worked for me
Drupal core 8.3.7
Paragraphs 8.x-1.0

couloir007’s picture

#7 works as well as appendItem except for when I open the node and save it I get this:

This entity (paragraph: 43) cannot be referenced.

8.4.2

couloir007’s picture

Scratch that. I'm feeling like an idiot. I was accidentally adding the wrong paragraph type. It added, but I guess it didn't like it.

miststudent2011’s picture

Here is a better example :

<?php

use Drupal\paragraphs\Entity\Paragraph;

// Create single new paragraph
$paragraph = Paragraph::create([
  'type' => 'paragraph_machine_name',
  'field_machine_name' => 'Field value',
]);
$paragraph->save();

// Create multiple new paragraphs
$multiParagraph1 = Paragraph::create([
  'type' => 'paragraph_machine_name',
  'field_machine_name' => 'Field value',
]);
$multiParagraph2 = Paragraph::create([
  'type' => 'paragraph_machine_name',
  'field_machine_name' => 'Field value',
]);
$multiParagraph1->save();
$multiParagraph2->save();


// Save paragraph to node it belongs to
$newCompanyNode = Node::create([
  'type' => 'node_machine_name',
  'title' => 'new_node_title',
  // Insert a single paragraph
  'node_field_paragraph_machine_name' => array(
    'target_id' => $paragraph->id(),
    'target_revision_id' => $paragraph->getRevisionId(),
  ),
  // Insert multiple paragraphs into the same reference field
  'node_paragraph_field_machine_name' => array(
    array(
      'target_id' => $multiParagraph1->id(),
      'target_revision_id' => $multiParagraph1->getRevisionId(),
    ),
    array(
      'target_id' => $multiParagraph2->id(),
      'target_revision_id' => $multiParagraph2->getRevisionId(),
    ),
  ),
]);

// Makes sure this creates a new node
$newCompanyNode->enforceIsNew();
// Saves the node
// Can also be used without enforceIsNew() which will update the node if a $newCompanyNode->id() already exists
$newCompanyNode->save();

Source :
https://stackoverflow.com/a/48399547/

sibopa’s picture

The #12 here have limitation in case you have an unlimited number of items to add. #7 will work better. Thanks!

sadikyalcin’s picture

Here is a more efficient way for unlimited and nested paragraphs. Note: you do not need to save the paragraphs when creating a new node; the relationship will be assigned automatically.

$parents = [];
foreach($data['parent_paragraph'] as $parent_paragraph) {
        $childs = [];
        foreach($parent_paragraph['child'] as $child) {
                $childs[] = Paragraph::create([
                        'type' => '...',
                        'field_...' => $foo,
                ]);
        }
        
        $parents[] = Paragraph::create([
                'type' => '...',
                'field_...' => $bar
                'field_child' => $childs,
        ]);
}

$new_submission = Node::create([
        'type' => '...',
        'title' => '...',
        'field_paragraphs' => $parents,
]);
$new_submission->save();

Credit to '4k4' on Stack: Source

ahaomar’s picture

I want to create Paragraph types can you some one guide me how can i create via programming

dorficus’s picture

@ahaomar the issue queue probably isn't the best place to be asking that. There is the forum section of Drupal.org and/or Drupal Answers. It's more likely that someone will see your question there and have time to answer rather than in the issue queue where the focus is on specific issues within projects.

With that being said, I suggest looking at the code for Paragraph.php and see how the base paragraph is created then maybe looking at a module that extends paragraphs like Bootstrap Paragraphs and see how those are built so that you can get a starting point.

mtift made their first commit to this issue’s fork.

xandermar’s picture

Workable in Drupal 9

function MY_MODULE_create_paragraph($nid, $content, $fid = false)
{
    $node = \Drupal\node\Entity\Node::load($nid);
    $paragraph = Paragraph::create(['type' => 'PARAGRAPH_TYPE',]);
    $paragraph->set('TEXT_FIELD_NAME', $content);
    if ($fid) {
        $file = file_load($fid);
        $paragraph->set('IMAGE_FIELD_NAME', $file);
    }
    $paragraph->isNew();
    $paragraph->save();

    // Grab any existing paragraphs from the node, and add this one
    $current = $node->get('NODE_FIELD_NAME')->getValue();
    $current[] = array(
      'target_id' => $paragraph->id(),
      'target_revision_id' => $paragraph->getRevisionId(),
    );
    $node->set('NODE_FIELD_NAME', $current);
    $node->save();
}
mxr10_’s picture

Hi team,
I'm having some issues trying to save some field using paragraphs,
Where i run my code happen this:
The first field has value and second is empty
and the next block the first field is empty and second has value
screenshoot
This is my code:

<?php
$paragraph_1 = Paragraph::create([
    'type' => 'field_from_paragraph',
    'field_item_1' => "abcdefghijk",
]);
$paragraph_icon->save();

$paragraph_2 = Paragraph::create([
    'type' => 'field_from_paragraph',
    'field_item_2' => "123456789",
]);
$paragraph_beneficio->save();

$node = Node::create([
    'type' => 'items',
    'field_from_content_type' => array(
        array(
              'target_id' => $paragraph_1->id(),
              'target_revision_id' => $paragraph_1->getRevisionId()
        ),
        array(
              'target_id' => $paragraph_2->id(),
              'target_revision_id' => $paragraph_2->getRevisionId()
        ),
      ),
    ]);

I don't know what to do to fill both field
Could you please help me?
Regards
Mario

ressa’s picture

I was looking for a way to create a new node, and populate a multi-value Paragraphs field, and found this issue. I didn't find the solution here, but finally figured it out so here it is:

$cars = [
  array("Volvo",22),
  array("BMW",15),
  array("Land Rover",17),
];
// print_r($cars);

foreach ($cars as $car) {
  $paragraph = Paragraph::create([
    'type' => 'para_item',
    'field_para_item_name' => $car[0],
    'field_para_item_number' => $car[1],
  ]);
  // Add the paragraphs to the node's paragraphs field one by one.
  $node->field_para->appendItem($paragraph);
  $paragraph->save();
}
$node->save();
oakulm’s picture

Sorry to raise old issues but this keeps popping in Google. You should not include references to concrete classes ie. Paragraph but should use service injection:

\Drupal::entityTypeManager()->getStorage('paragraph')->create([
  'type' => 'param_item',
])

Same goes with Node.