How to override block class ?
Sometimes you need to alter the build method or other methods of block class created by core or contributed modules without creating another class and extend it because doing that will duplicate the block instead of override it.
For Drupal 9 you can use hook_block_alter to override the block class in question like this example of system branding block:
<?php
/**
* Implements hook_block_alter().
*/
function MODULE_block_alter(&$definitions) {
foreach ($definitions as $id => $definition) {
// Check on your plugin Id here.
if ($id === 'system_branding_block') {
// Set your new class here.
$definitions[$id]['class'] = 'Drupal\MODULE\Plugin\Block\SystemBrandingBlockAlter';
}
}
}
And then create your new class SystemBrandingBlockAlter in MODULE/src/Plugin/Block like this:
<?php
namespace Drupal\MODULE\Plugin\Block;
use Drupal\system\Plugin\Block\SystemBrandingBlock;
/**
* Provides a block to display 'Site branding' elements altered.
*/
class SystemBrandingBlockAlter extends SystemBrandingBlock {
/**
* {@inheritdoc}
*/
public function build() {
// This is the build method called now you can make your changes here.
$build = [];
$site_config = $this->configFactory->get('system.site');
$build['site_slogan'] = [
'#markup' => $site_config->get('slogan'),
'#access' => $this->configuration['use_site_slogan'],
];
return $build;
}
}
And you are done ✔️ after clear cache Drupal will pick your class instead of the original one.
Comments