Created
March 16, 2016 08:05
-
-
Save filipengberg/e6f64de799df75d724c2 to your computer and use it in GitHub Desktop.
Drupal 8 module that hides entities that has no translation in the currently viewed language. Also redirects untranslated node views to frontpage
This file contains hidden or 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 | |
use Drupal\Core\Entity\EntityInterface; | |
use Drupal\Core\Session\AccountInterface; | |
use Symfony\Component\HttpFoundation\RedirectResponse; | |
use Drupal\Core\Access\AccessResult; | |
use Drupal\Core\Url; | |
/** | |
* Implements HOOK_entity_access | |
* Hide entities in $check_types | |
* if they don't match the current language. | |
* If viewing an untranslated node, | |
* redirect to front page in current language | |
*/ | |
function hide_untranslated_entity_access(EntityInterface $entity, $operation, AccountInterface $account) { | |
$type = $entity->getEntityTypeId(); | |
$check_types = ['node', 'inline_entity', 'paragraph']; | |
if($operation != 'view' || !in_array($type, $check_types)) { | |
return AccessResult::neutral(); | |
} | |
$language = Drupal::languageManager()->getCurrentLanguage(); | |
if ($entity->language()->getId() == $language->getId()) { | |
return AccessResult::neutral(); | |
} | |
// If viewing a node that is not translated | |
// to current language, redirect user to frontpage | |
if ($type == 'node') { | |
$node = Drupal::routeMatch()->getParameter('node'); | |
if (isset($node) && $node->id() == $entity->id()) { | |
$url = Url::fromRoute('<front>', [], ['language' => $language]); | |
$response = new RedirectResponse($url->toString()); | |
$response->send(); | |
} | |
} | |
return AccessResult::forbidden(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment