0

I have set up my site so that some users with a specific role can't edit their email address. This works fine - users with role type A can navigate to the edit tab on their profile and edit their email address, and users with role type B are unable to edit their email address. However, these users can still view their email address field on the edit tab, it just appears disabled. I do not want this to be the case.

I used the User Protect and Field Permissions modules to achieve this. For all of the other fields that I prevented users with role type B from editing (e.g. their name), the fields did not appear at all on the edit tab. I have used the same settings in field permissions for these fields and the email field but for some reason the email field appears under the edit tab but the others don't. How can I prevent the email field from displaying when users don't have permission to edit it?

1 Answer 1

4

You can to this using hook_form_FORM_ID_alter(), like this:

function MY_MODULE_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (in_array('role_B', \Drupal::currentUser()->getRoles())) {
    // We restrict access if the field is disabled.
    $form['account']['mail']['#access'] = FALSE;
  }
}
7
  • What is the easiest way to find out the form_id and the field name? I tried looking at the page source but inputting the names shown there didn't seem to work. Also there doesn't seem to be an edit user form file within the Form folder of the User module Dec 20, 2019 at 11:05
  • 1
    @Oceanescence I have updated my answer with the correct names.
    – user72672
    Dec 20, 2019 at 11:13
  • Unfortunately this isn't working for me Dec 20, 2019 at 11:53
  • !empty($form['account']['mail']['#attributes']['disabled']) is evaluating to FALSE i.e. it is not set to disabled.... But on the form the user is unable to type in the box so it is functionally disabled. Maybe this is to do with how the Field Permissions module works Dec 20, 2019 at 11:59
  • 1
    @Oceanescence Ok, the disabled attribute is probably not being set then. You can look on the role instead. Take a look at the updated answer, thanks.
    – user72672
    Dec 20, 2019 at 12:11

Your Answer

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

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