View source
<?php
namespace Drupal\better_exposed_filters\Plugin;
use Drupal\Component\Plugin\PluginBase;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Drupal\views\Plugin\views\ViewsHandlerInterface;
use Drupal\views\ViewExecutable;
abstract class BetterExposedFiltersWidgetBase extends PluginBase implements BetterExposedFiltersWidgetInterface {
use StringTranslationTrait;
protected $view;
protected $handler;
public function __construct(array $configuration, $plugin_id, $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->configuration = NestedArray::mergeDeep($this
->defaultConfiguration(), $configuration);
}
public function defaultConfiguration() {
return [
'plugin_id' => $this->pluginId,
];
}
public function getConfiguration() {
return $this->configuration;
}
public function setConfiguration(array $configuration) {
$this->configuration = $configuration;
}
public function setView(ViewExecutable $view) {
$this->view = $view;
}
public function setViewsHandler(ViewsHandlerInterface $handler) {
$this->handler = $handler;
}
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$values = $form_state
->getValues();
foreach ($values as $key => $value) {
if (array_key_exists($key, $this->configuration)) {
$this->configuration[$key] = $value;
}
else {
unset($values[$key]);
}
}
}
protected function addContext(array &$element) {
$element['#context'] = [
'#plugin_type' => 'bef',
'#plugin_id' => $this->pluginId,
'#view_id' => $this->view
->id(),
'#display_id' => $this->view->current_display,
];
}
protected function addElementToGroup(array &$form, FormStateInterface $form_state, $element, $group) {
$form[$group]['#access'] = TRUE;
$form[$element]['#group'] = $group;
if (empty($form[$group]['#open'])) {
$user_input = $form_state
->getUserInput()[$element] ?? [
0,
];
if (!is_array($user_input)) {
$user_input = [
$user_input,
];
}
$options = $form[$element]['#options'] ?? [];
$default_value = $form[$element]['#default_value'] ?? key($options);
$has_values = array_reduce($user_input, function ($carry, $value) use ($form, $element, $default_value) {
return $carry || ($value === $default_value ? '' : $value || $default_value === 0);
}, FALSE);
if ($has_values) {
$form[$group]['#open'] = TRUE;
}
}
}
protected function getExposedFormActionUrl(FormStateInterface $form_state) {
$view = $form_state
->get('view');
$display = $form_state
->get('display');
if (isset($display['display_options']['path'])) {
return Url::fromRoute(implode('.', [
'view',
$view
->id(),
$display['id'],
]));
}
$request = \Drupal::request();
$url = Url::createFromRequest(clone $request);
$url
->setAbsolute();
return $url;
}
}