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 EntityAccessControlHandlerInterface::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

// 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

// Check access on a field generally:
$field =  \Drupal\field\Entity\FieldStorageConfig::loadByName($entity_type_id, $field_name);
$access = \Drupal::entityManager()->getAccessControlHandler($entity_type_id)->fieldAccess('edit', $field);
// Or in the context of a given entity:
$access = $entity->$field_name->access('edit');

Implementing field access logic

Drupal 7:

/**
 * 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:

/**
 * 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->getName() == 'field_of_interest' && $operation == 'edit') {
    return $account->hasPermission('update field of interest');
  }
}
Impacts: 
Module developers