0

I have a custom entity type with a set of base fields and I can create/view/update/delete entities. However When I create & 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->entityTypeManager->getViewBuilder('my_entity');
$build['top_summary'] = $view_builder->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:

  1. First name
  2. Last name
  3. Email

They get displayed as

  1. Email
  2. First name
  3. 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

2

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' => [
      'render element' => '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 &$variables) {
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}
<!-- myentitty.html.twig -->
<article{{ attributes }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</article>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.