Created
October 28, 2021 15:44
-
-
Save markfullmer/3292ad93792d9530cacb7da5c42d1b21 to your computer and use it in GitHub Desktop.
Set Drupal View to be used per taxonomy vocabulary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\mymodule\Enhancer; | |
use Drupal\Core\Routing\EnhancerInterface; | |
use Drupal\taxonomy\TermInterface; | |
use Symfony\Component\HttpFoundation\Request; | |
use Symfony\Component\Routing\Route; | |
use Drupal\taxonomy\Entity\Term; | |
/** | |
* Override views defaults arguments for specific taxonomy vocabulary. | |
* | |
*/ | |
class RouteEnhancer implements EnhancerInterface { | |
/** | |
* Check if the route applies to the current path. | |
* | |
* @param \Symfony\Component\Routing\Route $route | |
* The route that is being enhanced. | |
* | |
* @return bool | |
* Return true if the route path applies. | |
*/ | |
private function applies(Route $route) { | |
return $route->getPath() == '/taxonomy/term/{taxonomy_term}'; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function enhance(array $defaults, Request $request) { | |
// Guard the route. | |
if (!$this->applies($defaults['_route_object'])) { | |
return $defaults; | |
} | |
// If the route has no term, ignore it. | |
if (empty($defaults['taxonomy_term'])) { | |
return $defaults; | |
} | |
$term = $defaults['taxonomy_term']; | |
// Attempt to load the term if passed a TID. | |
if (is_numeric($term)) { | |
$term = Term::load($term); | |
} | |
if ($term instanceof TermInterface) { | |
switch ($term->bundle()) { | |
case 'my_vocbulary': | |
$defaults['view_id'] = 'my_vocbulary'; | |
$defaults['display_id'] = 'page'; | |
break; | |
default: | |
$defaults['view_id'] = 'taxonomy_term'; | |
$defaults['display_id'] = 'page_1'; | |
break; | |
} | |
} | |
return $defaults; | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
mymodule.route_enhancer: | |
class: Drupal\mymodule\Enhancer\RouteEnhancer | |
tags: | |
- { name: route_enhancer } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment