1

I see node preprocess does this

$variables['node'] = $variables['elements']['#node'];

and then in the template one can do this

{{ node.id }}

but when I create a custom entity and do the same, I never get past all the the errors like

Exception: Object of type Drupal\Core\Field\FieldItemList cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 476 of core/lib/Drupal/Core/Template/TwigExtension.php).

What are they doing special for node?

1

Why does {{ custom_entity.id }} produce this error message?

Exception: Object of type Drupal\Core\Field\FieldItemList cannot be printed.

If your entity defines id for the entity ID then {{ custom_entity.id }} is ambiguous. It can mean the object property (the ID field) or the method EntityInterface::id().

So use parentheses to make it clear it is a method:

{{ custom_entity.id() }}

Or retrieve the field value when you have already a field as the error message shows:

{{ custom_entity.id.value }}

What are they doing special for node?

The node entity is using nid as ID field, so id and nid are unambigious.

Method id():

{{ node.id }}

Field nid:

{{ node.nid.value }}
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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