Integrating with Views Remote Data

Last updated on
30 April 2024

This documentation needs review. See "Help improve this page" in the sidebar.

Views Remote Data does not have a user interface for integration. You must integrate with Views Remote Data by defining information in hook_views_data() and implement an event subscriber. This guide page will walk through the following steps:

  • Defining a new Views base table that uses Views Remote Data.
  • Subscribing to the event to fetch remote data and set the data as the view's results.
  • Creating mocked entities to be attached to the results.

Defining a new Views base table that uses Views Remote Data

First, you must implement hook_views_data() in your module to create a base that uses the views_remote_data_query Views query plugin. This plugin is provided by the Views Remote Data module and is used to fire events that allow retrieving remote data to be displayed in a View.

Below is an example of minimum data needed for integrating with Views Remote Data. This allows rendering arbitrary data via fields in Views, like the Database Logging view for the watchdog table.

File: mymodule.views.inc

<?php

/**
 * @file
 * Provide views data for mymodule.
 */

declare(strict_types=1);

/**
 * Implements hook_views_data().
 */
function mymodule_views_data(): array {
  $data = [];

  $data['mymodule_remote_data']['table']['group'] = 'mymodule_remote_data';
  $data['mymodule_remote_data']['table']['base'] = [
    'title' => 'My Remote Data',
    'query_id' => 'views_remote_data_query',
  ];

  return $data;
}

If you would like to integrate with an existing entity type use the following example:

<?php

/**
 * @file
 * Provide views data for mymodule.
 */

declare(strict_types=1);

/**
 * Implements hook_views_data().
 */
function mymodule_views_data(): array {
  $data = [];

  $data['mymodule_remote_data']['table']['group'] = 'mymodule_remote_data';
  $data['mymodule_remote_data']['table']['base'] = [
    'title' => 'My Remote Data',
    'query_id' => 'views_remote_data_query',
  ];
  // These are required by Views for additional metadata.
  $data['mymodule_remote_data']['table']['entity type'] = 'node';
  $data['mymodule_remote_data']['table']['entity revision'] = FALSE;

  return $data;
}

This will expose the My Remote Data option to Views.

Setting the view's results

When a view using Views Remote Data is executed, the \Drupal\views_remote_data\Events\RemoteDataQueryEvent event is dispatched. This event contains:

  • Access to the ViewExecutable that is being run.
  • The conditions (contextual filter arguments and filters.)
  • The sorts.
  • The limit, for paging.
  • The offset amount, for paging.

This information can then be used to create an HTTP request, or other action, to retrieve remote data. Once you have your data, you must iterate over it and add new \Drupal\views\ResultRow values to the dispatched event.

\Drupal\views\ResultRow's constructor receives an array of values, it is just a wrapper around an arbitrary array of data.

The following is an example event subscriber:

File: src/EventSubscriber/MyRemoteDataSubscriber.php

<?php

declare(strict_types=1);

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Component\Serialization\Json;
use Drupal\views\ResultRow;
use Drupal\views_remote_data\Events\RemoteDataQueryEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

final class MyRemoteDataSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    return [
      RemoteDataQueryEvent::class => 'onQuery',
    ];
  }

  /**
   * Subscribes to populate the view results.
   *
   * @param \Drupal\views_remote_data\Events\RemoteDataQueryEvent $event
   *   The event.
   */
  public function onQuery(RemoteDataQueryEvent $event): void {
    $supported_bases = ['mymodule_remote_data'];
    $base_tables = array_keys($event->getView()->getBaseTables());
    if (count(array_intersect($supported_bases, $base_tables)) > 0) {
      $remote_data = $this->methodWhichCallsRemoteApi();

      foreach ($remote_data['data'] as $item) {
          $event->addResult(new ResultRow($item));
      }
    }
  }

}

Attaching entities to the results

Views Remote Data allows attaching entities to the views results, without actually having to have the entities stored locally. This is accomplished with the dispatched \Drupal\views_remote_data\Events\RemoteDataLoadEntitiesEvent event. This event allows you to set an entity on the ResultRow for the view results.

An updated example of the event subscriber above follows:

File: src/EventSubscriber/MyRemoteDataSubscriber.php

<?php

declare(strict_types=1);

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Component\Serialization\Json;
use Drupal\views\ResultRow;
use Drupal\views_remote_data\Events\RemoteDataLoadEntitiesEvent;
use Drupal\views_remote_data\Events\RemoteDataQueryEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

final class MyRemoteDataSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    return [
      RemoteDataQueryEvent::class => 'onQuery',
      RemoteDataLoadEntitiesEvent::class => 'onLoadEntities',
    ];
  }

  /**
   * Subscribes to populate the view results.
   *
   * @param \Drupal\views_remote_data\Events\RemoteDataQueryEvent $event
   *   The event.
   */
  public function onQuery(RemoteDataQueryEvent $event): void {
    $supported_bases = ['mymodule_remote_data'];
    $base_tables = array_keys($event->getView()->getBaseTables());
    if (count(array_intersect($supported_bases, $base_tables)) > 0) {
      $remote_data = $this->methodWhichCallsRemoteApi();

      foreach ($remote_data['data'] as $item) {
          $event->addResult(new ResultRow($item));
      }
    }
  }

  /**
   * Subscribes to populate entities against the results.
   *
   * @param \Drupal\views_remote_data\Events\RemoteDataLoadEntitiesEvent $event
   *   The event.
   */
  public function onLoadEntities(RemoteDataLoadEntitiesEvent $event): void {
    $supported_bases = ['mymodule_remote_data'];
    $base_tables = array_keys($event->getView()->getBaseTables());
    if (count(array_intersect($supported_bases, $base_tables)) > 0) {
      foreach ($event->getResults() as $key => $result) {
        assert(property_exists($result, 'name'));
        $result->_entity = EntityTest::create([
          'name' => $result->name,
        ]);
      }
    }
  }
}

Help improve this page

Page status: Needs review

You can: