d5e0fd965872d285f729b7ff9c294402a5109f54
[yaffs-website] / web / core / modules / system / tests / modules / form_test / src / Form / FormTestFormStateValuesCleanForm.php
1 <?php
2
3 namespace Drupal\form_test\Form;
4
5 use Drupal\Component\Serialization\Json;
6 use Drupal\Core\Form\FormBase;
7 use Drupal\Core\Form\FormStateInterface;
8
9 /**
10  * Form builder for \Drupal\Core\Form\FormState::cleanValues() test.
11  */
12 class FormTestFormStateValuesCleanForm extends FormBase {
13
14   /**
15    * {@inheritdoc}
16    */
17   public function getFormId() {
18     return 'form_test_form_state_clean_values_form';
19   }
20
21   /**
22    * {@inheritdoc}
23    */
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];
34
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);
38     $form['wine'] = [
39       '#type' => 'value',
40       '#value' => 3000,
41       '#process' => [[$class, 'cleanValue']],
42     ];
43
44     return $form;
45   }
46
47   /**
48    * Helper function to clean a value on an element.
49    */
50   public static function cleanValue(&$element, FormStateInterface $form_state, &$complete_form) {
51     $form_state->addCleanValueKey('wine');
52   }
53
54   /**
55    * {@inheritdoc}
56    */
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());
62     exit;
63   }
64
65 }