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

Ash*_*mar 4 drupal drupal-8

我想通过用户 ID 加载用户配置文件模块数据:

代码:

$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);
Run Code Online (Sandbox Code Playgroud)

但是,它将返回以下错误。

错误:

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)
Run Code Online (Sandbox Code Playgroud)

Ada*_*ane 6

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

我必须进入配置文件模块源代码才能找到它,但我想当您考虑它时很明显:

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

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