Score:-4

Referencing a paragraph-type via code

tf flag

I'm new to Drupal so the following may not be accurate.

I want to reference a paragraph-type from an Entity reference revisions field created in a content type using a hook_form_alter and I can't find the way to do so.

I've created a content type using the UI and also a new Entity reference revisions field inside it without selecting a paragraph. I need to select it by code (and even more than just one).

Also I need the paragraph(s) to be opened in the form for editing.

Can someone please send a working example for that?

Ways I've tried so far:

1.

$form['my_paragraph_field'] = [
  '#type' => 'entity_reference_revisions',
  '#entity_type' => 'paragraph',
  '#entity' => $paragraph,
  '#bundle' => $paragraph_type->id(),
  '#cardinality' => 1,
  '#title' => 'Paragraph',
  '#default_value' => $paragraph,
  '#weight' => 10,
  '#element_validate' => [],
  '#process' => []
];
  $p = ParagraphsType::load('test_paragraph');

  $id = $p->id();

  $paragraphs = ParagraphsType::loadMultiple([$id]); // Load entities 
  $form['my_paragraph_field']['widget'][0]['#entity'] = $paragraphs;
$form['field_test_paragraph']['#selection_settings']['target_bundles'] = ['test_paragraph', 'bundle_2'];
$node = $form_state->getFormObject()->getEntity();
$storage = \Drupal::entityTypeManager()->getStorage('paragraph');
$node->set('field_test_paragraph',  [
  'target_id' => $id,
  'target_revision_id' => $storage->getLatestRevisionId($id),
]);

If the question is not clear enough, please tell me what is missing.

Thanks!

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.