View source
<?php
namespace Drupal\flag_search_api\Plugin\facets\widget;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\facets\Result\Result;
use Drupal\facets\FacetInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\facets\Widget\WidgetPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class UserFlagWidget extends WidgetPluginBase implements ContainerFactoryPluginInterface {
protected $currentUser;
public function __construct(array $configuration, $plugin_id, $plugin_definition, $current_user) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentUser = $current_user;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('current_user'));
}
public function defaultConfiguration() {
return [
'flags_label' => "My Flagged Items",
'no_flags_label' => "No Flagged Items Available",
] + parent::defaultConfiguration();
}
public function build(FacetInterface $facet) {
$uid = $this->currentUser
->id();
$userFlagResult = FALSE;
$results = $facet
->getResults();
foreach ($results as $result) {
if ($result
->getRawValue() == $uid) {
$userFlagResult = $result;
$userFlagResult
->setDisplayValue($this
->getConfiguration()['flags_label']);
}
}
if ($userFlagResult) {
$facet
->setResults([
$userFlagResult,
]);
}
else {
$emptyResult = new Result($facet, $uid, $this
->getConfiguration()['no_flags_label'], 0);
$facet
->setResults([
$emptyResult,
]);
}
$build = parent::build($facet);
$build['#attributes']['class'][] = 'js-facets-checkbox-links';
$build['#attached']['library'][] = 'facets/drupal.facets.checkbox-widget';
return $build;
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state, FacetInterface $facet) {
$form = parent::buildConfigurationForm($form, $form_state, $facet);
$form['flags_label'] = [
'#type' => 'textfield',
'#title' => $this
->t('Flags label'),
'#description' => $this
->t('This text will be used for the flags checkbox label.'),
'#default_value' => $this
->getConfiguration()['flags_label'],
];
$form['no_flags_label'] = [
'#type' => 'textfield',
'#title' => $this
->t('No Flags label'),
'#description' => $this
->t("This text will be used when there aren't any matching flags."),
'#default_value' => $this
->getConfiguration()['no_flags_label'],
];
return $form;
}
}