3

I need to override the block configuration form in Drupal 8.

To override the configuration form for a new block we are creating can be done by implementing BlockBase::buildConfigurationForm method.

But I need to alter the configuration form for all the blocks which means overriding the BlockBase class. How can I implement this?

Is there a generic way to override all Drupal Core classes?

  • 1
    BlockBase isn't a service so you don't have DI here, I suspect you can't swap that class out (but I might be wrong). I'm not sure there's a non-hacky way to do what you need – Clive Aug 3 '15 at 10:02
4

No, you can't change the base class. This is a PHP language construct, it's not possible to override it.

I'm not exactly sure what you are trying to do but it is likely that what you are looking for is a plain old hook_form_alter() + third party settings on the block config entity.

The Block class D8 sandbox is a simple module that is doing exactly this and allows to configurabe custom CSS classes for every block.

Note that this is on a different level, you are altering the block config entity and it will only apply to how Drupal core/block.module uses block plugins but not e.g. page_manager. Doing it in a more generic way is simply not possible.

  • Well, you can do dirty things with changing the way how the classloader works, but I won't recommend that anyone and I think telling how to do it, is a bad idea – Daniel Wehner Aug 3 '15 at 21:36
  • Uh, yeah, I don't think you want to go there :) That's not just dirty, that's evil :) – Berdir Aug 3 '15 at 21:39
  • Yes a simple form_alter can do it. Thanks for saving me again :) – Pravin Ajaaz Aug 4 '15 at 6:28
  • Thank you for this suggestion! I was able to replicate the code from block_class to add fields to the block config form. Additionally, currently if you want the fields to appear within the config form in Layout Builder, you will need this patch and the core patch that is linked there. drupal.org/project/block_class/issues/2998114 – maskedjellybean Jan 31 at 21:46
  • With the patched code as a reference I was able to add checkbox fields to the block config form within Layout Builder which I use to display or hide blocks at certain breakpoints. I may make this into a contrib module because I imagine it would be useful to others. There is too much code to post as an answer here, but look to block_class for guidance. – maskedjellybean Jan 31 at 21:46
1

Use hook_entity_info_alter (from memory) and change the form class for the block entity

See entity.api.php for examples

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.