How to work with field collections in $build in hook_entity_view_alter? I have a hook_entity_view_alter() function inside the .module file for a custom content entity type that I am working on. I want to be able to conditionally show or hide fields in the canonical view of the entity based on the value of that field.

Example for a checkbox field: show it in the canonical if it was checked in the form, hide it in the canonical completely if it was unchecked in the form.

I am using unset($build['field_id']) for fields that are not inside field collections, and this is working fine. However, I would also like to use unset() for some fields that are contained within field collections.

I feel like this is probably a pretty simple thing to do and I'm just completely missing it. I've been var_dumping $build for a while and can't figure out what to unset, or if this is even the way to do it.

edit: here is the code I am working on in {module}.module

function {module}_{entity}_view_alter(array &amp;$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {

  $notAllowed = stripos($entity-&gt;get('field_category')-&gt;getValue()[0]['value'], "Not Allowed");
  $allowedConditionally = $entity-&gt;get('field_maintenance_info')-&gt;first()-&gt;getFieldCollectionItem()-&gt;get('field_allowed_on_maintenance')-&gt;getValue();

  if ($notAllowed !== false) {
    if (!$allowedConditionally[0]['value']) {
        //the next 4 lines work with fields defined at the module settings level, not inside field collections - this works!
        unset($build['field_allowed_1']);
        unset($build['field_there_are_multiple_varieti']);
        unset($build['field_variations']);
        $build['title']['#prefix'] = "No ";
    }
  }

  $protein = stripos($entity-&gt;get('field_category')-&gt;getValue()[0]['value'], "Protein");

  //this is just a loop I had for exploring $build, this outputs string(2) "25" which I am pretty sure is the field collection ID
  //'field_allowed_1' and 'field_serving_settings' are both field collections, the latter nested inside the former
  if (!($protein &amp;&amp; !$notAllowed) &amp;&amp; !($notAllowed &amp;&amp; $protein2 &amp;&amp; $allowedOnMaintenance)) {
    var_dump($build['field_allowed_1'][0]['#field_collection_item']-&gt;field_serving_settings[0]-&gt;value);
  }
}
HOOK_entity_view_alter() works with render elements. That are all array keys, that have no '#' sign.

At the point you are now there are only fields prepared for rendering on the top level, that means the fields, which are not in a field collection. 

Fields that are inside a field collection have at this point no renderable output.

To get the render elements of these fields you have to use the hook for field_collection_item:

function mymodule_field_collection_item_view_alter(&amp;$build, $entity, $display) {
   kint($build);
}


Here you will be able to unset fields inside the field collection.