I have code that worked, but I wanted to clean it up and use dependency injection. I'm working in a BlockBase that implements ContainerFactoryPluginInterface.
class DefaultBlock extends BlockBase implements ContainerFactoryPluginInterface {
I need to access some information from the user object. Right now I'm using Drupal\Core\Session\AccountProxyInterface. This works fine, but doesn't give me all the information I was expecting. I have a contrib module adding a field to the user. I can access that field if I use User::load($id) however, I get the warning that...
User::load calls should be avoided in Drupal classes, use dependency injection instead
So I'm trying. And failing.
This code works...
$userIdx = \Drupal::currentUser()->id();
$userx = \Drupal\user\Entity\User::load($userIdx);
$countryx = $userx->country_iso_code_2;
But when I clean that up and do it the right way, I can't get that country_iso_code_2 information.
Here is the code I'm "trying" to work with...
<?php
namespace Drupal\country_selector\Plugin\Block;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a 'DefaultBlock' block.
*
* @Block(
* id = "default_block",
* admin_label = @Translation("Country switcher"),
* )
*/
class DefaultBlock extends BlockBase implements ContainerFactoryPluginInterface {
protected $account;
/**
* Class constructor.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $account) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->account = $account;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_user')
);
}
/**
* {@inheritdoc}
*/
public function build() {
$build = [];
$userIdx = \Drupal::currentUser()->id();
$userx = \Drupal\user\Entity\User::load($userIdx);
$countryx = $userx->country_iso_code_2;
$userId = $this->account->id();
$country = $this->account->country_iso_code_2;
.....
When I debug, I see that:
$userx is Drupal\user\Entity\User
$user is Drupal\core\Session\AccountProxy
So I get that I'm working with two different things. I just don't understand how I'm supposed to call something like User::load with dependency injection.
I hope that makes sense. Would love some advice!