Integration with SHS

Created on 10 April 2023, almost 2 years ago
Updated 26 May 2024, 8 months ago

I've made a views filter handler which extends shs views filter handlers.
It's just a clone of TaxonomyEntityIndexTidDepth, but instead extending ShsTaxonomyIndexTidDepth
It could be dropped into this module to provide much-needed extra functionality.

namespace Drupal\taxonomy_entity_index\Plugin\views\filter;

use Drupal\Core\Database\Query\Condition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\shs\Plugin\views\filter\ShsTaxonomyIndexTidDepth;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ViewExecutable;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Filter handler for smallad categories with depth.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("shs_taxonomy_entity_index_tid_depth")
 */
class ShsTaxonomyEntityIndexTidDepth extends ShsTaxonomyIndexTidDepth implements ContainerFactoryPluginInterface {

  /**
   * The vocabulary storage.
   *
   * @var \Drupal\taxonomy\VocabularyStorageInterface
   */
  protected $vocabularyStorage;

  /**
   * The term storage.
   *
   * @var \Drupal\taxonomy\TermStorageInterface
   */
  protected $termStorage;

  /**
   * Stores the base table information.
   *
   * @var array
   */
  private $baseTableInfo = [];

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->database = $container->get('database');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->baseTableInfo = \Drupal::service('views.views_data')->get($this->table);
  }

  /**
   * {@inheritdoc}
   */
  public function buildExtraOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildExtraOptionsForm($form, $form_state);
    $form['depth']['#description'] = $this->t('The depth will match entities tagged with terms in the hierarchy. For example, if you have the term "fruit" and a child term "apple", with a depth of 1 (or higher) then filtering for the term "fruit" will get entities that are tagged with "apple" as well as "fruit". If negative, the reverse is true; searching for "apple" will also pick up nodes tagged with "fruit" if depth is -1 (or lower).');
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    // If no filter values are present, then do nothing.
    if (count($this->value) == 0) {
      return;
    }
    elseif (count($this->value) == 1) {
      // Sometimes $this->value is an array with a single element so convert it.
      if (is_array($this->value)) {
        $this->value = current($this->value);
      }
      $operator = '=';
    }
    else {
      $operator = 'IN';
    }

    // The normal use of ensure_my_table() here breaks Views.
    // So instead we trick the filter into using the alias of the base table.
    // See http://drupal.org/node/271833
    // If a relationship is set, we must use the alias it provides.
    if (!empty($this->relationship)) {
      $this->tableAlias = $this->relationship;
    }
    // If no relationship, then use the alias of the base table.
    else {
      $this->tableAlias = $this->query->ensureTable($this->view->storage->get('base_table'));
    }

    // Now build the subqueries.
    $subquery = $this->database->select('taxonomy_entity_index', 'tei');
    $base_field = $this->baseTableInfo['taxonomy_entity_index_entity_tid']['relationship']['base field'];
    $real_field = $this->baseTableInfo['taxonomy_entity_index_entity_tid']['relationship']['real field'];
    $subquery->addField('tei', $base_field);
    if (isset($this->baseTableInfo['table']['entity type'])) {
      $subquery->condition('entity_type', $this->baseTableInfo['table']['entity type']);
    }
    $or = new Condition('OR');
    $where = $or->condition('tei.tid', $this->value, $operator);
    $last = "tei";

    if ($this->options['depth'] > 0) {
      $subquery->leftJoin('taxonomy_term__parent', 'th', "th.entity_id = tei.tid");
      $last = "th";
      foreach (range(1, abs($this->options['depth'])) as $count) {
        $subquery->leftJoin('taxonomy_term__parent', "th$count", "$last.parent_target_id = th$count.entity_id");
        $where->condition("th$count.entity_id", $this->value, $operator);
        $last = "th$count";
      }
    }
    elseif ($this->options['depth'] < 0) {
      foreach (range(1, abs($this->options['depth'])) as $count) {
        $subquery->leftJoin('taxonomy_term__parent', "th$count", "$last.entity_id = th$count.parent_target_id");
        $where->condition("th$count.entity_id", $this->value, $operator);
        $last = "th$count";
      }
    }

    $subquery->condition($where);
    $this->query->addWhere($this->options['group'], "$this->tableAlias.$real_field", $subquery, 'IN');
  }

}

Then, in my_module add the filter to the views handlers for the entity.

function my_module_views_data_alter(&$data) {
  $data['my_entity']['shs_taxonomy_entity_index_tid_depth']['filter']['id'] = 'shs_taxonomy_entity_index_tid_depth';
}
✨ Feature request
Status

Needs work

Version

1.0

Component

Code

Created by

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @matslats
  • πŸ‡¦πŸ‡ΊAustralia larowlan πŸ‡¦πŸ‡ΊπŸ.au GMT+10

    I think the best place for this would be in an optional sub-module, either here or in SHS

  • Status changed to Needs work 8 months ago
  • πŸ‡«πŸ‡·France Grimreaper France πŸ‡«πŸ‡·

    Hi,

    Thanks for the shared code.

    In my_module.views.inc, I put the following code to see the filter:

    function my_module_views_data_alter(&$data) {
      $entity_info = taxonomy_entity_index_entity_views_integrable();
      // Loop over compatible entity types.
      foreach ($entity_info as $info) {
        if ($info->getKey('id')) {
          $base_table = $info->getBaseTable();
          $label = $info->getLabel();
          $entity_keys = $info->getKeys();
          // Is revision support enabled & does the current entity type support it?
          $revisions = taxonomy_entity_index_entity_views_revisionable($entity_keys);
    
          $data[$base_table]['my_module_shs_taxonomy_entity_index_tid_depth'] = [
            'help' => t('Display content if it has the selected taxonomy terms, or children of the selected terms. Due to additional complexity, this has fewer options than the versions without depth.'),
            'group' => t('Taxonomy Entity Index'),
            'real field' => $revisions ? $entity_keys['revision'] : $entity_keys['id'],
            'filter' => [
              'title' => t('Has taxonomy terms on @entity_type (with depth and indexed in taxonomy_entity_index) (SHS)', ['@entity_type' => $label]),
              'id' => 'my_module_shs_taxonomy_entity_index_tid_depth',
            ],
          ];
        }
      }
    }
    
    

    my_module_shs_taxonomy_entity_index_tid_depth is the plugin ID I put in one of my custom module to test/have it until merged.

    But after adding a filter, I obtain the following error message:

    No valid values found on filter: Taxonomy Entity Index: Has taxonomy terms on Paragraphe (with depth and indexed in taxonomy_entity_index) (SHS).

  • πŸ‡«πŸ‡·France Grimreaper France πŸ‡«πŸ‡·

    Possibility to replace:

        $this->baseTableInfo = \Drupal::service('views.views_data')->get($this->table);
    

    By:

        $this->baseTableInfo = $this->getViewsData()->get($this->table);
    

    To avoid the call to drupal service.

    And when using strict types:

    Update:

          foreach (range(1, abs($this->options['depth'])) as $count) {
    
    

    By:

          foreach (\range(1, \abs((int) $this->options['depth'])) as $count) {
    
Production build 0.71.5 2024