0

My content type has a node reference field that allows users to enter an unlimited amount of nodes in. I need to programmatically change what comes first in this list.

Using the code below I'm able to obtain the data from the field.

$node = \Drupal::entityTypeManager()->getStorage('node')->load($function);
$focus = $node->field_focus_area->getValue();

And it produces:

array(2) {
  [0]=>
  array(1) {
    ["target_id"]=>
    string(2) "31"
  }
  [1]=>
  array(1) {
    ["target_id"]=>
    string(3) "161"
  }
}

In order to rearrange it I tried doing

$newOrder[0] = ['target_id'=> 161]; 
$newOrder[1] = ['target_id'=> 31];

$focus->field_focus_area->rekey($newOrder);

But it was then when I realized that rekey was a protected function so I could use it. How would I programmatically rearrange the deltas (if that's what you'd call it) of an entity reference field programmatically?

1

After getting and rearranging the field data you can set it again:

$node->field_focus_area->setValue($newOrder);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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