function UserHooks::userViewAlter

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/src/Hook/UserHooks.php, line 186

Class

UserHooks
Hook implementations for user.

Namespace

Drupal\user\Hook

Code

public function userViewAlter(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(),
                ]));
            }
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.