3 namespace Drupal\Tests\block\Traits;
5 use Drupal\block\Entity\Block;
8 * Provides methods to create and place block with default settings.
10 * This trait is meant to be used only by test classes.
12 trait BlockCreationTrait {
15 * Creates a block instance based on default settings.
17 * @param string $plugin_id
18 * The plugin ID of the block type for this block instance.
19 * @param array $settings
20 * (optional) An associative array of settings for the block entity.
21 * Override the defaults by specifying the key and value in the array, for
24 * $this->drupalPlaceBlock('system_powered_by_block', array(
25 * 'label' => t('Hello, world!'),
28 * The following defaults are provided:
29 * - label: Random string.
30 * - ID: Random string.
31 * - region: 'sidebar_first'.
32 * - theme: The default theme.
33 * - visibility: Empty array.
35 * @return \Drupal\block\Entity\Block
39 * Add support for creating custom block instances.
41 protected function placeBlock($plugin_id, array $settings = []) {
42 $config = \Drupal::configFactory();
44 'plugin' => $plugin_id,
45 'region' => 'sidebar_first',
46 'id' => strtolower($this->randomMachineName(8)),
47 'theme' => $config->get('system.theme')->get('default'),
48 'label' => $this->randomMachineName(8),
53 foreach (['region', 'id', 'theme', 'plugin', 'weight', 'visibility'] as $key) {
54 $values[$key] = $settings[$key];
55 // Remove extra values that do not belong in the settings array.
56 unset($settings[$key]);
58 foreach ($values['visibility'] as $id => $visibility) {
59 $values['visibility'][$id]['id'] = $id;
61 $values['settings'] = $settings;
62 $block = Block::create($values);