Skip to content

Make the file required and prevent submitForm to be called in case file_save_upload does not validate extensions #20

@Nicolas-Bouteille

Description

@Nicolas-Bouteille

It seems attribute "#required" on a 'file' FormElement leads to a bug that displays a missing file error no matter what...
However, we have our convenient custom validator for that '#element_validate' => ['::validateFileupload'],
The first thing file_save_upload does, it checks there is actually a file. If none, it returns NULL. In case of error though, it returns FALSE.
So we can make a first check and add a specific error message for missing file:

$file = file_save_upload('csvimport', $validators, FALSE, 0, FileSystemInterface::EXISTS_REPLACE);
if ($file === NULL) {
 $form_state->setErrorByName('csvimport', t("Missing file"));
}
elseif ($file) { // != FALSE
}
else {
  // The line below prevents the submitForm function to be called. The errors added by file_save_upload will be displayed
  $form_state->setErrorByName('csvimport', '');
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions