0
votes

I am building a form and where te user can upload a file. Since I am using Drupal I am using the managed_file. The file is being uploaded but I cannot seem to get the filename out of the form... This is my code

Buildform:

        $form['formfile'] = array(
        '#type' => 'managed_file',
        '#name' => 'formfile',
        '#title' => t('File'),
        '#upload_validators' => $validators,
        '#upload_location' => 'public://trainingrequests/',
    );

Submit

drupal_set_message($form_state->getValue('formfile'));

I have literally tried everything.

1
From Form api Reference "...The form's validate and submit handlers receive a file object ID in $form_state['values'] that represents the ID of the new file in the {file_managed} table.". Now you have to load file from DB \Drupal::entityTypeManager() ->getStorage('file') ->load($file_id); - lamp5
And how do I get $file_id? - user7227057

1 Answers

3
votes

You first need to get the entity ID of the File entity, then load the entity:

$formfile = $form_state->getValue('formfile');
if ($formfile) {
  $oNewFile = File::load(reset($formfile));
  $oNewFile->setPermanent();
  drupal_set_message('Filename: ' . $oNewFile->getFilename());
}

You can browse the source code of the File entity in your file system: core/modules/file/src/Entity/File.php