Describe your bug or feature request.

On the user page /user/[user-id] there is a tab "orders".
There is no way to hide it, even the only permission for authenticated user is "view own orders"

The tab is visible for user A when he is viewing user B. When User A clicks the "orders" tab on user B page, the
site says "The requested page could not be found. ".

So the tab "orders" should not be visible when viewing other user's pages.

How can I hide the tab "orders" so that it is only visible when I visit my own page, but hidden when I visit
others pages?

If a bug, provide steps to reproduce it from a clean install.

Comments

jukka792 created an issue. See original summary.

bob.hinrichs’s picture

I spent all day fixing this. The best way is unclear, but I had to create a custom Access class like this:

class IsMyUserOrAdmin implements AccessInterface {
  protected $routeMatch;
  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  public function access(AccountInterface $account) {
    // return true if the useris an admin or the user id in the route matches the current user id
    return AccessResult::allowedIf($account->hasPermission('administer users')
      || $account->id() == $this->routeMatch->getParameter('user')->id());
  }
} 

Then set it up as a service like:

  mymodule.is_my_user_or_admin:
    class: Drupal\mymodule\Access\IsMyUserOrAdmin
    arguments: ['@current_route_match']
    tags:
      - { name: access_check, applies_to: _mymodule_is_my_user_or_admin }

Then since this is a view, I made it a views custom access plugin, with this being the operative part.

  public function alterRouteDefinition(Route $route) {
    $route->setRequirement('_custom_access', 'mymodule.is_my_user_or_admin::access');
  }

I am kind of blown away by how much knowledge and engineering was needed to solve this very simple problem. There is perhaps an easier way but this was the most functional way, that can be reused in the system in similar cases.

mradcliffe’s picture

Stumbled across this behavior, and did a bit of issue digging. I appreciate the code example that you posted as that'll help me.

It looks like this has been an issue with Views since Drupal 6 and Drupal 7 in contrib., and carried over into Views in core in Drupal 8, 9, 10 and 11 #426114: Option to prevent view access (eg to hide tab) when view is empty

kayograco’s picture

I tried this code to put the class "my-profile" into the body, but it breaks the site when clicking on "Orders" (Commerce) tab.

function MYTHEME_preprocess_page(array &$variables) {
  $current_user = \Drupal::currentUser();  
  if ($user = \Drupal::routeMatch()->getParameter('user')) {
    if ($user->id() == $current_user->id()) {
      $variables['attributes']['class'][] = 'my-profile';
    }
  }
}