I have a simple form with a multiple file upload field. I am trying to validate the documents against extensions and file size. The validation seems to work, but now if I don't select any file (field is not required), the validation fails and I get an error:
Fatal error: Call to a member function getError() on a non-object in /home/www/test/core/modules/file/file.module on line 726
Here is my validation function:
public function validateForm(array &$form, FormStateInterface $form_state) {
$validators = array(
'file_validate_extensions' => array('pdf doc docx xls xlsx txt jpg jpeg png gif'),
'file_validate_size' => array(7 * 1024 * 1024), // 7MB file size limit
);
/** @var File[] $documents */
$documents = file_save_upload('documents_upload', $validators, 'public://');
$error = false;
if(null !== $documents) {
foreach($documents as $i => $document) {
if ($document === FALSE) {
$error = true;
}
}
if ($error === true) {
$form_state->setErrorByName('documents_upload', 'Error: could not upload file.');
}
}
}
Any idea?