Updated to Drupal 8.5. Core Media not yet in use.
[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  * @internal
13  */
14 class FormTestFormStateValuesCleanForm extends FormBase {
15
16   /**
17    * {@inheritdoc}
18    */
19   public function getFormId() {
20     return 'form_test_form_state_clean_values_form';
21   }
22
23   /**
24    * {@inheritdoc}
25    */
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];
36
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);
40     $form['wine'] = [
41       '#type' => 'value',
42       '#value' => 3000,
43       '#process' => [[$class, 'cleanValue']],
44     ];
45
46     return $form;
47   }
48
49   /**
50    * Helper function to clean a value on an element.
51    */
52   public static function cleanValue(&$element, FormStateInterface $form_state, &$complete_form) {
53     $form_state->addCleanValueKey('wine');
54   }
55
56   /**
57    * {@inheritdoc}
58    */
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());
64     exit;
65   }
66
67 }