I have generated an array in Drupal 8 which is created by using viewbuilder in this manner:

 $content = $this->entityManager()->getViewBuilder($entity->getEntityTypeId())>view($entity, 'hardcopy');

And now I want to hide comment section present in this array.

Any idea on how to do this?

  • 1
    It's an array - find the element you don't want, and simply remove it as you would with any array. Or is there a reason you can't use the normal language features for this?
    – Clive
    Commented Apr 25, 2015 at 11:29
  • I tried using unset($content['#content']['#node']['comment']); but still comment part remains in the array. I don't what is happening wrong? Commented Apr 25, 2015 at 11:45
  • I am not sure if I am unsetting the appropriate key, so please help me with this!!! Commented Apr 25, 2015 at 11:51
  • There is a error coming which says: Cannot use object of type Drupal\node\Entity\Node as array ... . this is coming when I am trying to unset the comment key. Commented Apr 25, 2015 at 12:07

1 Answer 1


The result that you get there is only prepared, the actual rendered content is not set there, you can't remove it there.

The comments are a field, you can hide/show them in the manage view display UI like any other files.

Define a view mode/display for your use case if the default ones don't work for you and then configure it there.

Doing it in code is only possibly in indirect ways. You'd need to set a flag in $content and then implement hook_node_view() alter and remove it there.

  • Can you please explain me with help of some code or reference, I am still a novice to this stuff!! Thanks. Commented Apr 25, 2015 at 12:23
  • 1
    That's the point, you don't need code. Looking at your code sample again, you apparently already have a view mode "hardcopy". So you just need to go to admin/structure/types/manage/$nodetype/display, and enable your view mode there at the bottom. Then go to the local task that should show up and hide the comment field. Done.
    – Berdir
    Commented Apr 25, 2015 at 12:25
  • you are simply awesome I know this was very basic question and should have figured it out. But I am very new to this stuff. Thanks again. I can't even upvote since I am noob over here!! Commented Apr 25, 2015 at 13:02

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