summaryrefslogtreecommitdiffstats
path: root/core/modules/file/tests/file_module_test/src/Form/FileModuleTestForm.php
blob: 78b6e7d05d41b80a2143db711f2f87491a07c998 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php

namespace Drupal\file_module_test\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Form controller for file_module_test module.
 *
 * @internal
 */
class FileModuleTestForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'file_module_test_form';
  }

  /**
   * {@inheritdoc}
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param bool $tree
   *   (optional) If the form should use #tree. Defaults to TRUE.
   * @param bool $extended
   *   (optional) If the form should use #extended. Defaults to TRUE.
   * @param bool $multiple
   *   (optional) If the form should use #multiple. Defaults to FALSE.
   * @param array $default_fids
   *   (optional) Any default file IDs to use.
   */
  public function buildForm(array $form, FormStateInterface $form_state, $tree = TRUE, $extended = TRUE, $multiple = FALSE, $default_fids = NULL) {
    $form['#tree'] = (bool) $tree;

    $form['nested']['file'] = [
      '#type' => 'managed_file',
      '#title' => $this->t('Managed <em>@type</em>', ['@type' => 'file & butter']),
      '#upload_location' => 'public://test',
      '#progress_message' => $this->t('Please wait...'),
      '#extended' => (bool) $extended,
      '#size' => 13,
      '#multiple' => (bool) $multiple,
    ];
    if ($default_fids) {
      $default_fids = explode(',', $default_fids);
      $form['nested']['file']['#default_value'] = $extended ? ['fids' => $default_fids] : $default_fids;
    }

    $form['textfield'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Type a value and ensure it stays'),
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($form['#tree']) {
      $uploads = $form_state->getValue(['nested', 'file']);
    }
    else {
      $uploads = $form_state->getValue('file');
    }

    if ($form['nested']['file']['#extended']) {
      $uploads = $uploads['fids'];
    }

    $fids = [];
    foreach ($uploads as $fid) {
      $fids[] = $fid;
    }

    \Drupal::messenger()->addStatus($this->t('The file ids are %fids.', ['%fids' => implode(',', $fids)]));
  }

}