I created a very simple module 'testform'. In this module, I generate a form and a block. (via the drush console)
The form contains a textfield ("housename") and a submit button.
In the form Class, I add a condition in the validate handler for display an error when the user submit the form without any data in the textfield.
The form from the form page (no problem)
- I load the form page (url path found in the testform.routing.yml)
- I click to the submit button without enter any data in the housename textfield
- The next page load, the empty housename field is red and there is an error message "the housename field is empty" => By this way, all is ok
The form from the block (there is the problem)
- I load a page where is displayed the form block
- In the block, I click to the sumbit button without enter any data in the textfield
- The next page load, the empty housename field is red and there isn't any error message
- If I reload the page, the setError message appears
I don't understand why when the form is displayed in a block, the error message doesn't work properly.
This is the code I am using.
The modules/custom/testform/src/Form/DefaultForm.php file
<?php
namespace Drupal\testform\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Class DefaultForm.
*
* @package Drupal\testform\Form
*/
class DefaultForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'default_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['housename'] = [
'#type' => 'textfield',
'#title' => $this->t('housename'),
'#maxlength' => 64,
'#size' => 64,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => t('Submit'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$housename = $form_state->getValue('housename');
if(empty($housename)){
$form_state->setErrorByName("housename","The housename field is empty");
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Display result.
ksm("Work...");
}
}
The modules/custom/testform/src/Plugin/Block/DefaultBlock.php file
<?php
namespace Drupal\testform\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a 'DefaultBlock' block.
*
* @Block(
* id = "default_block",
* admin_label = @Translation("Default block"),
* )
*/
class DefaultBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
return \Drupal::formBuilder()->getForm('Drupal\testform\Form\DefaultForm');
}
}