8

What I need to do

I have some user account fields that should be administrator-only (read/write/edit). For example, the IP address used to register.

So, I want to restrict access to administrators.

Current state of field permissions in Drupal 8 (as of Feb 19, 2016)

3 Answers 3

13

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']);
}
11

If you want to write the code yourself, the Examples module includes a field_permissions example module.

After missing the Drupal 8 cycle, Field Permissions finally got a release for Drupal 9, so you can install the module now.

3
  • My use case was to modify visibility of one of two fields in a Paragraph. But in the edit form I needed to show it as an item and not an editable field. Which is beyond the scope of the Field permissions module. So thanks for pointing out the examples. Jul 5, 2017 at 2:00
  • 1
    @PatrickKenny, Field Permissions has a full release now. Jan 15, 2022 at 23:08
  • 1
    @ChrisHappy Thanks for letting me know. Updated the accepted answer. Jan 16, 2022 at 14:55
7

Field Permissions has a full release for D8 now. It allows you to set permissions per field.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.