I have a custom module which ultimately creates a node of a given type. It gets the fields of that node type and creates my own form with them, HOWEVER, it does not preserve that node's order of fields.

I can do it manually, but would prefer to follow one of the display mode's configuration, like 'view' or 'form'

How can I access the field weights in PHP?

1 Answer 1


If $build is your own form, keyed by field names, you can try something like this:

$display = \Drupal::service('entity_display.repository')
  ->getFormDisplay('node', 'given_type');

foreach ($display->getComponents() as $name => $options) {
  if (isset($build[$name])) {
    $build[$name]['#weight'] = $options['weight'];
  • YES! that seems to do the trick. Thank you. Mar 17 at 13:16
  • I posed the question in slack, but one field that does not appear with this solution is "body". How do I find that? Apr 25 at 14:52

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.