diff --git a/core/modules/block/src/BlockForm.php b/core/modules/block/src/BlockForm.php index 50e4d38..e32ff1d 100644 --- a/core/modules/block/src/BlockForm.php +++ b/core/modules/block/src/BlockForm.php @@ -288,6 +288,12 @@ public function validateForm(array &$form, FormStateInterface $form_state) { $settings = (new FormState())->setValues($form_state->getValue('settings')); // Call the plugin validate handler. $this->entity->getPlugin()->validateConfigurationForm($form, $settings); + // Check if the form has errors and copy them into the $form_state. + if (FormState::hasAnyErrors()) { + foreach ($settings->getErrors() as $name => $error) { + $form_state->setError($form['settings'][$name], $error); + } + } // Update the original form values. $form_state->setValue('settings', $settings->getValues()); $this->validateVisibility($form, $form_state); diff --git a/core/modules/block/src/Tests/BlockUiTest.php b/core/modules/block/src/Tests/BlockUiTest.php index 6b55667..301f035 100644 --- a/core/modules/block/src/Tests/BlockUiTest.php +++ b/core/modules/block/src/Tests/BlockUiTest.php @@ -293,4 +293,22 @@ public function testBlockPlacementIndicator() { $this->assertUrl('admin/structure/block/list/classy'); } + /** + * Tests the block settings validations. + */ + public function testBlockValidateErrors() { + $url = 'admin/structure/block/add/test_settings_validation/classy'; + $this->drupalGet($url); + $edit = [ + 'settings[only_numbers]' => 'abc', + ]; + $this->drupalPostForm($url, $edit, 'Save block'); + $arguments = [ + ':message' => 'Only numbers are allowed', + ]; + $pattern = '//div[contains(@class,"messages messages--error")]/div[contains(text()[2],:message)]'; + $elements = $this->xpath($pattern, $arguments); + $this->assertTrue(!empty($elements), 'The error message appear in the form correctly.'); + } + } diff --git a/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestSettingsValidationBlock.php b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestSettingsValidationBlock.php new file mode 100644 index 0000000..a7fb2ba --- /dev/null +++ b/core/modules/block/tests/modules/block_test/src/Plugin/Block/TestSettingsValidationBlock.php @@ -0,0 +1,58 @@ + 'textfield', + '#title' => $this->t('Only numbers'), + ]; + + return $form; + } + + /** + * {@inheritdoc} + */ + public function blockSubmit($form, FormStateInterface $form_state) { + $this->configuration['only_numbers'] = $form_state->getValue('only_numbers'); + } + + public function blockValidate($form, FormStateInterface $form_state) { + $value = $form_state->getValue('only_numbers'); + + if (!is_numeric($value)) { + $form_state->setErrorByName('only_numbers', t('Only numbers are allowed')); + } + } + + /** + * {@inheritdoc} + */ + public function build() { + return array( + '#children' => $this->configuration['only_numbers'], + ); + } +}