I have managed to hide certain fields for certain roles programmatically in Drupal 8 using function module_name_form_node_form_alter(array &$form, FormStateInterface &$form_state, $form_id).

The matter is that what I managed to hide such fields in the "Edit" tab, but I would also like to do the same in the "View" tab. What I intend to do is to hide certain fields depending on their machine name and the role of the user logged.

Do any of you know which hook should I use for that?

  • 1
    Welcome to Drupal Answers :) Have you come across Field permissions? It handles both of your requirements out of the box and now has a stable release
    – Clive
    Jun 8 '20 at 18:38
  • Thanks @Clive for your answer. Yes, I have came across Field Permissions, as it's what I was initially using. Unfortunately, we are not longer allowed to use it and that's why I'm writing my own module. Jun 8 '20 at 21:38

OK, this code seems to be the solution:

 * Implements hook_entity_field_access().
function MYMODULE_entity_field_access($operation, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, \Drupal\Core\Session\AccountInterface $account, \Drupal\Core\Field\FieldItemListInterface $items = NULL) {
  if ($field_definition->getName() == 'NAME_OF_THE_FIELD' && $operation == 'view') {
    return \Drupal\Core\Access\AccessResult::forbidden();
  else {
    return \Drupal\Core\Access\AccessResult::neutral();

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.