3

I am trying to create a custom Views filter plugin. Basically it should read the current path, check the relevant path field in the node (defined as text-field) and get that content. I'm stuck around generateOptions() function and defining "Content: Filter by path if avail (= field_pathoes)" – please see screen shot below and code.

 <?php
/**
 * Implements hook_views_data_alter().
 */
function atc_views_filter_path_views_data_alter(array &$data) {
    $data['node_field_data']['field_pathoes'] = array(
        'title' => t('Filter by path if available'),
        'filter' => array(
            'title' => t('Filter by path if avail'),
            'help' => t('Checks current path and if value in path_field match, then the content is used.'),
            'field' => 'type',
            'id' => 'atc_views_filter_path_field_pathoes'
        ),
    );
}

/**
 * @file
 * Definition of Drupal\atc_views_filter_path\Plugin\views\filter\NodeTitles.
 */

namespace Drupal\atc_views_filter_path\Plugin\views\filter;

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\Equality;
use Drupal\views\ViewExecutable;
use Drupal\Core\Url;

/**
 * Filters by given list of node title options.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("atc_views_filter_path_field_pathoes")
 */
class PathValueFilter extends Equality
{

    /**
     * {@inheritdoc}
     */
    public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL)
    {
        parent::init($view, $display, $options);
        $this->valueTitle = t('Path filter to be included');
        $this->definition['options callback'] = array($this, 'generateOptions');
    }

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

    /**
     * Helper function that generates the options.
     * @return array 
     */
    public function generateOptions()
    {
        //use Drupal\Core\Url;
        $current_route = Url::fromRoute('<current>')->getInternalPath();

        return array(
            'field_pathoes_value' => $current_route,            
        );
    }

}

view_screen_shot

  • You should try and use arguments here instead of filters. – nikunj Jan 29 '18 at 8:50

Your Answer

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

Browse other questions tagged or ask your own question.