How to traverse up and down nested entities in Drupal 8

Sometimes it's necessary to get values from children or parents of an entity. In Drupal 8, like in previous versions, there are hard ways and easy ways to get at this information.

Here's an example of a node preprocess function which traverses down to a paragraph, then to a nested paragraph, then to a term on the nested paragraph, then finally gets the value from a field on the term.

 

Here's an example, using hook_view_mode_alter(), which traverses up to get the parent that a media entity is attached to:

 

If you have installed the Devel module and configured it to use Kint, then seeing all the methods on an entity can be done by combining dpm() and get_class_methods(), as follows:

 

Article Type

General