Score:0

Optimal way to get a content type's field definition

in flag

When I need a content type's field definition in Drupal 8+, I used to run the following code (for getting 'body' field in content type 'page'):

$page_fields = \Drupal::getContainer()->get('entity_field.manager')
               ->getFieldDefinitions('node', 'page'); 
$body_definition = $page_fields['body'];

I learned, that it is also possible by running the following code:

$body_definition = \Drupal::entityTypeManager()
                  ->getStorage('field_config')
                  ->load('node.page.body');

Now my question is, what's an advantage of one over the other? The latter is of course only one line, but that can't be the end of the story, I guess. Is one of these ways the "Drupal way"?

Score:2
cn flag

Field definitions can be defined in different places. The first code examples gets all definitions, the second code example only a specific field definition and it finds only configured fields.

The service entity_field.manager is responsible for discovering fields in multiple locations, configuration and a lot of different methods in code, which might be extended in future to find even more. So using this service is the most generic way to get field definitions.

Use \Drupal only in hooks, not in classes. And then you can reference services via \Drupal::service('entity_field.manager'), you don't need to get the container.

Paul avatar
in flag
Thanks a lot, 4k4. Out of curiosity, where else could a field be defined if not in (db) configuration? Does this include configuration files, for example if there were a field defined in a (not yet imported) yml file?
4uk4 avatar
cn flag
No, the field manager doesn't read YAML files directly, only the active config in db. Normally base fields are defined in the entity class and bundle fields in config. But there are a lot of other methods to create or alter field definitions. For example bundle fields can be defined in the entity class, too. Also in hooks. But this is rarely used.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.