Custom restrictions using hooks (for developers)
Last updated on
21 May 2021
Site-specific restrictions not requiring UI-based changes can be done by implementing hook_plugin_filter_TYPE__CONSUMER_alter() (which is invoked for both themes and modules). Examples follow.
Restrict certain blocks across all Layout Builder usage sitewide
/**
* Implements hook_plugin_filter_TYPE__CONSUMER_alter().
*/
function mymodule_plugin_filter_block__layout_builder_alter(array &$definitions) {
// Explicitly remove the "Help" blocks from the list.
unset($definitions['help_block']);
// Explicitly remove the "Sticky at top of lists field_block".
$disallowed_fields = [
'sticky',
];
foreach ($definitions as $plugin_id => $definition) {
// Field block IDs are in the form 'field_block:{entity}:{bundle}:{name}',
// for example 'field_block:node:article:revision_timestamp'.
preg_match('/field_block:.*:.*:(.*)/', $plugin_id, $parts);
if (isset($parts[1]) && in_array($parts[1], $disallowed_fields, TRUE)) {
// Unset any field blocks that match our predefined list.
unset($definitions[$plugin_id]);
}
}
}Restrict access to layouts and blocks by user role
/**
* Implements hook_plugin_filter_TYPE__CONSUMER_alter().
*/
function mymodule_plugin_filter_layout__layout_builder_alter(array &$definitions, array $extra) {
$currentUser = User::load(\Drupal::currentUser()->id());
if (isset($definitions['diagonal']) && !$currentUser->hasRole('administrator')) {
unset($definitions['diagonal']);
}
}
/**
* Implements hook_plugin_filter_TYPE__CONSUMER_alter().
*/
function mymodule_plugin_filter_block__layout_builder_alter(array &$definitions, array $extra) {
$currentUser = User::load(\Drupal::currentUser()->id());
if (!$currentUser->hasRole('administrator')) {
unset($definitions['inline_block:icon_with_text']);
unset($definitions['inline_block:news_cards_external']);
unset($definitions['inline_block:program_list']);
unset($definitions['inline_block:profile_collection']);
unset($definitions['inline_block:view']);
unset($definitions['inline_block:work_study_list']);
unset($definitions['inline_block:advanced_accordion']);
}
}
Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion