4

I would like to load user profile module data by user id:

Code:

$profile_type = 'my_profile';
$user_id = 1;
$current_user = User::load($user_id);
$active_profile = $this->entityTypeManager()->getStorage('profile')->loadByUser($current_user, $profile_type);

print_r($active_profile);

But, It will return following error.

Error:

The website encountered an unexpected error. Please try again later.
Recoverable fatal error: Argument 1 passed to Drupal\profile\ProfileStorage::loadByUser() must implement interface Drupal\Core\Session\AccountInterface, null given, called in C:\xampp\htdocs\catchow\htdocs\modules\custom\catchow_registration_contactlab\src\Controller\CatchowRegistrationContactlabController.php on line 122 and defined in Drupal\profile\ProfileStorage->loadByUser() (line 16 of modules\contrib\profile\src\ProfileStorage.php).
Drupal\profile\ProfileStorage->loadByUser(NULL, 'authenticated_user') (Line: 122)
Ashwin Parmar
  • 3,025
  • 3
  • 26
  • 42

2 Answers2

6

This is late, but other people will come here (just like I did).

I had to go into the profile module source code to find this, but I guess it's obvious when you think about it:

$list = \Drupal::entityTypeManager()
  ->getStorage('profile')
  ->loadByProperties([
    'uid' => $account->id(),
    'type' => 'profile_type',
  ]);

You'll probably want to wrap it up in a service - and if you don't, you should take a long hard look at yourself as to why not :-)

Adaddinsane
  • 535
  • 6
  • 11
-1

Did you try to use user_load function instead of User::Load :

$current_user = user_load($user_id);

https://api.drupal.org/api/drupal/core%21modules%21user%21user.module/function/user_load/8.2.x

And when you are dumping $current_user do you have some data ?

Fky
  • 2,133
  • 1
  • 15
  • 23
  • Yes, I got `$current_user` object properly. – Ashwin Parmar Mar 30 '17 at 15:20
  • This is of no use whatsoever since the profile fields are not attached to the user object. – Adaddinsane Sep 20 '18 at 13:29
  • First; the user was asking how to load a user... not the currant user per se. Second; "user_load" is depreciated (see https://api.drupal.org/api/drupal/core%21modules%21user%21user.module/function/user_load/8.2.x) – sea26.2 Jan 30 '19 at 04:04
  • @sea26.2 First : I get his code to answer . Second : "Will be removed on D9" not on D8 , so deprecated but still usable in version 8. – Fky Feb 06 '19 at 15:59