51353f6381b16fa9d7692af468f7d8a79cebb0fd
[yaffs-website] / web / core / modules / file / tests / file_module_test / src / Form / FileModuleTestForm.php
1 <?php
2
3 namespace Drupal\file_module_test\Form;
4
5 use Drupal\Core\Form\FormBase;
6 use Drupal\Core\Form\FormStateInterface;
7
8 /**
9  * Form controller for file_module_test module.
10  *
11  * @internal
12  */
13 class FileModuleTestForm extends FormBase {
14
15   /**
16    * {@inheritdoc}
17    */
18   public function getFormId() {
19     return 'file_module_test_form';
20   }
21
22   /**
23    * {@inheritdoc}
24    *
25    * @param array $form
26    *   An associative array containing the structure of the form.
27    * @param \Drupal\Core\Form\FormStateInterface $form_state
28    *   The current state of the form.
29    * @param bool $tree
30    *   (optional) If the form should use #tree. Defaults to TRUE.
31    * @param bool $extended
32    *   (optional) If the form should use #extended. Defaults to TRUE.
33    * @param bool $multiple
34    *   (optional) If the form should use #multiple. Defaults to FALSE.
35    * @param array $default_fids
36    *   (optional) Any default file IDs to use.
37    */
38   public function buildForm(array $form, FormStateInterface $form_state, $tree = TRUE, $extended = TRUE, $multiple = FALSE, $default_fids = NULL) {
39     $form['#tree'] = (bool) $tree;
40
41     $form['nested']['file'] = [
42       '#type' => 'managed_file',
43       '#title' => $this->t('Managed <em>@type</em>', ['@type' => 'file & butter']),
44       '#upload_location' => 'public://test',
45       '#progress_message' => $this->t('Please wait...'),
46       '#extended' => (bool) $extended,
47       '#size' => 13,
48       '#multiple' => (bool) $multiple,
49     ];
50     if ($default_fids) {
51       $default_fids = explode(',', $default_fids);
52       $form['nested']['file']['#default_value'] = $extended ? ['fids' => $default_fids] : $default_fids;
53     }
54
55     $form['textfield'] = [
56       '#type' => 'textfield',
57       '#title' => $this->t('Type a value and ensure it stays'),
58     ];
59
60     $form['submit'] = [
61       '#type' => 'submit',
62       '#value' => $this->t('Save'),
63     ];
64
65     return $form;
66   }
67
68   /**
69    * {@inheritdoc}
70    */
71   public function submitForm(array &$form, FormStateInterface $form_state) {
72     if ($form['#tree']) {
73       $uploads = $form_state->getValue(['nested', 'file']);
74     }
75     else {
76       $uploads = $form_state->getValue('file');
77     }
78
79     if ($form['nested']['file']['#extended']) {
80       $uploads = $uploads['fids'];
81     }
82
83     $fids = [];
84     foreach ($uploads as $fid) {
85       $fids[] = $fid;
86     }
87
88     drupal_set_message($this->t('The file ids are %fids.', ['%fids' => implode(',', $fids)]));
89   }
90
91 }