How to specify/modify form view mode for Drupal 8 Forms

I haven’t seen a whole lot of documentation on how to use a custom form display mode in D8, here’s a little example code snippet making it pretty easy.

In the below case, we created a custom display with the machine name “restricted” and want to use it for the user profile edit page for non admin users only. Obviously easy enough to change for different entity types, bundles and user roles/permissions.

Works a charm.

function my_module_entity_form_display_alter(&$form_display, $context) {
  if($context['entity_type'] == 'user' && $context['bundle'] == 'user'){
    $user = Drupal::currentUser();
    if(!in_array('administrator', $user->getRoles())){
      $storage = Drupal::service('entity_type.manager')->getStorage('entity_form_display');
      $form_display = $storage->load('user.user.restricted');
    }
  }
}
Drupal version: 


Source: https://www.drupal.org/taxonomy/term/4/feed