How to create paragraphs item programmatically in D8?

Created on 15 April 2016, over 8 years ago
Updated 16 March 2023, over 1 year ago

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?

💬 Support request
Status

Fixed

Component

Documentation

Created by

🇩🇪Germany derMatze

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇩🇰Denmark ressa Copenhagen

    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, 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 parent entity's paragraphs field.
      $node->field_para->appendItem($paragraph);
      $paragraph->save();
    }
    $node->save();
    
  • 🇫🇮Finland oakulm

    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.

Production build 0.71.5 2024