Skip to content

Instantly share code, notes, and snippets.

@mattschaff
Last active April 1, 2019 14:24
Show Gist options
  • Save mattschaff/0b1d84da1dfb108f17b97a1eae0d286c to your computer and use it in GitHub Desktop.
Save mattschaff/0b1d84da1dfb108f17b97a1eae0d286c to your computer and use it in GitHub Desktop.
Drupal 8: Admin override of first item in a view
<?php
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
/**
* @file
* Hooks and procedural code for My Module
*
* This code should be in a *.module or *.inc file
*/
/**
* Implements hook_views_query_alter()
*/
function my_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
// Alter my_view query depending on input to the Featured Nodes form.
if ($view->id() === 'my_view') {
// Get config.
$config = \Drupal::config('my_module.featured_node');
if (is_object($config) && !empty($config->get('featured_node'))) {
// Add WHERE to query.
$nid = $config->get('featured_node');
// If featured block, view nid should be the admin-set view.
if (!empty($insight_view_featured) && $view->getDisplay()->display['id'] == 'featured_display') {
$operator = '=';
}
// If general landing page ...
// ... view nid should NOT be the admin-set view,
// and set offset to 0.
elseif (!empty($insight_view_page) && $view->getDisplay()->display['id'] == 'list_display') {
$operator = '<>';
$view->setOffset(0);
}
$query->addWhere(1, 'node_field_data.nid', $nid, $operator);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment