3 namespace Drupal\file_test\Form;
5 use Drupal\Core\Form\FormInterface;
6 use Drupal\Core\Form\FormStateInterface;
9 * File test form class.
11 class FileTestForm implements FormInterface {
16 public function getFormId() {
17 return '_file_test_form';
23 public function buildForm(array $form, FormStateInterface $form_state) {
24 $form['file_test_upload'] = [
26 '#title' => t('Upload a file'),
28 $form['file_test_replace'] = [
30 '#title' => t('Replace existing image'),
32 FILE_EXISTS_RENAME => t('Appends number until name is unique'),
33 FILE_EXISTS_REPLACE => t('Replace the existing file'),
34 FILE_EXISTS_ERROR => t('Fail with an error'),
36 '#default_value' => FILE_EXISTS_RENAME,
38 $form['file_subdir'] = [
39 '#type' => 'textfield',
40 '#title' => t('Subdirectory for test file'),
41 '#default_value' => '',
44 $form['extensions'] = [
45 '#type' => 'textfield',
46 '#title' => t('Allowed extensions.'),
47 '#default_value' => '',
50 $form['allow_all_extensions'] = [
51 '#type' => 'checkbox',
52 '#title' => t('Allow all extensions?'),
53 '#default_value' => FALSE,
56 $form['is_image_file'] = [
57 '#type' => 'checkbox',
58 '#title' => t('Is this an image file?'),
59 '#default_value' => TRUE,
64 '#value' => t('Submit'),
72 public function validateForm(array &$form, FormStateInterface $form_state) {}
77 public function submitForm(array &$form, FormStateInterface $form_state) {
78 // Process the upload and perform validation. Note: we're using the
79 // form value for the $replace parameter.
80 if (!$form_state->isValueEmpty('file_subdir')) {
81 $destination = 'temporary://' . $form_state->getValue('file_subdir');
82 file_prepare_directory($destination, FILE_CREATE_DIRECTORY);
90 if ($form_state->getValue('is_image_file')) {
91 $validators['file_validate_is_image'] = [];
94 if ($form_state->getValue('allow_all_extensions')) {
95 $validators['file_validate_extensions'] = [];
97 elseif (!$form_state->isValueEmpty('extensions')) {
98 $validators['file_validate_extensions'] = [$form_state->getValue('extensions')];
101 // The test for drupal_move_uploaded_file() triggering a warning is
102 // unavoidable. We're interested in what happens afterwards in
103 // file_save_upload().
104 if (\Drupal::state()->get('file_test.disable_error_collection')) {
105 define('SIMPLETEST_COLLECT_ERRORS', FALSE);
108 $file = file_save_upload('file_test_upload', $validators, $destination, 0, $form_state->getValue('file_test_replace'));
110 $form_state->setValue('file_test_upload', $file);
111 \Drupal::messenger()->addStatus(t('File @filepath was uploaded.', ['@filepath' => $file->getFileUri()]));
112 \Drupal::messenger()->addStatus(t('File name is @filename.', ['@filename' => $file->getFilename()]));
113 \Drupal::messenger()->addStatus(t('File MIME type is @mimetype.', ['@mimetype' => $file->getMimeType()]));
114 \Drupal::messenger()->addStatus(t('You WIN!'));
116 elseif ($file === FALSE) {
117 \Drupal::messenger()->addError(t('Epic upload FAIL!'));