Skip to content

Instantly share code, notes, and snippets.

@sumitk
Forked from filipengberg/hide_untranslated.php
Created July 8, 2020 06:30
Show Gist options
  • Save sumitk/5beac7f7b5df4900bdd7e8ab3d0a9a30 to your computer and use it in GitHub Desktop.
Save sumitk/5beac7f7b5df4900bdd7e8ab3d0a9a30 to your computer and use it in GitHub Desktop.

Revisions

  1. @filipengberg filipengberg renamed this gist Mar 16, 2016. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @filipengberg filipengberg created this gist Mar 16, 2016.
    43 changes: 43 additions & 0 deletions hide_untranslated.module
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    <?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();
    }