3 namespace Drupal\user\Plugin\views\field;
5 use Drupal\Core\Extension\ModuleHandlerInterface;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\views\Plugin\views\field\FieldPluginBase;
8 use Drupal\views\ResultRow;
9 use Drupal\user\UserDataInterface;
10 use Symfony\Component\DependencyInjection\ContainerInterface;
13 * Provides access to the user data service.
15 * @ingroup views_field_handlers
17 * @see \Drupal\user\UserDataInterface
19 * @ViewsField("user_data")
21 class UserData extends FieldPluginBase {
24 * Provides the user data service object.
26 * @var \Drupal\user\UserDataInterface
33 * @var \Drupal\Core\Extension\ModuleHandlerInterface
35 protected $moduleHandler;
40 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
41 return new static($configuration, $plugin_id, $plugin_definition, $container->get('user.data'), $container->get('module_handler'));
45 * Constructs a UserData object.
47 public function __construct(array $configuration, $plugin_id, $plugin_definition, UserDataInterface $user_data, ModuleHandlerInterface $module_handler) {
48 parent::__construct($configuration, $plugin_id, $plugin_definition);
50 $this->userData = $user_data;
51 $this->moduleHandler = $module_handler;
57 protected function defineOptions() {
58 $options = parent::defineOptions();
60 $options['data_module'] = ['default' => ''];
61 $options['data_name'] = ['default' => ''];
69 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
70 parent::buildOptionsForm($form, $form_state);
72 $modules = $this->moduleHandler->getModuleList();
74 foreach (array_keys($modules) as $name) {
75 $names[$name] = $this->moduleHandler->getName($name);
78 $form['data_module'] = [
79 '#title' => $this->t('Module name'),
81 '#description' => $this->t('The module which sets this user data.'),
82 '#default_value' => $this->options['data_module'],
86 $form['data_name'] = [
87 '#title' => $this->t('Name'),
88 '#type' => 'textfield',
89 '#description' => $this->t('The name of the data key.'),
90 '#default_value' => $this->options['data_name'],
97 public function render(ResultRow $values) {
98 $uid = $this->getValue($values);
99 $data = $this->userData->get($this->options['data_module'], $uid, $this->options['data_name']);
101 // Don't sanitize if no value was found.
103 return $this->sanitizeValue($data);