2

I am working on a custom Drupal 8 theme and I am trying to get the user avatar picture on a variable and output somewhere in the HTML.

I have created this function to get the name & email of the current user logged in like so:

#Function to get the user name value & output in the HTML DOM
function tropical_preprocess_page(&$variables){
  # gets current user name
  $user_logged_in_name = $variables['user']->getDisplayName();

  # creates value to ouput in the DOM & capitalize first letter
  $variables['user_logged_in_name'] = ucfirst($user_logged_in_name);

  # gets user email
  $user_email = $variables['user']->getEmail();
  $variables['user_email'] = $user_email;
}

That worked perfectly! Now I am trying to get the user profile picture, but I am not able to do it. Any help will be appreciate it.

4

you can get Url it by get('user_picture')->entity->url()( you can get URI too with get('user_picture')->entity->getFileUri()), So

function tropical_preprocess_page(&$variables){
  // gets current user name
  $user_logged_in_name = $variables['user']->getDisplayName();

  // creates value to ouput in the DOM & capitalize first letter
  $variables['user_logged_in_name'] = ucfirst($user_logged_in_name);

  // gets user email
  $user_email = $variables['user']->getEmail();
  $variables['user_email'] = $user_email;

  // get user picture
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())
  $variables['user_picture'] = $user->get('user_picture')->entity->url();

}

Additionally, If you want to get the default image when the user account doesn't have an image associated, use the following code.

$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$picture = file_create_url($file->getFileUri());
| improve this answer | |
  • 1
    @ManuelAbascal you're very welcome. :) – Yuseferi Mar 21 '19 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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