0

In a node, I have a multi-value field "field_MV" containing 3 items

I don't think it is important, but field_MV is of type "Entity reference revisions" and the items are paragraphs of only one type.

Each paragraph (item) have a field "field_quantity" containing a number.

Here is my exemple:

$node->field_MV[0]->field_quantity->value=5 (paragraph at delta 0)
$node->field_MV[1]->field_quantity->value=3 (paragraph at delta 1)
$node->field_MV[2]->field_quantity->value=7 (paragraph at delta 2)

In hook_node_presave, I would like to loop in the paragraphs to change their delta according the the value of field_quantity (descending)

Here is the result I would like to have:

$node->field_MV[0]->field_quantity->value=7 (previously paragraph delta 2)
$node->field_MV[1]->field_quantity->value=5 (previously paragraph delta 0)
$node->field_MV[2]->field_quantity->value=3 (previously paragraph delta 1)

My question is not how to order (I can handle this), but how to change the delta with something like:

$node->field_MV[0]->set("delta",1);
$node->field_MV[0]->save();
1

You would want to set the field value to an array in the order you want them. Since you are doing this inside hook_node_presave, you don't have to bother saving the node. It will be done for you.

Something like this should work:

$values = $node->get('field_mv')->getValue();

... your sorting function ...

$node->set('field_mv', $values);
  • 1
    Thank you Chance G, it is working except that I have changed the first line into $values = $node->field_mv->referencedEntities(); to be able to get an array that I can sort. If you update your answer, I will vote for it. – Baud Jan 3 '18 at 23:48
  • I changed it to the generic getValue() method. Like most things Drupal, there is more than one way to do things ;) – Chance G Jan 4 '18 at 18:49

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.