Prepopulate node form in form alter with created paragraphs

Created on 8 April 2018, about 7 years ago
Updated 26 January 2024, over 1 year ago

Hi guys,

I am using Paragraphs to create subitems in a node. For one particular node I need to populate the node add form (through hook_form_alter) with already created paragraphs.

My last effort is this:

if ($form_id == "node_schedule_form") {
      $paragraph = \Drupal\paragraphs\Entity\Paragraph::create([
        'type' => 'agenda_item',
        'field_title' => 'Test agenda 1',
        'field_description' =>  'This is test agenda item 1',
      ]);
      $paragraph->save();
      $form['field_agenda_items']['widget'][0]['target_id']['#value'] = $paragraph;

$paragraph = \Drupal\paragraphs\Entity\Paragraph::create([
        'type' => 'agenda_item',
        'field_title' => 'Test agenda 2',
        'field_description' =>  'This is test agenda item 2',
      ]);
      $paragraph->save();
      $form['field_agenda_items']['widget'][1]['target_id']['#value'] = $paragraph;
  }

I tried a lot of variations of $form['field_agenda_items']['widget'] and everything that comes next, but it's not showing up in the form at all.

Can someone point me in the right direction? I am stuck at this for weeks now. I hope someone can help me with this.

Best,
Jessica

💬 Support request
Status

Active

Version

1.2

Component

Code

Created by

🇳🇱Netherlands interactivex

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.

  • 🇮🇳India dhirendra.mishra

    It does not work in my scenario :

    - I was able to achieve above scenario and it does work properly when node is created.
    - It also updates the same paragraph if used in other entity (for ex. user entity)
    - When now editing node and trying to update value of same paragraph field, then it does get updated in node but same paragraph values does not get updated in user entity.
    - I debugged further and found that same paragraph reference is being used but different paragraph revision is loaded (on User entity and node entity).
    - My requirement is : It should also update on user entity when node is edited.

    can you please guide me how to achieve this ?

Production build 0.71.5 2024