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.
buildForm:
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; }
submitForm:
public function submitForm(array &$form, FormStateInterface $form_state) { $event_image = $form_state->getValue('event_image'); if ($event_image) { $file = File::load(reset($event_image)); $file->setPermanent(); drupal_set_message('Filename: ' . $file->getFilename()); } ksm($event_image); // Returns empty array?? }