View source
<?php
namespace Drupal\KernelTests\Core\Form;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\KernelTests\KernelTestBase;
class TriggeringElementProgrammedTest extends KernelTestBase implements FormInterface {
public function getFormId() {
return 'triggering_element_programmed_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['one'] = [
'#type' => 'textfield',
'#title' => 'One',
'#required' => TRUE,
];
$form['two'] = [
'#type' => 'textfield',
'#title' => 'Two',
'#required' => TRUE,
];
$form['actions'] = [
'#type' => 'actions',
];
$user_input = $form_state
->getUserInput();
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => 'Save',
'#limit_validation_errors' => [
[
$user_input['section'],
],
],
'#submit' => [
[
$this,
'submitForm',
],
],
];
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
$this
->assertEquals($form['actions']['submit']['#array_parents'], $form_state
->getTriggeringElement()['#array_parents']);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
}
public function testLimitValidationErrors() {
$form_state = new FormState();
$form_state
->setValue('section', 'one');
$form_builder = $this->container
->get('form_builder');
$form_builder
->submitForm($this, $form_state);
$errors = $form_state
->getErrors();
$this
->assertTrue(isset($errors['one']), "Section 'one' was validated.");
$this
->assertFalse(isset($errors['two']), "Section 'two' was not validated.");
$this
->assertTrue($form_state
->hasValue('one'), "Values for section 'one' found.");
$this
->assertFalse($form_state
->hasValue('two'), "Values for section 'two' not found.");
}
}