FormTestRedirectForm.php in Drupal 8
File
core/modules/system/tests/modules/form_test/src/Form/FormTestRedirectForm.php
View source
<?php
namespace Drupal\form_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
class FormTestRedirectForm extends FormBase {
public function getFormId() {
return 'form_test_redirect';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['redirection'] = [
'#type' => 'checkbox',
'#title' => t('Use redirection'),
];
$form['destination'] = [
'#type' => 'textfield',
'#title' => t('Redirect destination'),
'#states' => [
'visible' => [
':input[name="redirection"]' => [
'checked' => TRUE,
],
],
],
];
$form['submit'] = [
'#type' => 'submit',
'#value' => t('Submit'),
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
if (!$form_state
->isValueEmpty('redirection')) {
if (!$form_state
->isValueEmpty('destination')) {
$form_state
->setRedirectUrl(Url::fromUserInput('/' . $form_state
->getValue('destination')));
}
}
else {
$form_state
->disableRedirect();
}
}
}