0

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);
  }
}
0

1 Answer 1

0

You don’t need to populate an array with the IDs of the referenced entities. You just need to use a single line, the following one.

$node->set('field_paragraphs', $entities);

The code you are using can be simplified to the following one.

function mymodule_node_presave(NodeInterface $node) {
  if ($node->bundle() == 'page' && $node>get('field_paragraphs')->count() > 1) {
    $entities = $node->get('field_paragraphs')->referencedEntities();
    uasort($entities, function ($a, $b) {
      return Unicode::strcasecmp($a->get('field_text')->value, $b->get('field_text')->value);
    });

    $node->set('field_paragraphs', $entities);
  }
}

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.