Score:0

Programmatically add value to multi-valued/repeater field at weight/index

cn flag

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?

Score:0
in flag

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();
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.