Last active
May 28, 2021 21:16
-
-
Save fredysan/b678d3c1c3d54d99119647a5db4b122f to your computer and use it in GitHub Desktop.
Views Custom Filter - Filters out users based on a Subquery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
*/ | |
namespace Drupal\my_module\Plugin\views\filter; | |
use Drupal\views\Plugin\views\display\DisplayPluginBase; | |
use Drupal\views\Plugin\views\filter\InOperator; | |
use Drupal\views\ViewExecutable; | |
/** | |
* Filters out users that don't have at least one linked content as owners. | |
* | |
* @ingroup views_filter_handlers | |
* | |
* @ViewsFilter("views_user_ownership") | |
*/ | |
class IsOwnerFilter extends InOperator { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) { | |
parent::init($view, $display, $options); | |
$this->definition['options callback'] = [$this, 'generateOptions']; | |
} | |
/** | |
* Override the query so that no filtering takes place if the user doesn't | |
* select any options. | |
*/ | |
public function query() { | |
$subquery = \Drupal::database()->select('node_field_data', 'nfd'); | |
$subquery->addExpression('count(*)', 'count'); | |
$subquery->where('nfd.owner = {users_field_data}.uid'); | |
// Filter out users that don't have at least one linked content as owners. | |
$this->query->addWhere('subquery', $subquery, 0, '>'); | |
} | |
/** | |
* Skip validation if no options have been chosen so we can use it as a | |
* non-filter. | |
*/ | |
public function validate() { | |
if (!empty($this->value)) { | |
parent::validate(); | |
} | |
} | |
/** | |
* Helper function that generates the options. | |
* @return array | |
*/ | |
public function generateOptions() { | |
// Array keys are used to compare with the table field values. | |
return [ | |
'is_owner' => 'Is Owner', | |
]; | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implements hook_views_data_alter(). | |
*/ | |
function my_module_views_data_alter(array &$data) { | |
$data['users_field_data']['ownership'] = [ | |
'title' => t('Ownership'), | |
'filter' => [ | |
'title' => t('Ownership'), | |
'help' => t('Checks if the users has been linked as an owner of at least one content.'), | |
'field' => 'uid', | |
'id' => 'views_user_ownership' | |
], | |
]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment