Same name and namespace in other branches
  1. 8.9.x core/modules/user/user.module \user_user_view_alter()
  2. 9 core/modules/user/user.module \user_user_view_alter()

Implements hook_ENTITY_TYPE_view_alter() for user entities.

This function adds a default alt tag to the user_picture field to maintain accessibility.

File

core/modules/user/user.module, line 318
Enables the user registration and login system.

Code

function user_user_view_alter(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
  if (!empty($build['user_picture']) && user_picture_enabled()) {
    foreach (Element::children($build['user_picture']) as $key) {
      if (!isset($build['user_picture'][$key]['#item']) || !$build['user_picture'][$key]['#item'] instanceof ImageItem) {

        // User picture field is provided by standard profile install. If the
        // display is configured to use a different formatter, the #item render
        // key may not exist, or may not be an image field.
        continue;
      }

      /** @var \Drupal\image\Plugin\Field\FieldType\ImageItem $item */
      $item = $build['user_picture'][$key]['#item'];
      if (!$item
        ->get('alt')
        ->getValue()) {
        $item
          ->get('alt')
          ->setValue(\Drupal::translation()
          ->translate('Profile picture for user @username', [
          '@username' => $account
            ->getAccountName(),
        ]));
      }
    }
  }
}