<?php
// module custom /src/Plugin/views/filter/CustomFilter.php
// ejemplo en smsjd_druplal
<?php
namespace Drupal\sm_utils\Plugin\views\filter;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\InOperator;
use Drupal\views\ViewExecutable;
/**
* Filters by current tags.
*
* @ingroup views_filter_handlers
*
* @ViewsFilter("som360_node_revelance_filter")
*/
class CurrentNodeRevelanceFilter extends InOperator {
/**
* {@inheritdoc}
*/
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
parent::init($view, $display, $options);
$this->valueTitle = $this->t('Current Tags');
$this->definition['options callback'] = [$this, 'generateOptions'];
}
/**
* {@inheritdoc}
*/
public function operators() {
return [
'=' => [
'title' => $this->t('Is equal to'),
'short' => $this->t('='),
'method' => 'opFilterNodeRevelance',
'values' => 1,
],
'!=' => [
'title' => $this->t('Is not equal to'),
'short' => $this->t('!='),
'method' => 'opFilterNodeRevelance',
'values' => 1,
],
];
}
/**
* {@inheritdoc}
*/
public function query() {
// Override the query
// So that no filtering takes place if the user doesn't select any options.
if (!empty($this->value)) {
parent::query();
}
}
/**
* {@inheritdoc}
*/
public function validate() {
// Skip validation
// If no options have been chosen so we can use it as a non-filter.
if (!empty($this->value)) {
parent::validate();
}
}
/**
* Helper function that generates the options.
*
* @return string[]
*/
public function generateOptions() {
return [
'current_tag' => t('Current tags'),
];
}
/**
* Add SQL condition to filter by.
*/
protected function opFilterNodeRevelance() {
if (empty($this->value)) {
return;
}
$this->ensureMyTable();
$mid = 1854;
// $field = 'node__field_ref_minisites.field_ref_minisites_target_id';
$field = 'node_field_data.nid';
$this->query->addWhereExpression($this->options['group'], "$field $this->operator $mid");
}
}
//en sm_utils.module
/**
* Implements hook_views_data_alter()
*
* Register a new filter to be used in views in this project.
* Logic is defined in src/views/filter/CurrentNodeRevelanceFilter.php
*/
function sm_utils_views_data_alter(&$data) {
$data['node_field_data']['node_revelance_filter'] = [
'label' => t('Custom tags filter'),
'title' => t('Current tags'),
'group' => t('Custom Filters'),
'filter' => [
'title' => t('Current tags'),
'help' => t('Filters nodes that belong to current tags'),
'field' => 'smsjdnode_field_data',
'id' => 'som360_node_revelance_filter',
],
];
}
// en config/schema.yml
views.filter.som360_node_revelance_filter:
type: views.filter.in_operator
label: 'Current tags'