1

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.

1 Answer 1

3

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.

1
  • is there any shorthand way to access them in twig templates? Commented Dec 2, 2023 at 0:59

Your Answer

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

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