Score:1

How to access the node/term field-values in a cleaner way?

ph flag

My code is filled with methods like these to access field values:

\Drupal::entityTypeManager()->getStorage('node')->get('field_name')->getValue()[0]['value'];
\Drupal\taxonomy\Entity\Term::load($tid)->get('field_name')->getValue()[0]['value'];
\Drupal::routeMatch()->getParameter('node')->get('field_name')->getValue()[0]['value'];
\Drupal::routeMatch()->getParameter('node')->get('field_entity')->getValue()[0]['target_id'];
\Drupal::routeMatch()->getParameter('node')->get('field_link')->getValue()[0]['title'];

And in twig templates:

content.field_name[0]['#context']['value']
item.entity.field_tech_spec_name.0.value
item.entity.field_image_link.0.url

Surely there has to be a more correct and aesthetic way to get these, which I am missing. Sorry for such a basic question.

Score:2
ru flag

You can use magic getter methods like $entity->field_name->database_column to get the first value of a field:

$node->field_name->value;
$node->field_entity->target_id;
$node->field_link->title;

etc

This will get the first value of that field (and will not work with multi cardinality fields). If that is "cleaner"... there are people who claim magic getters are plain evil. A more practical downside is that your IDE's Intellisense/autocompletion will not work with magic getters.

I sit in a Tesla and translated this thread with Ai:

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.