0

I want to prefill multiple paragraphs when user click on "add node" for specific content type. What would be a good way to do this ?

4

You can't reuse existing paragraphs, you have to create new paragraphs for each node:

$paragraph1 = Paragraph::create([
  'title' => 'Paragraph 1',
  'type' => 'paragraph_type1',
]);
$paragraph1->save();

$paragraph2 = Paragraph::create([
  'title' => 'Paragraph 2',
  'type' => 'paragraph_type2',
]);
$paragraph2->save();

$node = Node::create([
  'title' => 'Node with two paragraphs',
  'type' => 'article',
  'field_paragraph' => [$paragraph1, $paragraph2],
  ]);
$node->save();

You could place this code in a custom controller:

  public function addCustomContentType() {
    $node = $this->entityTypeManager()->getStorage('node')->create([
      'type' => 'custom_content_type',
    ]);

    // create paragraphs, don't save them yet, in case the node is not submitted

    $paragraph1 = $this->entityTypeManager()->getStorage('paragraph')->create([
      'title' => 'Paragraph 1',
      'type' => 'paragraph_type1',
       // more field data
    ]);

    $paragraph2 = $this->entityTypeManager()->getStorage('paragraph')->create([
      'title' => 'Paragraph 2',
      'type' => 'paragraph_type2',
      // more field data
    ]);

    // prefill the paragraph field in the node with the paragraphs
    $node->field_paragraph = [$paragraph1, $paragraph2];

    $form = $this->entityFormBuilder()->getForm($node);

    return $form;
1

You can hack simple fields during hook_form_alter(), but paragraphs have too complicated structure. It must be done earlier, during fresh node creation, before the form is created.

function MY_MODULE_node_create(Drupal\Core\Entity\EntityInterface $entity) {

  $bundle = $entity->bundle();
  if ($bundle != 'MY_CONTENT_TYPE') {
    return;
  }

  // you may add here additional checks
  // to make sure node creation happens
  // on node add page

  $pg = Paragraph::create([
    'type' => 'MY_PG_MACHINE_NAME',
    'field_reference' => ['target_id' => 111],
    'field_integer' => 2222,
  ]);

  // Insert here as many paragraphs as you need.
  $entity->field_paragraphs = [$pg];

}

See also: hook_entity_create()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.