1

I've created a controller and I'm loading a node.

$variables['contest'] = Node::load(12);

return [
    '#theme' => 'theme_contest',
    '#variables' => $variables,
];

In this node there is a field "field_contest_things" of type list (text):

0|Dance
1|Read
2|Playing

In the twig file if I'm doing

{{ variables['contest'].field_contest_things.value }}

this will display the key and not the "value".

Is there any way that I can display the value and not the key in the twig ? Or should I change something in my controller ?

Thanks

1 Answer 1

5

If your field allows only 1 value, you can do it in both ways, i.e Controller or Twig :

Controller

$node->field_contest_things->getFieldDefinition()->getSetting('allowed_values')[$node>field_contest_things->value];

Twig

{{ node.field_contest_things.fieldDefinition.settings['allowed_values'][node.field_contest_things.value] }}

Update

You can now skip the usage of fieldDefinition on the latests Drupal 8 updates:

{{ node.field_contest_things.setting('allowed_values')[node.field_contest_things.value] }}

By experience, I suggest you to move for a taxonomy if you need to query your node by this field value on the future. It's more maintainable & scalable.


Hope it helps you !

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.