BlockContentCreationTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. <?php
  2. namespace Drupal\Tests\block_content\Functional;
  3. use Drupal\Component\Render\FormattableMarkup;
  4. use Drupal\block_content\Entity\BlockContent;
  5. use Drupal\Core\Database\Database;
  6. /**
  7. * Create a block and test saving it.
  8. *
  9. * @group block_content
  10. */
  11. class BlockContentCreationTest extends BlockContentTestBase {
  12. /**
  13. * Modules to enable.
  14. *
  15. * Enable dummy module that implements hook_block_insert() for exceptions and
  16. * field_ui to edit display settings.
  17. *
  18. * @var array
  19. */
  20. public static $modules = ['block_content_test', 'dblog', 'field_ui'];
  21. /**
  22. * {@inheritdoc}
  23. */
  24. protected $defaultTheme = 'classy';
  25. /**
  26. * Permissions to grant admin user.
  27. *
  28. * @var array
  29. */
  30. protected $permissions = [
  31. 'administer blocks',
  32. 'administer block_content display',
  33. ];
  34. /**
  35. * Sets the test up.
  36. */
  37. protected function setUp() {
  38. parent::setUp();
  39. $this->drupalLogin($this->adminUser);
  40. }
  41. /**
  42. * Creates a "Basic page" block and verifies its consistency in the database.
  43. */
  44. public function testBlockContentCreation() {
  45. $this->drupalLogin($this->adminUser);
  46. // Create a block.
  47. $edit = [];
  48. $edit['info[0][value]'] = 'Test Block';
  49. $edit['body[0][value]'] = $this->randomMachineName(16);
  50. $this->drupalPostForm('block/add/basic', $edit, t('Save'));
  51. // Check that the Basic block has been created.
  52. $this->assertRaw(new FormattableMarkup('@block %name has been created.', [
  53. '@block' => 'basic',
  54. '%name' => $edit['info[0][value]'],
  55. ]), 'Basic block created.');
  56. // Check that the view mode setting is hidden because only one exists.
  57. $this->assertNoFieldByXPath('//select[@name="settings[view_mode]"]', NULL, 'View mode setting hidden because only one exists');
  58. // Check that the block exists in the database.
  59. $blocks = \Drupal::entityTypeManager()
  60. ->getStorage('block_content')
  61. ->loadByProperties(['info' => $edit['info[0][value]']]);
  62. $block = reset($blocks);
  63. $this->assertNotEmpty($block, 'Custom Block found in database.');
  64. // Check that attempting to create another block with the same value for
  65. // 'info' returns an error.
  66. $this->drupalPostForm('block/add/basic', $edit, t('Save'));
  67. // Check that the Basic block has been created.
  68. $this->assertRaw(new FormattableMarkup('A custom block with block description %value already exists.', [
  69. '%value' => $edit['info[0][value]'],
  70. ]));
  71. $this->assertSession()->statusCodeEquals(200);
  72. }
  73. /**
  74. * Creates a "Basic page" block with multiple view modes.
  75. */
  76. public function testBlockContentCreationMultipleViewModes() {
  77. // Add a new view mode and verify if it is selected as expected.
  78. $this->drupalLogin($this->drupalCreateUser(['administer display modes']));
  79. $this->drupalGet('admin/structure/display-modes/view/add/block_content');
  80. $edit = [
  81. 'id' => 'test_view_mode',
  82. 'label' => 'Test View Mode',
  83. ];
  84. $this->drupalPostForm(NULL, $edit, t('Save'));
  85. $this->assertRaw(t('Saved the %label view mode.', ['%label' => $edit['label']]));
  86. $this->drupalLogin($this->adminUser);
  87. // Create a block.
  88. $edit = [];
  89. $edit['info[0][value]'] = 'Test Block';
  90. $edit['body[0][value]'] = $this->randomMachineName(16);
  91. $this->drupalPostForm('block/add/basic', $edit, t('Save'));
  92. // Check that the Basic block has been created.
  93. $this->assertRaw(new FormattableMarkup('@block %name has been created.', [
  94. '@block' => 'basic',
  95. '%name' => $edit['info[0][value]'],
  96. ]), 'Basic block created.');
  97. // Save our block permanently
  98. $this->drupalPostForm(NULL, ['region' => 'content'], t('Save block'));
  99. // Set test_view_mode as a custom display to be available on the list.
  100. $this->drupalGet('admin/structure/block/block-content');
  101. $this->drupalGet('admin/structure/block/block-content/types');
  102. $this->clickLink(t('Manage display'));
  103. $this->drupalGet('admin/structure/block/block-content/manage/basic/display');
  104. $custom_view_mode = [
  105. 'display_modes_custom[test_view_mode]' => 1,
  106. ];
  107. $this->drupalPostForm(NULL, $custom_view_mode, t('Save'));
  108. // Go to the configure page and change the view mode.
  109. $this->drupalGet('admin/structure/block/manage/testblock');
  110. // Test the available view mode options.
  111. $this->assertOption('edit-settings-view-mode', 'default', 'The default view mode is available.');
  112. $this->assertOption('edit-settings-view-mode', 'test_view_mode', 'The test view mode is available.');
  113. $view_mode['settings[view_mode]'] = 'test_view_mode';
  114. $this->drupalPostForm(NULL, $view_mode, t('Save block'));
  115. // Check that the view mode setting is shown because more than one exists.
  116. $this->drupalGet('admin/structure/block/manage/testblock');
  117. $this->assertFieldByXPath('//select[@name="settings[view_mode]"]', NULL, 'View mode setting shown because multiple exist');
  118. // Change the view mode.
  119. $view_mode['region'] = 'content';
  120. $view_mode['settings[view_mode]'] = 'test_view_mode';
  121. $this->drupalPostForm(NULL, $view_mode, t('Save block'));
  122. // Go to the configure page and verify the view mode has changed.
  123. $this->drupalGet('admin/structure/block/manage/testblock');
  124. $this->assertFieldByXPath('//select[@name="settings[view_mode]"]/option[@selected="selected"]', 'test_view_mode', 'View mode changed to Test View Mode');
  125. // Check that the block exists in the database.
  126. $blocks = \Drupal::entityTypeManager()
  127. ->getStorage('block_content')
  128. ->loadByProperties(['info' => $edit['info[0][value]']]);
  129. $block = reset($blocks);
  130. $this->assertNotEmpty($block, 'Custom Block found in database.');
  131. // Check that attempting to create another block with the same value for
  132. // 'info' returns an error.
  133. $this->drupalPostForm('block/add/basic', $edit, t('Save'));
  134. // Check that the Basic block has been created.
  135. $this->assertRaw(new FormattableMarkup('A custom block with block description %value already exists.', [
  136. '%value' => $edit['info[0][value]'],
  137. ]));
  138. $this->assertSession()->statusCodeEquals(200);
  139. }
  140. /**
  141. * Create a default custom block.
  142. *
  143. * Creates a custom block from defaults and ensures that the 'basic block'
  144. * type is being used.
  145. */
  146. public function testDefaultBlockContentCreation() {
  147. $edit = [];
  148. $edit['info[0][value]'] = $this->randomMachineName(8);
  149. $edit['body[0][value]'] = $this->randomMachineName(16);
  150. // Don't pass the custom block type in the url so the default is forced.
  151. $this->drupalPostForm('block/add', $edit, t('Save'));
  152. // Check that the block has been created and that it is a basic block.
  153. $this->assertRaw(new FormattableMarkup('@block %name has been created.', [
  154. '@block' => 'basic',
  155. '%name' => $edit['info[0][value]'],
  156. ]), 'Basic block created.');
  157. // Check that the block exists in the database.
  158. $blocks = \Drupal::entityTypeManager()
  159. ->getStorage('block_content')
  160. ->loadByProperties(['info' => $edit['info[0][value]']]);
  161. $block = reset($blocks);
  162. $this->assertNotEmpty($block, 'Default Custom Block found in database.');
  163. }
  164. /**
  165. * Verifies that a transaction rolls back the failed creation.
  166. */
  167. public function testFailedBlockCreation() {
  168. // Create a block.
  169. try {
  170. $this->createBlockContent('fail_creation');
  171. $this->fail('Expected exception has not been thrown.');
  172. }
  173. catch (\Exception $e) {
  174. // Expected exception; just continue testing.
  175. }
  176. $connection = Database::getConnection();
  177. if ($connection->supportsTransactions()) {
  178. // Check that the block does not exist in the database.
  179. $id = $connection->select('block_content_field_data', 'b')
  180. ->fields('b', ['id'])
  181. ->condition('info', 'fail_creation')
  182. ->execute()
  183. ->fetchField();
  184. $this->assertFalse($id, 'Transactions supported, and block not found in database.');
  185. }
  186. else {
  187. // Check that the block exists in the database.
  188. $id = $connection->select('block_content_field_data', 'b')
  189. ->fields('b', ['id'])
  190. ->condition('info', 'fail_creation')
  191. ->execute()
  192. ->fetchField();
  193. $this->assertTrue($id, 'Transactions not supported, and block found in database.');
  194. // Check that the failed rollback was logged.
  195. $records = $connection->query("SELECT wid FROM {watchdog} WHERE message LIKE 'Explicit rollback failed%'")->fetchAll();
  196. $this->assertTrue(count($records) > 0, 'Transactions not supported, and rollback error logged to watchdog.');
  197. }
  198. }
  199. /**
  200. * Test deleting a block.
  201. */
  202. public function testBlockDelete() {
  203. // Create a block.
  204. $edit = [];
  205. $edit['info[0][value]'] = $this->randomMachineName(8);
  206. $body = $this->randomMachineName(16);
  207. $edit['body[0][value]'] = $body;
  208. $this->drupalPostForm('block/add/basic', $edit, t('Save'));
  209. // Place the block.
  210. $instance = [
  211. 'id' => mb_strtolower($edit['info[0][value]']),
  212. 'settings[label]' => $edit['info[0][value]'],
  213. 'region' => 'sidebar_first',
  214. ];
  215. $block = BlockContent::load(1);
  216. $url = 'admin/structure/block/add/block_content:' . $block->uuid() . '/' . $this->config('system.theme')->get('default');
  217. $this->drupalPostForm($url, $instance, t('Save block'));
  218. $block = BlockContent::load(1);
  219. // Test getInstances method.
  220. $this->assertCount(1, $block->getInstances());
  221. // Navigate to home page.
  222. $this->drupalGet('');
  223. $this->assertText($body);
  224. // Delete the block.
  225. $this->drupalGet('block/1/delete');
  226. $this->assertText(\Drupal::translation()->formatPlural(1, 'This will also remove 1 placed block instance.', 'This will also remove @count placed block instance.'));
  227. $this->drupalPostForm(NULL, [], 'Delete');
  228. $this->assertRaw(t('The custom block %name has been deleted.', ['%name' => $edit['info[0][value]']]));
  229. // Create another block and force the plugin cache to flush.
  230. $edit2 = [];
  231. $edit2['info[0][value]'] = $this->randomMachineName(8);
  232. $body2 = $this->randomMachineName(16);
  233. $edit2['body[0][value]'] = $body2;
  234. $this->drupalPostForm('block/add/basic', $edit2, t('Save'));
  235. $this->assertNoRaw('Error message');
  236. // Create another block with no instances, and test we don't get a
  237. // confirmation message about deleting instances.
  238. $edit3 = [];
  239. $edit3['info[0][value]'] = $this->randomMachineName(8);
  240. $body = $this->randomMachineName(16);
  241. $edit3['body[0][value]'] = $body;
  242. $this->drupalPostForm('block/add/basic', $edit3, t('Save'));
  243. // Show the delete confirm form.
  244. $this->drupalGet('block/3/delete');
  245. $this->assertNoText('This will also remove');
  246. }
  247. /**
  248. * Test that placed content blocks create a dependency in the block placement.
  249. */
  250. public function testConfigDependencies() {
  251. $block = $this->createBlockContent();
  252. // Place the block.
  253. $block_placement_id = mb_strtolower($block->label());
  254. $instance = [
  255. 'id' => $block_placement_id,
  256. 'settings[label]' => $block->label(),
  257. 'region' => 'sidebar_first',
  258. ];
  259. $block = BlockContent::load(1);
  260. $url = 'admin/structure/block/add/block_content:' . $block->uuid() . '/' . $this->config('system.theme')->get('default');
  261. $this->drupalPostForm($url, $instance, t('Save block'));
  262. $dependencies = \Drupal::service('config.manager')->findConfigEntityDependentsAsEntities('content', [$block->getConfigDependencyName()]);
  263. $block_placement = reset($dependencies);
  264. $this->assertEqual($block_placement_id, $block_placement->id(), "The block placement config entity has a dependency on the block content entity.");
  265. }
  266. }