function ComponentAsFormElementTest::testElementValidateCallback
Tests that #element_validate works as expected.
File
-
core/
tests/ Drupal/ KernelTests/ Components/ ComponentAsFormElementTest.php, line 249
Class
- ComponentAsFormElementTest
- Tests the correct rendering of components in form.
Namespace
Drupal\KernelTests\ComponentsCode
public function testElementValidateCallback() : void {
/** @var \Drupal\Core\Form\FormBuilderInterface $form_builder */
$form_builder = \Drupal::service('form_builder');
// Build the form.
$form_builder->getForm($this);
// Simulate form submission with a value that should pass validation.
$form_state = new FormState();
$form_state->setValues([
'sdc_input_with_required' => 'test_data_required_value',
'sdc_input_with_validation' => 'test_data_valid_value',
]);
$form_builder->submitForm($this, $form_state);
// There should be no errors for valid value.
$this->assertFalse($form_state->hasAnyErrors(), "No errors should be set for valid value.");
// Simulate form submission with a value that should fail validation because
// an invalid value is provided.
$form_state = new FormState();
$form_state->setValues([
'sdc_input_with_required' => 'test_data_required_value',
'sdc_input_with_validation' => 'invalid_value',
]);
// You may need to adjust your customValidator to actually set
// an error for this value.
$form_builder->submitForm($this, $form_state);
// There should be an error for invalid value.
$this->assertTrue($form_state->hasAnyErrors(), "An error should be set for invalid value.");
$this->assertArrayHasKey('sdc_input_with_validation', $form_state->getErrors(), "An error should be set for invalid value on sdc_input_with_validation.");
// Simulate form submission with a value that should fail
// validation because an invalid value is provided.
$form_state = new FormState();
$form_state->setValues([
'sdc_input_with_validation' => 'test_data_valid_value',
]);
// You may need to adjust your customValidator
// to actually set an error for this value.
$form_builder->submitForm($this, $form_state);
// There should be an error for invalid value.
$this->assertTrue($form_state->hasAnyErrors(), "An error should be set when required value is not provided.");
$this->assertArrayHasKey('sdc_input_with_required', $form_state->getErrors(), "An error should be set for required field sdc_input_with_required.");
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.