3

I have a content type with a paragraph entity reference field and every time a user is going to add a node of this type I want to have the paragraph field already open and prefilled. I've tried with hook_form_alter, but it's not opening the paragraph form with prefilled values.

[SOLUTION] 4k4's answer on another post is the answer to this question. I did some rework of the code to make it more efficient:

 /**
 * Implements hook_ENTITY_TYPE_create() for 'node'.
 */
function hook_node_create(\Drupal\node\NodeInterface $node) {

  if ($node->getType() == 'my_content_type') {
    $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('my_voc');

    foreach ($terms as $term) {
      $paragraph = \Drupal\paragraphs\Entity\Paragraph::create([
        'type' => 'pmr_item',
        'field_title' => array(
          "value" => $term->name,
        ),
      ]);
      $paragraph->save();

      $node->field_pmr_items[] = $paragraph;
  }
 }
}
  • 3
    see drupal.stackexchange.com/questions/259275/… – 4k4 Apr 24 '18 at 13:04
  • 4k4's link is gold! – sonfd Apr 24 '18 at 13:16
  • I've seen you've edited the answer in the linked post. I've rejected the edit, because the original code was based on the question over there, which I'd changed only where relevant for moving it to the hook. Second reason was, I didn't save the paragraph intentionally, because you don't know whether the node form is submitted and if not, then the saved paragraphs are orphaned in the database. – 4k4 Apr 28 '18 at 16:17
0

In the form display for that content type you can tell the paragraph field to have a default paragraph selected. So when new nodes are created it will appear there

Then on your actually paragraph you'd need to set the default values for each field it contains (Just by editing those fields on the paragraph and setting the defaults)

  • 1
    Thanks! But I have to pre fill the paragraph with data I need to get from another node so I need to do it from hook_form_alter. Any thoughts about how to achieve that? – Jessica IX Apr 24 '18 at 13:11

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.