- Issue created by @pemson18
This should be possible today with code. You haven’t demonstrated it is not.
- 🇮🇳India pemson18 South Goa
I had to create a menu in the drupal admin backend ui and place it using the block layout admin section and then export it and in the menu link update the menu links for the menu in update hook. so its a mixture of ui config + update code not pure code.
You are saying that Drupal has no block placement API. Do I have that right?
Is Block::create not working in this case?
- Status changed to Postponed: needs info
5 months ago 5:40pm 28 July 2024 - 🇨🇷Costa Rica yuvania
Hi @Pemson18,
I've reviewed the discussion, and I'd like to offer a suggestion that might help clarify the process of block instantiation and placement using code in Drupal 10.
From my experience, it is possible to create and place blocks programmatically without using the UI configuration. Here's a basic example of how you might achieve this in an update hook:
use Drupal\block\Entity\Block; /** * Implements hook_update_N(). */ function mymodule_update_10001() { // Create a new custom block. $block = Block::create([ 'id' => 'my_custom_block', 'theme' => 'bartik', 'plugin' => 'my_custom_block_plugin', 'settings' => [], 'visibility' => [], 'region' => 'sidebar_first', 'weight' => 0, ]); $block->save(); // Ensure the block is placed in the desired region. \Drupal::service('theme_handler')->rebuildThemeData(); \Drupal::service('theme_handler')->refreshInfo(); $theme = \Drupal::theme()->getActiveTheme(); $theme_name = $theme->getName(); // Clear cache to apply changes. \Drupal::service('cache.render')->invalidateAll(); }
This code snippet creates a custom block and places it in the 'sidebar_first' region of the 'bartik' theme. Note that you need to adjust 'my_custom_block_plugin' to your actual block plugin ID.
Make sure to clear the cache after running the update hook to see the changes. This approach should bypass the need for UI configuration and ensure that your block is placed directly via code.
I hope this helps clarify the problem! Let me know if you need further clarification or assistance.
- Status changed to Closed: outdated
about 1 month ago 2:55am 15 November 2024