0

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

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'];
  }
}
3
  • YES! that seems to do the trick. Thank you. Commented 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? Commented Apr 25 at 14:52
  • There is no reason why the body field shouldn't work but you have to be careful with the machine name. This field doesn't have the prefix field_.
    – 4uk4
    Commented Jun 6 at 6:19

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.