Another major area where you will deal with access is when trying to control access to a custom block. If you remember in Chapter 2, Creating Your First Module, we created the HelloWorldSalutationBlock plugin so that our salutation can also be rendered using a block. Now that block can be placed in a region and even configured to show up only on certain pages, for certain user roles, or even on node pages restricted by bundle. This is all done in the UI:
However, this is oftentimes not enough, and you will want to have a block placed in a region and control yourself under what circumstances it should show up. Enter block access.
Inside the BlockBase plugin base class, there is the blockAccess() method which always returns positively. This is because, by default, all blocks will be rendered once they are placed in a region. Unless, of course, they are configured to only show in certain cases, in which case a system of visibility based on the available contexts kicks in to control that. However, if we override this method in our block plugin class, we can control whether or not the block is shown. So we can leave the visibility options empty when placing the block in a region and then handle everything we want regarding its visibility inside the blockAccess() method. Neat, isn't it?
Also, as expected, the method has one parameter, namely the account being checked, and needs to return an AccessResultInterface. Since we can inject services into our block plugin (by implementing the ContainerFactoryPluginInterface as we saw in Chapter 2, Creating Your First Module), we can use what we want to check whether the given user should see the block. If we deny access, the block is simply not rendered.
That is pretty much all there is to the block access control.