1

Given an entity type id of a fieldable entity type, a bundle name, and a view mode name, how do I construct a url to the respective field_ui form where this view mode can be edited?

The patterns for the route name seem to be:

  • entity.entity_view_display.ENTITY_TYPE_ID.view_mode
  • entity.entity_view_display.ENTITY_TYPE_ID.default

But it seems the parameters have custom names, e.g. /admin/structure/types/manage/{node_type}/display/{view_mode_name}, here the bundle parameter is called node_type.

Is there a generic way to build such urls to field_ui pages for any entity type?

1 Answer 1

2

After searching in the core files I found the pattern, see the example below:

use Drupal\Core\Url;
// The entity type can be 'node'.
$entity_type = 'taxonomy_term';

// Find the bundle entity type, e.g. 'node_type' or .
/** @var \Drupal\Core\Entity\EntityTypeManagerInterface $etm */
$etm = \Drupal::service('entity_type.manager');
$bundle_entity_type = $etm->getDefinition($entity_type)->getBundleEntityType();

if (NULL === $bundle_entity_type) {
  // Not clear what to do in this case.
  return NULL;
}

// The bundle can be 'article'.
$bundle = 'tags';
// The route, see that the $entity_type variable is used.
$route = "entity.entity_view_display.$entity_type.view_mode";
// The view mode can be 'teaser'.
$view_mode = 'full';
$a = Url::fromRoute($route, [$bundle_entity_type => $bundle, 'view_mode_name' => $view_mode])->toString();
// To use dpm() you need the Devel module.
dpm($a);
10
  • But what is the generic way to find $bundle_entity_type?
    – donquixote
    Sep 5, 2017 at 17:09
  • I think that this is another question like: How to find all the existing bundle entity types? Your question here is Is there a generic way to build such urls to field_ui pages for any entity type? I think that is better if you create another question, if you do it let my know. Sep 5, 2017 at 17:21
  • Sorry but without this part, the answer is incomplete. It only shows how to build such urls for taxonomy terms. But I agree that "How to find all the existing bundle entity types?" is a worthwhile question by itself.
    – donquixote
    Sep 5, 2017 at 17:35
  • @donquixote if you use the values that I write in the comments you will see that this code works for all the entities, just check again and try for nodes. Sep 5, 2017 at 17:39
  • It seems that $bundleEntityTypeId = $targetEntityType->getBundleEntityType(); provides what we need.
    – donquixote
    Sep 5, 2017 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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