I created a custom entity called 'Representative' using the drupal console 'generate:entity:content' command.

The entity works correctly I added a bundle of fields to it, added some content, and can query this entity using the EntityTypeManager query.

My problem is - I can't render this entity in twig. When I pass this entity to the render array:

    $build = [
  '#theme' => 'representatives',
  '#representative_entity' => $representative

I get the following error:

Exception: Object of type

Drupal\kelk_representatives\Entity\RepresentativeEntity cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 476 of core/lib/Drupal/Core/Template/TwigExtension.php).

(I was using drupal console to automatically generate the twig files and preprocess functions)..

Can anyone help?

1 Answer 1


You must render the correct view mode of the entity, like this:

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('ENTITY_TYPE');
$entity_view = $view_builder->view($representative);

$build = [
  '#theme' => 'representatives',
  '#representative_entity' => $entity_view,
  • Still get an error - 'Cannot use object of type Drupal\kelk_representatives\Entity\RepresentativeEntity as array'
    – Yaron
    Jan 1, 2020 at 11:53
  • I have updated my answer!
    – user72672
    Jan 1, 2020 at 11:58
  • Great ! Didn't realise I needed to use ViewBuilder for it.
    – Yaron
    Jan 1, 2020 at 12:05
  • 1
    ViewBuilder yes, but no renderer. Twig renders build arrays in variables automatically and when you render too early you lose cache metadata and attachments.
    – 4uk4
    Jan 1, 2020 at 12:31
  • 1
    @4k4 Oh yes of course. I updated my answer, thanks.
    – user72672
    Jan 1, 2020 at 12:36

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.