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;
41 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
42 return new static($configuration, $plugin_id, $plugin_definition, $container->get('user.data'), $container->get('module_handler'));
46 * Constructs a UserData object.
48 public function __construct(array $configuration, $plugin_id, $plugin_definition, UserDataInterface $user_data, ModuleHandlerInterface $module_handler) {
49 parent::__construct($configuration, $plugin_id, $plugin_definition);
51 $this->userData = $user_data;
52 $this->moduleHandler = $module_handler;
58 protected function defineOptions() {
59 $options = parent::defineOptions();
61 $options['data_module'] = ['default' => ''];
62 $options['data_name'] = ['default' => ''];
70 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
71 parent::buildOptionsForm($form, $form_state);
73 $modules = $this->moduleHandler->getModuleList();
75 foreach (array_keys($modules) as $name) {
76 $names[$name] = $this->moduleHandler->getName($name);
79 $form['data_module'] = [
80 '#title' => $this->t('Module name'),
82 '#description' => $this->t('The module which sets this user data.'),
83 '#default_value' => $this->options['data_module'],
87 $form['data_name'] = [
88 '#title' => $this->t('Name'),
89 '#type' => 'textfield',
90 '#description' => $this->t('The name of the data key.'),
91 '#default_value' => $this->options['data_name'],
98 public function render(ResultRow $values) {
99 $uid = $this->getValue($values);
100 $data = $this->userData->get($this->options['data_module'], $uid, $this->options['data_name']);
102 // Don't sanitize if no value was found.
104 return $this->sanitizeValue($data);