On a domain site (domain access module), I want to filter medias/nodes by the related domains to the current user. For this I have created a custom views filter : I analyse the user domains and modify the query to display only the needed nodes/medias. Here is the code of my custom views filter:

 * {@inheritdoc}
public function query() {
  // Load the current user.
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $domains = array();
  // Retrieve the domains of the current user.
  $user_domains = $user->get('field_domain_access')->getValue();
  foreach ($user_domains as $domain) {
    $domains[] = $domain['target_id'];
  if (!empty($this->value) and $user->get('field_domain_all_affiliates')->value == 0) {
    // Add an additional condition to filter contents/medias by the user domains.
    $this->query->addWhere($this->options['group'], 'node__field_domain_access.field_domain_access_target_id', $domains, 'IN');  

But, I get duplicates results in my views. If I use this filter, I need to desactivate the SQL rewriting option, so I can't use the distinct option to remove duplicates.

Is there a solution to add a groupBy to remove duplicates? I tried to use this code without sucess:

$this->query->distinct(); // don't work

Do I add a new field in my query (node field) ?

Thanks for your help.

  • 1
    you can use Sql::addOrderBy – berramou Dec 27 '18 at 15:55
  • Try with $this->ensureMyTable()->query->addOrderBy('node', 'nid', $order = 'ASC', $alias = '', []); – berramou Dec 27 '18 at 16:01
  • Thanks Berramou ! If I add this code, duplicates aren't visible : $this->query->addOrderBy('node', 'nid', $order = 'ASC', $alias = '', []); $this->query->options['distinct'] = TRUE; But, on my views table, I can't sort the results with any sort filters. Do I add another sort filters in my custom filter? – user28220 Dec 28 '18 at 10:37

You can use hook_query_alter(), see this web page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.