Drupal - How do I set access permissions per field?
You're stuck doing this in code, but the Examples module includes a field_permissions
example module.
This is an old thread, but as I stumbled upon same problem, not wanting to use a heavy module for few fields, I ran into this article (after this one, so I thought I could share) : https://atendesigngroup.com/blog/form-and-view-modes-vs-field-access-drupal-8
From other exemples around, this one takes care of cache context .
Just be careful to comments below article and some other little mistakes in code example. Correct and working code looks like this :
function YOUR_MODULE_NAME_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
$result = AccessResult::neutral();
if ($field_definition->getName() == 'field_we_care_about') {
if ($operation == 'edit' && !in_array('administrator', $account->getRoles())) {
$result = AccessResult::forbidden();
}
}
return $result->addCacheContexts(['user.roles:administrator']);
}
Field Permissions has a beta release for D8 now. It allows you to set permissions per field.