I am trying to reorder some paragraphs based on a text field within them on node save so the author does not need to maintain the alphabetical order manually, but when I save the node all values are lost. I tried matching the array from $node->get('field_paragraphs')->getValue(), but that does not seem to work.
function mymodule_node_presave(NodeInterface $node) {
if ($node->bundle() == 'page' && $node>get('field_paragraphs')->count() > 1) {
$values = $node->get('field_paragraphs')->getValue();
$entities = $node->get('field_paragraphs')->referencedEntities();
uasort($entities, function ($a, $b) {
return Unicode::strcasecmp($a->get('field_text')->value, $b->get('field_text')->value);
});
$new_values = [];
foreach ($entities as &$entity) {
$id = $entity->id();
$new_value = [
'target_id' => $id,
'target_revison_id' => $entity->getRevisionId(),
];
$index = array_search($id, array_column($values, 'target_id'));
if (FALSE !== $index && isset($values[$index]['subform'])) {
$new_value['subform'] = $values[$index]['subform'];
}
$new_values[] = $new_value;
}
$node->set('field_paragraphs', $new_values);
}
}