0

I have a repeatable paragraph in which I have several fields. I use it to build a table.

The Manage Display is set to the order I want the fields inside the repeatable paragraphs.

If I render this field the Drupal way in Twig then it outputs the data, in the correct order, but I can't access the individual fields to add custom mark up I need. I would like to loop through the fields separately in Twig or a module/theme PHP.

BUT... if I obtain the fields in the theme/module or even Twig using something like this:

$paragraph->getFields()

then the fields do not come out in the Manage Display order. They come out in another and wrong order.

If I inspect the Paragraph object, there is a render field for #fields which lists them in the right order, but I just cant seem to extract the data in this field. I have no idea how to access #fields. The above method getFields() seems to get the exact same as what getFieldDefinitions() does and neither are in the correct order.

There is no "weight" data either that I could use to put them in the right order. I can't find anything I can access to allow me to put the fields in the right order.

Does anyone have a solution for this?

Thanks

enter image description here

1 Answer 1

1

The #fields array is a static cache and you see the order in which the fields were accessed, probably in the build process in preparation for the template. But you can't rely on that, render arrays are cached on multiple levels, and in future requests, you might be the first one accessing the fields. To get the correct order you have to load the display object:

$display = \Drupal::service('entity_display.repository')
  ->getViewDisplay('paragraph', 'paragraph_type');

See Get Field Weights Programmatically for a code example.

1
  • This did it! Thank you so much. I then used uasort to sort them by weight. Then I used entity->getFields() to get the actual data. Then I could iterate though the display fields above which are in the correct order and fetch the data using display field as the key in the fields list. Commented Jun 8 at 20:26

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.