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