Defining custom Views handlers or pluginsfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Views in Drupal offers a robust system for creating dynamic, customizable listings and data presentations. By defining custom Views handlers or plugins, you expand the capability of your site views, ultimately enabling more sophisticated and interactive user experiences. This lesson delves into creating custom handlers and plugins that elevate your site's data display capabilities.

Understanding Views Handlers and Plugins

Drupal's Views module is a powerful tool for generating dynamic content lists and displays. Views handlers and plugins extend this functionality by allowing developers to introduce new behaviors and data manipulations within Views. Handlers can process data differently, add custom filters, or define unique sorts, while plugins can add display options, query alterations, or provide new styles.

Crafting Your Custom Views Plugin

Let’s create a custom Views plugin to introduce a new style that presents content in a card layout. This addition will enhance the engagement of listed content items.

Step 1: Define the Plugin

Create a directory for your Views plugin within your module, typically src/Plugin/views/style. Then, create a file named CardLayout.php.


namespace Drupal\your_module\Plugin\views\style;

use Drupal\views\Plugin\views\style\StylePluginBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * A Views style plugin for displaying content in a card layout.
 *
 * @ViewsStyle(
 *   id = "card_layout",
 *   title = @Translation("Card Layout"),
 *   help = @Translation("Displays content in a card layout."),
 *   theme = "views_view_card_layout",
 *   display_types = {"normal"}
 * )
 */
class CardLayout extends StylePluginBase {
    /**
     * {@inheritdoc}
     */
    public function render() {
        $rows = $this->view->style_plugin->renderGrouping($this->view->result);
        
        return [
            '#theme' => $this->themeFunctions(),
            '#rows' => $rows,
        ];
    }
}

This plugin extends StylePluginBase and defines a new style for displaying View results. By linking the plugin to a theme hook, you facilitate custom theming and rendering strategies.

Step 2: Add a Theme Hook

To enhance the card layout style, register a theme hook in your module’s .module file:


/**
 * Implements hook_theme().
 */
function your_module_theme() {
    return [
        'views_view_card_layout' => [
            'variables' => ['rows' => []],
        ],
    ];
}

Use this hook to define how the card layout will be styled. This structure ensures your content displays as intended, offering creative flexibility in how data is organized and presented to site users.

Step 3: Create a Theme Template

Create a template file named views-view-card-layout.html.twig within your module’s templates directory to define the HTML structure for your card layout:


{% for row in rows %}
  
{{ row.content }}
{% endfor %}

In this example, each result is wrapped in a div with the class card. You can apply CSS to style the cards to fit within your site’s design framework.

Enhancing Display with Custom Handlers

Handlers allow distinct query and rendering logic within views. You might create custom handlers to add new filtering capabilities specific to your data model or introduce specialized sorting logic.

Developing a Custom Filter

Perhaps you need a custom filter to display content based on unique criteria not supported out of the box. Create a PHP file under src/Plugin/views/filter:


namespace Drupal\your_module\Plugin\views\filter;

use Drupal\views\Plugin\views\filter\FilterPluginBase;

/**
 * Custom handler for filtering based on a custom condition.
 *
 * @ViewsFilter("custom_condition_filter")
 */
class CustomConditionFilter extends FilterPluginBase {

    /**
     * {@inheritdoc}
     */
    public function query() {
        // Apply custom filtering logic using conditions.
        $this->query->addWhereExpression(0, 'custom_field >= :value', [':value' => $this->value]);
    }
}

This filter implementation allows you to modify how data is retrieved based on specialized conditions. Such filters give developers the power to fine-tune displays to fit precise data requirements.

Conclusion

Defining custom Views handlers or plugins amplifies the potential of your Drupal site, offering enriched data displays and sophisticated query options. Through this lesson, you’ve learned how to extend Views with custom style plugins and handlers that enhance aesthetics and functionality.

Next, we'll explore "Defining Custom Contextual Filters in Views," where you'll further refine how views accommodate user inputs and contextual data, making your displays more dynamic and interactive. Continue developing with Drupal, one powerful feature at a time!