In Drupal 8, I have a custom form that I built using the Form API in a custom module. I am trying to upload a file using managed_file field. For some reason I can't get it to give me the file ID no matter what code I try. The file does indeed get uploaded and saved, but only as a temporary file.

Please see below for the code I am using. The value of the form field is always NULL.


public function buildForm(array $form, FormStateInterface $form_state, $event = NULL) {
  $validators = array(
    'file_validate_extensions' => array('jpg jpeg png gif'),
  $form['event_image'] = array(
    '#type' => 'managed_file',
    '#name' => 'event_image',
    '#title' => t('Event Image'),
    '#upload_validators' => $validators,
    '#upload_location' => 'public://event-images/',

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Save'),

  return $form;


public function submitForm(array &$form, FormStateInterface $form_state) {
  $event_image = $form_state->getValue('event_image');
  if ($event_image) {
    $file = File::load(reset($event_image));
    drupal_set_message('Filename: ' . $file->getFilename());
  ksm($event_image); // Returns empty array??
  • Your code looks correct. There is nothing wrong with it that I can see, and this is an area I've worked with a fair bit. This may indicate a deeper problem in your system. Try checking your logs and seeing if anything strange is popping up when you submit your form. This may give you a clue where to work backwards from. – Jaypan Jul 12 '19 at 21:44
  • does the directory exist and is writable? do you see any errors in your logs? – sonfd Jul 12 '19 at 23:56
  • @Jaypan Thanks for looking. Nothing shows up in the logs. I have dblog enabled and it is empty. Nothing in apache/php/mysql logs either. I'm using a local MAMP server so I may try to upload to a "real" server and see if that makes a difference. – Micah Jul 13 '19 at 3:15
  • @sonfd Yes, actually the file gets uploaded successfullly to the directory that I specify and I can see it as a temp file at /admin/content/files. But it just says used in 0 places. – Micah Jul 13 '19 at 3:17
  • 1
    You need to call fille_usage_add() I think – Jaypan Jul 13 '19 at 3:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.