Field weight in display mode is not respected on custom entity I have a custom entity type with a set of base fields and I can create/view/update/delete entities. However When I create &amp; enabled a custom view mode to the entity type and set to display subset of fields (using Manage display) in a page using below code:
$view_builder = $this-&gt;entityTypeManager-&gt;getViewBuilder('my_entity');
$build['top_summary'] = $view_builder-&gt;view($entity, 'summary');

The fields get rendered, but not in the order they are in the view mode. They are in the order of the IDs of the fields alphabetically. So if the entity has these fields in this order:

First name
Last name
Email

They get displayed as

Email
First name
Last name

I can hide fields using the hidden section, but can't change the visible fields' order.
Updating the fields' order in core.entity_view_display.[ENTITY_TYPE].[BUNDLE].[VIEW MODE] does not help as the fields are sorted alphabetically on config import/export
After debugging the Drupal\Core\Field\FormaterBase on how the fields getting rendered, it seems the weights are getting applied to each field in Drupal\Core\Entity\EntityViewBuidler, but they are not getting rendered in the order at the entity level.
So providing a theme for the entity using hook_theme and a preprocess solves this issue. Here is the code:
// mymodule.module

use Drupal\Core\Render\Element;

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'myentity' =&gt; [
      'render element' =&gt; 'elements',
    ],
  ];
}

/**
 * Prepares variables for myentity templates.
 *
 * Default template: myentity.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the entity
 *     information and any fields attached to the entity.
 *   - attributes: HTML attributes for the containing element.
 */
function template_preprocess_myentity(array &amp;$variables) {
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

&lt;!-- myentitty.html.twig --&gt;
&lt;article{{ attributes }}&gt;
  {% if content %}
    {{- content -}}
  {% endif %}
&lt;/article&gt;