3 namespace Drupal\form_test\Form;
5 use Drupal\Component\Serialization\Json;
6 use Drupal\Core\Form\FormBase;
7 use Drupal\Core\Form\FormStateInterface;
10 * Form builder for \Drupal\Core\Form\FormState::cleanValues() test.
12 class FormTestFormStateValuesCleanForm extends FormBase {
17 public function getFormId() {
18 return 'form_test_form_state_clean_values_form';
24 public function buildForm(array $form, FormStateInterface $form_state) {
25 // Build an example form containing multiple submit and button elements; not
26 // only on the top-level.
27 $form = ['#tree' => TRUE];
28 $form['foo'] = ['#type' => 'submit', '#value' => t('Submit')];
29 $form['bar'] = ['#type' => 'submit', '#value' => t('Submit')];
30 $form['beer'] = ['#type' => 'value', '#value' => 1000];
31 $form['baz']['foo'] = ['#type' => 'button', '#value' => t('Submit')];
32 $form['baz']['baz'] = ['#type' => 'submit', '#value' => t('Submit')];
33 $form['baz']['beer'] = ['#type' => 'value', '#value' => 2000];
35 // Add an arbitrary element and manually set it to be cleaned.
36 // Using $form_state->addCleanValueKey('wine'); didn't work here.
37 $class = get_class($this);
41 '#process' => [[$class, 'cleanValue']],
48 * Helper function to clean a value on an element.
50 public static function cleanValue(&$element, FormStateInterface $form_state, &$complete_form) {
51 $form_state->addCleanValueKey('wine');
57 public function submitForm(array &$form, FormStateInterface $form_state) {
58 $form_state->cleanValues();
59 // This won't have a proper JSON header, but Drupal doesn't check for that
60 // anyway so this is fine until it's replaced with a JsonResponse.
61 print Json::encode($form_state->getValues());