OpignoUserLearningPathStatusFilter.php in Opigno training catalog 3.x
File
src/Plugin/views/filter/OpignoUserLearningPathStatusFilter.php
View source
<?php
namespace Drupal\opigno_catalog\Plugin\views\filter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\views\Plugin\views\filter\StringFilter;
use Symfony\Component\DependencyInjection\ContainerInterface;
class OpignoUserLearningPathStatusFilter extends StringFilter {
protected $account;
public function __construct(AccountInterface $account, ...$default) {
parent::__construct(...$default);
$this->account = $account;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($container
->get('current_user'), $configuration, $plugin_id, $plugin_definition, $container
->get('database'));
}
public function defineOptions() {
$options = parent::defineOptions();
$options['current_user'] = FALSE;
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['current_user'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Consider the current user.'),
'#description' => $this
->t('Apply the filter only to trainings the current user belongs to.'),
'#weight' => -10,
'#default_value' => $this->options['current_user'] ?? FALSE,
];
}
public function submitOptionsForm(&$form, FormStateInterface $form_state) {
parent::submitOptionsForm($form, $form_state);
$this->options['current_user'] = $form_state
->getValue([
'options',
'current_user',
]);
}
public function query() {
parent::query();
$consider_user = $this->options['current_user'] ?? FALSE;
if (!$consider_user) {
return;
}
$uid = (int) $this->account
->id();
$this
->ensureMyTable();
$this->query
->addWhere(NULL, "{$this->tableAlias}.uid", $uid);
}
}