View source
<?php
namespace Drupal\language_hierarchy\Plugin\views\filter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\views\Plugin\views\filter\FilterPluginBase;
use Drupal\views\Plugin\views\query\Sql;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContentLanguageFallbackLimitedFilter extends FilterPluginBase {
protected $languageManager;
public function __construct($configuration, $plugin_id, $plugin_definition, LanguageManagerInterface $language_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->languageManager = $language_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('language_manager'));
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['value']['default'] = '1';
return $options;
}
public function query() {
if ($this->value) {
$this
->ensureMyTable();
$langcode = $this->languageManager
->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
->getId();
$this->value = array_values($this->languageManager
->getFallbackCandidates([
'langcode' => $langcode,
'operation' => 'query',
]));
if (!in_array($langcode, $this->value, TRUE)) {
$this->value = array_merge([
$langcode,
], $this->value);
}
$query = $this->query;
$qualified_field = "{$this->tableAlias}.{$this->realField}";
if (count($this->value) === 1) {
$query
->addWhere($this->options['group'], $qualified_field, $this->value[0], '=');
}
else {
$query
->addWhere($this->options['group'], $qualified_field, $this->value, 'IN');
$query
->addTag('language_hierarchy_limit');
$data = $this->viewsData
->getAll();
$this->view->build_info['language_hierarchy_limit'][$qualified_field] = [
'base_table' => $this->table,
'base_field' => $data[$this->table]['table']['base']['field'],
'lang_codes' => $this->value,
];
}
}
}
protected function valueForm(&$form, FormStateInterface $form_state) {
$exposed = $form_state
->get('exposed');
$form['value'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Show only the most specific translation for the content language selected for a page.'),
'#default_value' => $this->value,
];
$query_plugin = $this->displayHandler
->getPlugin('query');
if (!$query_plugin instanceof Sql) {
$form['value']['#disabled'] = TRUE;
$form['value']['#default_value'] = '';
$form['value']['#description'] = $this
->t('This option only supports the <em>Sql</em> query backend.');
}
if (!empty($this->options['exposed'])) {
$identifier = $this->options['expose']['identifier'];
$user_input = $form_state
->getUserInput();
if ($exposed && !isset($user_input[$identifier])) {
$user_input[$identifier] = $this->value;
$form_state
->setUserInput($user_input);
}
}
}
}