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 &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
$notAllowed = stripos($entity->get('field_category')->getValue()[0]['value'], "Not Allowed");
$allowedConditionally = $entity->get('field_maintenance_info')->first()->getFieldCollectionItem()->get('field_allowed_on_maintenance')->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->get('field_category')->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 && !$notAllowed) && !($notAllowed && $protein2 && $allowedOnMaintenance)) {
var_dump($build['field_allowed_1'][0]['#field_collection_item']->field_serving_settings[0]->value);
}
}
field_collection_item
. You can target this one to change the fields inside. If it still does not work, perhaps you can put some code in the question what you have done so far.$build['field_allowed_1'][0]
beside'#field_collection_item'
?