0

I have a "Feedback" form implemented on a block. This block displays only when viewing the user profile page.

To stop people rating themselves, I would like to hide this block when the logged in user is viewing their own profile page.

This block should only show when viewing other people's profile pages.

I am using Drupal 8.

How can I do this please?

Here is the code I am currently using:

The issue is a person should not see the block when viewing their own profile page. They should see the block only when viewing another person's profile.

/**
 * Hide feedback form to prevent self voting.
 */
 use \Drupal\block\Entity\Block; 
 use \Drupal\Core\Session\AccountInterface;

function zup_hide_feedback_form_block_access($block, $account) {

    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $uid= $user->get('uid')->value;

    if ($operation == 'view' && $block->getPluginId() == 'block-webform-3') {
        if($account->id() != $uid){
            return \Drupal\Core\Access\AccessResult::forbiddenIf($block->getRegion())
            ->addCacheableDependency($block);
        }
    }
      // No opinion.
      return \Drupal\Core\Access\AccessResult::neutral();
}
2

You can use hook_block_access()

/**
 * Implements hook_block_access().
 */
 function mymodule_block_access(\Drupal\block\Entity\Block $block, $operation, \Drupal\Core\Session\AccountInterface $account) {
  if($operation == 'view' && $block->getPluginId() == 'block_id') {
    $uid_from_url = Drupal::requestStack()->getCurrentRequest()->get('user')->id();
    if($account->id() == $uid_from_url) {
      return \Drupal\Core\Access\AccessResult::forbiddenIf($block->getRegion())
        ->addCacheableDependency($block);
    }
  }
  // No opinion.
  return \Drupal\Core\Access\AccessResult::neutral();
}

See more document function hook_block_access

  • Thanks for your help but the above still shows the feedback block when I access my profile page. Basically the Feedback form (block) should not appear when a person is viewing their own profile BUT should appear when they are viewing other people's profile page. – ibexy Aug 23 '18 at 9:02
  • you need condition if($account->id() != $uid_from_url) – vinhdv Aug 23 '18 at 10:48
  • I chnaged the code above as requested but I still see the block when I visit my profile page. Here is the code now: – ibexy Aug 24 '18 at 14:11
  • @ibexy you see api get request parameter from url api.drupal.org/api/drupal/… – vinhdv Aug 24 '18 at 14:15
  • Added the code sample in the original post. – ibexy Aug 24 '18 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.