Change record status: 
Project: 
Introduced in branch: 
8.x
Description: 

In Drupal 7, field access grants (typically view and edit) were checked using the field_access() function, and modules could implement custom access logic using hook_field_access().

In Drupal 8,

  • field access are checked using EntityAccessControllerInterface::fieldAccess() or FieldItemListInterface::access() when in the context of a specific entity (see code examples below)
  • hook_field_access() is replaced by hook_entity_field_access()

Code examples:

Checking field access

Drupal 7

<?php
// Check access on a field generally:
$field = field_info_field($field_name);
$access = field_access('edit', $field, $entity_type);
// Or in the context of a given entity:
$access = field_access('edit', $field, $entity_type, $entity);
?>

Drupal 8

<?php
// Check access on a field generally:
$field Field::fieldInfo()->getField($field_name);
$access = \Drupal::entityManager()->getAccessController($entity_type)->fieldAccess('edit', $field);
// Or in the context of a given entity:
$access = $entity->$field_name->access('edit');
?>

Implementing field access logic

Drupal 7:

<?php
/**
* Implements hook_field_access().
*/
function hook_field_access($op, $field, $entity_type, $entity = NULL, $account = NULL) {
  if (
$field['field_name'] == 'field_of_interest' && $op == 'edit') {
    return
$account->hasPermission('edit field of interest');
  }
  return
TRUE;
}
?>

Drupal 8:

<?php
/**
* Implements hook_entity_field_access().
*/
function hook_entity_field_access($operation, \Drupal\Core\Entity\Field\FieldDefinitionInterface $field_definition, \Drupal\Core\Session\AccountInterface $account, \Drupal\Core\Entity\Field\FieldItemListInterface $items = NULL) {
  if (
$field_definition->getFieldName() == 'field_of_interest' && $operation == 'edit') {
    return
$account->hasPermission('update field of interest');
  }
}
?>
Impacts: 
Module developers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done