Form API multiplie file upload validation error 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 &amp;$form, FormStateInterface $form_state) {

  $validators = array(
    'file_validate_extensions' =&gt; array('pdf doc docx xls xlsx txt jpg jpeg png gif'),
    'file_validate_size' =&gt; 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 =&gt; $document) {
      if ($document === FALSE) {
        $error = true;
      }
    }

    if ($error === true) {
      $form_state-&gt;setErrorByName('documents_upload', 'Error: could not upload file.');
    }
  }
}


Any idea?
This happened to me today. After some research it's appear that Drupal8 have a bug with empty file form element when this one is multiple.

The file_save_upload function expects an array looks like this when element is empty :

 ['form_field_name' =&gt; NULL]


But actually for an empty multiple file form element the array is:

 ['form_field_name' =&gt; [0 =&gt; NULL]]


So the condition check for an empty value and fail. The code continue until it try to use getError() on a null value.

Here is a function to check if a file were uploaded or not. You can use it in the validateForm callback of your form class or in a hook.

function isFileUploaded($form_field_name) {
  $all_files = \Drupal::request()-&gt;files-&gt;get('files', array());

  return isset($all_files[$form_field_name]) &amp;&amp;
    !empty($all_files[$form_field_name]) &amp;&amp;
    NULL !== reset($all_files[$form_field_name]);
}


It's not very pretty but it'll work until they fix that bug.