#StackBounty: #views #8 Custom views filter for custom view field

Bounty: 50

I want to created a custom views field, following this tutorial:
https://www.webomelette.com/creating-custom-views-field-drupal-8. This custom field counts and returns the number of referencing entities. So if the current view row item is referenced by 10 other entities the field show a 10.

Now I want to create a custom exposed filter filtering on the output of this field. The output of the field is a number between 0 and 100. So I want to be able to say. Show all items that are referenced more than 5 times.

So it would be nice if it is possible to get the int filter options (Equal to, Not equal to, Larger etc.).

This tutorial also shows a link on creating your own filter. Content from this link is used in the duplicate answer that is mentioned. In this custom filter they work with existing fields. Where I want the filter to work with the same calculation (database query) I use in the custom field.

What I got so far is in my “.views.inc“`:

/* @    -- Total score number/percentage */
$data['tests']['score_percentage'] = array(
  'title' => t('Percentage Filter'),
  'filter' => array(
      'title' => t('Percentage Filter'),
      'help' => t('Provides a custom filter for tests to filter by total score percentage'),
      'id' => 'score_percentage'
  ),
);

The tests type is a custom entity type I created with ECK Entity Types.

Then in my src/Plugin/views/filter folder I have a ScorePercentage.php file when I have this starter setup…but what now?

<?php

namespace Drupalscore_percentagePluginviewsfilter;

use DrupalviewsPluginviewsdisplayDisplayPluginBase;
use DrupalviewsPluginviewsfilterInOperator;
use DrupalviewsViewExecutable;

/**
 * Filters by given list of node title options.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("score_percentage")
 */
class ScorePercentage extends InOperator {

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->valueTitle = t('Percentage Filter');
  }

  /**
   * Override the query so that no filtering takes place if the user doesn't
   * select any options.
   */
  public function query() {
    if (!empty($this->value)) {
      parent::query();
    }
  }

  /**
   * 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();
    }
  }
}

Can someone help me creating this exposed filter? Thanks!


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.