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!