View source
<?php
namespace Drupal\form_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class FormTestProgrammaticForm extends FormBase {
public function getFormId() {
return 'form_test_programmatic_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['textfield'] = array(
'#title' => 'Textfield',
'#type' => 'textfield',
);
$form['checkboxes'] = array(
'#title' => t('Checkboxes'),
'#type' => 'checkboxes',
'#options' => array(
1 => 'First checkbox',
2 => 'Second checkbox',
),
'#default_value' => array(
1,
2,
),
);
$form['field_to_validate'] = array(
'#type' => 'radios',
'#title' => 'Field to validate (in the case of limited validation)',
'#description' => 'If the form is submitted by clicking the "Submit with limited validation" button, then validation can be limited based on the value of this radio button.',
'#options' => array(
'all' => 'Validate all fields',
'textfield' => 'Validate the "Textfield" field',
'field_to_validate' => 'Validate the "Field to validate" field',
),
'#default_value' => 'all',
);
$form['field_restricted'] = array(
'#type' => 'textfield',
'#title' => 'Textfield (no access)',
'#access' => FALSE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
$form['submit_limit_validation'] = array(
'#type' => 'submit',
'#value' => 'Submit with limited validation',
'#submit' => array(
'::submitForm',
),
);
$user_input = $form_state
->getUserInput();
if (!empty($user_input['field_to_validate']) && $user_input['field_to_validate'] != 'all') {
$form['submit_limit_validation']['#limit_validation_errors'] = array(
array(
$user_input['field_to_validate'],
),
);
}
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
if ($form_state
->isValueEmpty('textfield')) {
$form_state
->setErrorByName('textfield', t('Textfield is required.'));
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_state
->set('programmatic_form_submit', $form_state
->getValues());
}
}