3

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?

1
  • No code, no answer.
    – user21641
    Aug 29, 2015 at 19:04

1 Answer 1

1

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' => NULL]

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

 ['form_field_name' => [0 => 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()->files->get('files', array());

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.