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) {
  array(1) {
    string(2) "31"
  array(1) {
    string(3) "161"

In order to rearrange it I tried doing

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


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 Answer 1


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


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.