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.
14 class FormTestFormStateValuesCleanForm extends FormBase {
19 public function getFormId() {
20 return 'form_test_form_state_clean_values_form';
26 public function buildForm(array $form, FormStateInterface $form_state) {
27 // Build an example form containing multiple submit and button elements; not
28 // only on the top-level.
29 $form = ['#tree' => TRUE];
30 $form['foo'] = ['#type' => 'submit', '#value' => t('Submit')];
31 $form['bar'] = ['#type' => 'submit', '#value' => t('Submit')];
32 $form['beer'] = ['#type' => 'value', '#value' => 1000];
33 $form['baz']['foo'] = ['#type' => 'button', '#value' => t('Submit')];
34 $form['baz']['baz'] = ['#type' => 'submit', '#value' => t('Submit')];
35 $form['baz']['beer'] = ['#type' => 'value', '#value' => 2000];
37 // Add an arbitrary element and manually set it to be cleaned.
38 // Using $form_state->addCleanValueKey('wine'); didn't work here.
39 $class = get_class($this);
43 '#process' => [[$class, 'cleanValue']],
50 * Helper function to clean a value on an element.
52 public static function cleanValue(&$element, FormStateInterface $form_state, &$complete_form) {
53 $form_state->addCleanValueKey('wine');
59 public function submitForm(array &$form, FormStateInterface $form_state) {
60 $form_state->cleanValues();
61 // This won't have a proper JSON header, but Drupal doesn't check for that
62 // anyway so this is fine until it's replaced with a JsonResponse.
63 print Json::encode($form_state->getValues());