facets_range_nouislider-1.0.0/src/Plugin/facets/widget/RangeNoUiSliderWidget.php
src/Plugin/facets/widget/RangeNoUiSliderWidget.php
<?php
namespace Drupal\facets_range_nouislider\Plugin\facets\widget;
use Drupal\Core\Form\FormStateInterface;
use Drupal\facets\FacetInterface;
/**
* The range NoUiSlider widget.
*
* @FacetsWidget(
* id = "range_nouislider",
* label = @Translation("Range NoUiSlider"),
* description = @Translation("A widget that shows a range NoUiSlider."),
* )
*/
class RangeNoUiSliderWidget extends NoUiSliderWidget {
/**
* @param FacetInterface $facet
*
* @return array
*/
public function build(FacetInterface $facet): array {
$build = parent::build($facet);
if (empty($facet->getResults())) {
return $build;
}
$active = $facet->getActiveItems();
$facet_settings = &$build['#attached']['drupalSettings']['facets']['sliders'][$facet->id()];
$facet_settings['range'] = TRUE;
$facet_settings['url'] = reset($facet_settings['urls']);
unset($facet_settings['value']);
unset($facet_settings['urls']);
$min = $facet_settings['min'];
$max = $facet_settings['max'];
$facet_settings['values'] = [
isset($active[0][0]) ? (float) $active[0][0] : $min,
isset($active[0][1]) ? (float) $active[0][1] : $max,
];
$facet_settings = array_merge($facet_settings, $this->getConfiguration());
// Add inputs template.
if ($facet_settings['add_inputs']) {
$input_to = [
'#type' => 'textfield',
'#title' => $this->getConfiguration()['to'],
'#attributes' => [
'id' => [
'nouislider-input-to',
],
'class' => [
'nouislider-input',
],
],
];
$search = 'facets_range_nouislider_form';
$found = NULL;
// Get parent template.
array_walk($build['#items'], function ($item, $key) use ($search, &$found) {
if (in_array($search, $item)) {
$found = $key;
}
});
$input_from = $build['#items'][$found]['#inputs'];
$build['#items'][$found]['#inputs'] = [$input_from, $input_to];
}
return $build;
}
/**
* @param array $form
* @param FormStateInterface $form_state
* @param FacetInterface $facet
*
* @return array
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state, FacetInterface $facet): array {
$config = $this->getConfiguration();
$form = parent::buildConfigurationForm($form, $form_state, $facet);
$form['to'] = [
'#type' => 'textfield',
'#size' => 5,
'#title' => $this->t('Label to'),
'#default_value' => $config['to'],
];
return $form;
}
/**
* @param string $name
* @param string $type
*
* @return bool
*/
public function isPropertyRequired($name, $type): bool {
if ($name === 'range_slider' && $type === 'processors') {
return TRUE;
}
if ($name === 'show_only_one_result' && $type === 'settings') {
return TRUE;
}
return FALSE;
}
/**
* @return string
*/
public function getQueryType(): string {
return 'range';
}
}
