0

In Drupal 8, I have a content type and more than a few nodes that have a Paragraph field with unlimited number of values, and so I need to programmatically add a paragraph at an index to the existing values in the field. I know in the form editor widget I'm able to add a field value then drag the field to the order that I need, or change the weight then save the content.

I'm currently loading the node and appending the value like so

    $paragraph_node = Paragraph::create($fields);
    $paragraph_node->save();

    $node = Node::load($nid);

    $node->field_paragraph_repeater->appendItem(
      [
        'target_id' => $paragraph_node->id(),
        'target_revision_id' => $paragraph_node->getRevisionId(),
      ]
    );

    $node->save();

but this only adds the value at the end, how would I be able to add this with a weight?

1 Answer 1

0

You can get the field values as an array and then use array_splice to insert your new value where you want it. See Insert new item in array on any position in PHP.

$values = $node->get('field_paragraph_repeater')->getValue();
$addition = [
  'target_id' => $paragraph_node->id(),
  'target_revision_id' => $paragraph_node->getRevisionId(),
];
$addition_index = 3;

// Insert the new value into your $values array.
array_splice($values, $addition_index, 0, [$addition]);

// Set the value on your node and save.
$node->set('field_paragraph_repeater', $values);
$node->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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