function BlockCreationTrait::placeBlock

Same name and namespace in other branches
  1. 9 core/modules/block/tests/src/Traits/BlockCreationTrait.php \Drupal\Tests\block\Traits\BlockCreationTrait::placeBlock()
  2. 8.9.x core/modules/block/tests/src/Traits/BlockCreationTrait.php \Drupal\Tests\block\Traits\BlockCreationTrait::placeBlock()
  3. 11.x core/modules/block/tests/src/Traits/BlockCreationTrait.php \Drupal\Tests\block\Traits\BlockCreationTrait::placeBlock()

Creates a block instance based on default settings.

@todo Add support for creating content block instances.

Parameters

string $plugin_id: The plugin ID of the block type for this block instance.

array $settings: (optional) An associative array of settings for the block entity. Override the defaults by specifying the key and value in the array, for example:

$this->drupalPlaceBlock('system_powered_by_block', [
  'label' => t('Hello, world!'),
]);

The following defaults are provided:

  • label: Random string.
  • id: Random string.
  • region: 'sidebar_first'.
  • theme: The default theme.
  • visibility: Empty array.

Return value

\Drupal\block\Entity\Block The block entity.

242 calls to BlockCreationTrait::placeBlock()
AccessDeniedTest::setUp in core/modules/system/tests/src/Functional/System/AccessDeniedTest.php
AccessDeniedTest::testAccessDenied in core/modules/system/tests/src/Functional/System/AccessDeniedTest.php
AccessTestBase::setUp in core/modules/user/tests/src/Functional/Views/AccessTestBase.php
Sets up the test.
AjaxBlockTest::setUp in core/modules/layout_builder/tests/src/FunctionalJavascript/AjaxBlockTest.php
AjaxFormCacheTest::testBlockForms in core/tests/Drupal/FunctionalJavascriptTests/Ajax/AjaxFormCacheTest.php
Tests AJAX forms in blocks.

... See full list

File

core/modules/block/tests/src/Traits/BlockCreationTrait.php, line 42

Class

BlockCreationTrait
Provides methods to create and place block with default settings.

Namespace

Drupal\Tests\block\Traits

Code

protected function placeBlock($plugin_id, array $settings = []) {
  $config = \Drupal::configFactory();
  $settings += [
    'plugin' => $plugin_id,
    'region' => 'content',
    'id' => $this->randomMachineName(8),
    'theme' => $config->get('system.theme')
      ->get('default'),
    'label' => $this->randomMachineName(8),
    'visibility' => [],
    'weight' => 0,
  ];
  $values = [];
  foreach ([
    'region',
    'id',
    'theme',
    'plugin',
    'weight',
    'visibility',
  ] as $key) {
    $values[$key] = $settings[$key];
    // Remove extra values that do not belong in the settings array.
    unset($settings[$key]);
  }
  foreach ($values['visibility'] as $id => $visibility) {
    $values['visibility'][$id]['id'] = $id;
  }
  $values['settings'] = $settings;
  $block = Block::create($values);
  $block->save();
  return $block;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.