2

Hi after following this guide I was able to create multiple blocks. But I have couple of issues.

  1. Blocks are not created instantly need to clear cache but cant find a way to do it instantly (solution might be clearing block cache but how ?).
  2. I need to assign region to the block while creating itself but cant do so .
  3. I want to have x content for x block id and y content for y block id cant write a filter condition as I cant get block id of the blocks.

Basically I want to achieve all the D7 module's functionality in D8.

If anyone have an idea please help me.

  • 1
    Well of course you need to clear cache when adding new block definitions - the system needs to pick up the annotation class that was added. – Kevin Jul 19 '18 at 14:59
  • Yes, just like I commented over there, this is by design. Blocks in Drupal 8 are placed by creating them, they don't exist by default. If you want to automatically put them somewhere then you need to create a new block config entity. – Berdir Sep 5 '18 at 14:23
2

That's expected. You can do it from code if needed. The following are the steps to follow.

  1. Settings definition is done as in block.block.test_block.yml. Place that file, after editing it, in my_module/config/install and you're set. A quick hack is managing the block settings manually in a local environment and export them from /admin/config/development/configuration/single/export.

  2. Import your settings, which can be done using code similar to the following one.

    use Drupal\Core\Config\FileStorage;
    
    $config_path = drupal_get_path('module', 'my_module') . '/config/install';
    $source = new FileStorage($config_path);
    $config_storage = \Drupal::service('config.storage');
    $block_config = 'block.block.test_block';
    $config_storage->write($block_config , $source->read($block_config));
    

    Block settings are theme dependent.

For dynamic allocation of blocks, you can load and alter the block entity like this.

use Drupal\block\Entity\Block;

$block = Block::load('test_block');
$block->setRegion('my_region');
$block->save();

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.