View source
<?php
namespace Drupal\Tests\system\Kernel\Form;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Form\FormState;
use Drupal\KernelTests\KernelTestBase;
class ProgrammaticTest extends KernelTestBase {
protected static $modules = [
'form_test',
];
public function testSubmissionWorkflow() {
$current_batch = $batch =& batch_get();
$batch = [];
$this
->doSubmitForm([], FALSE);
$this
->doSubmitForm([
'textfield' => 'test 1',
], TRUE);
$this
->doSubmitForm([], FALSE);
$this
->doSubmitForm([
'textfield' => 'test 2',
], TRUE);
$this
->doSubmitForm([
'textfield' => 'dummy value',
'checkboxes' => [
1 => 1,
2 => 2,
],
], TRUE);
$this
->doSubmitForm([
'textfield' => 'dummy value',
'checkboxes' => [
1 => 1,
2 => NULL,
],
], TRUE);
$this
->doSubmitForm([
'textfield' => 'dummy value',
'checkboxes' => [
1 => NULL,
2 => 2,
],
], TRUE);
$this
->doSubmitForm([
'textfield' => 'dummy value',
'checkboxes' => [
1 => NULL,
2 => NULL,
],
], TRUE);
$this
->doSubmitForm([
'op' => 'Submit with limited validation',
'field_to_validate' => 'all',
], FALSE);
$this
->doSubmitForm([
'op' => 'Submit with limited validation',
'field_to_validate' => 'textfield',
], FALSE);
$this
->doSubmitForm([
'op' => 'Submit with limited validation',
'field_to_validate' => 'field_to_validate',
], TRUE);
$batch = $current_batch;
}
protected function doSubmitForm($values, $valid_input) {
$form_state = (new FormState())
->setValues($values);
\Drupal::formBuilder()
->submitForm('\\Drupal\\form_test\\Form\\FormTestProgrammaticForm', $form_state);
$errors = $form_state
->getErrors();
$valid_form = empty($errors);
$args = [
'%values' => print_r($values, TRUE),
'%errors' => $valid_form ? t('None') : implode(' ', $errors),
];
$this
->assertSame($valid_form, $valid_input, new FormattableMarkup('Input values: %values<br />Validation handler errors: %errors', $args));
if ($valid_input) {
$stored_values = $form_state
->get('programmatic_form_submit');
foreach ($values as $key => $value) {
$this
->assertEquals($value, $stored_values[$key], new FormattableMarkup('Submission handler correctly executed: %stored_key is %stored_value', [
'%stored_key' => $key,
'%stored_value' => print_r($value, TRUE),
]));
}
}
}
public function testProgrammaticAccessBypass() {
$form_state = (new FormState())
->setValues([
'textfield' => 'dummy value',
'field_restricted' => 'dummy value',
]);
\Drupal::formBuilder()
->submitForm('\\Drupal\\form_test\\Form\\FormTestProgrammaticForm', $form_state);
$values = $form_state
->get('programmatic_form_submit');
$this
->assertEquals('dummy value', $values['field_restricted'], 'The value for the restricted field is stored correctly.');
$form_state
->setProgrammedBypassAccessCheck(FALSE);
\Drupal::formBuilder()
->submitForm('\\Drupal\\form_test\\Form\\FormTestProgrammaticForm', $form_state);
$values = $form_state
->get('programmatic_form_submit');
$this
->assertNotSame('dummy value', $values['field_restricted'], 'The value for the restricted field is not stored.');
}
}