I'm trying to create a block with a label list using all labels of a specific field type, entity_reference_revisions.

I created a Block plugin and load the EntityTypeManager service. I tried:

    $values = array(
      'targetEntityType' => 'node',
      'bundle' => $bundle,
      'mode' => $view_mode,
      'status' => TRUE,
    $entity_view_display = $this->entityType->getStorage('entity_view_display')->create($values);
    $fields = $entity_view_display->get('fieldDefinitions');
    $labels = [];
    foreach ($fields as $field) {
      if($field->getFieldStorageDefinition()->getType() == 'entity_reference_revisions') {
        $labels[] = $field->get('label');

The problem is that I get the fields in a wrong order, and I can't get the weight attribute.

  • The weight is configured in the viewmode, not in the field definition, try $entity_view_display->getComponents(). BTW you know you create a viewmode instead of loading an existing one in the first line and so only get default values? – 4k4 May 28 '18 at 12:08

I solved it loading the field definition using entityManager, I got the weight attribute, and then ordered the labels by weight.

$node = $this->requestStack->getCurrentRequest()->get('node');
$bundle = $node->getType();
$view_mode = 'full';

$fields = [];
foreach($this->entityManager->getFieldDefinitions('node', $bundle)  as $field_name => $field_definition) {
  if($field_definition->getType() == 'entity_reference_revisions') {
    $field_name = $field_definition->getName();
    $element = $node->$field_name->view($view_mode);
    $fields[] = [
      'name' => $field_name,
      'label' => $field_definition->getLabel(),
      'weight' => $element['#weight'],


usort($fields, [$this, 'sortByWeight']);
| improve this answer | |

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.