If I use the following code to create a form, then when I select a file of a file extension not specified, I get two automated errors the same, about the wrong file type.

Example error (which occurs twice)

The specified file test.vcf could not be uploaded.
Only files with the following extensions are allowed: pdf jpg jpeg png gif.
A scanned document must be uploaded.

class ContributeForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'amazing_forms_contribute_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['document_scan'] = array
    (
      '#type' => 'managed_file',
      '#title' => t('Document (Scanned Copy)'),
      '#description' => t('Upload a file. Allowed extensions: pdf, jpg, jpeg, png, gif'),
      //'#required' => TRUE,
      '#upload_validators'  => array
      (
        'file_validate_extensions' => array('pdf jpg jpeg png gif'),
        'file_validate_size' => array(25600000),
      ),
      '#upload_location' => 'public://myfile/'
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit')
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if ($this->getFilename($form_state, 'passport_scan') === NULL)
    {
      $form_state->setErrorByName
      (
        'document_scan',
        $this->t
        (
          "A scanned document must be uploaded.",
          $form_state->getValue('document_scan')
        )
      );
    }
  }

  // $formFieldID = 'document_scan' etc.
  // This is my own member function.
  private function getFilename($form_state, $form_field_id)
  {
    if ($form_state->hasFileElement())
    {
      $file_array = $form_state->getValue($form_field_id);
      if (is_array($file_array))
      {
        if (isset($file_array[0]))
        {
          $file_id = $file_array[0];
          $file = \Drupal\file\Entity\File::load($file_id);
          if ($file !== NULL)
          {
            $filename = $file->getFilename();
            return $filename;
          }
        }
      }
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Display result.
    foreach ($form_state->getValues() as $key => $value) {
      if (is_string($key) && is_string($value))
      {
        drupal_set_message($key . ': ' . $value);
      }
    }
  }
}
?>

Comments

CatsFromStonehenge created an issue. See original summary.

cilefen’s picture

Status: Active » Closed (duplicate)
Related issues: +#2346893: Duplicate AJAX wrapper around a file field

I am pretty sure this is a duplicate.