如何在 Drupal 8 中加载用户配置文件类型?

How to load User Profile Type in Drupal 8?

我想通过用户 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);

但是,它会return以下错误。

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)

您是否尝试使用 user_load 函数而不是 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

当你转储时 $current_user 你有一些数据吗?

来晚了,但其他人会来这里(就像我一样)。

我不得不进入配置文件模块源代码才能找到它,但我想当你想到它时它是显而易见的:

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

您可能希望将其包装在服务中 - 如果您不这样做,您应该仔细审视一下自己,看看为什么不这样做:-)