I'm attempting to create a module with a custom form that allows users to upload a file using a managed_file field. The name of my module is foundation_settings and the file structure is:
foundation_settings
-foundation_settings.info.yml
-foundation_settings.module
-src
-Form
-FoundationForm.php
Inside FoundationForm.php I'm building the form with the following code:
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('foundation.settings');
$form['icons'] = [
'#type' => 'details',
'#title' => t('Front Page Icons'),
'#open' => FALSE,
'icon1' => [
'#type' => 'fieldset',
'#title' => t('First Icon'),
'icon1_file' => [
'#type' => 'managed_file',
'#name' => 'icon1',
'#title' => t('First Icon Image'),
'#default_value' => $config->get('icon1_file'),
'#upload_location' => 'public://',
],
],
];
}
However I'm not sure how to handle the managed_file when the form is being submitted. In my submitForm function I have
public function submitForm(array&$form, FormStateInterface $form_state) {
$imageid = $form_state->getValue('icon1_file');
$file = file_load($imageid[0]);
if (gettype($file) == 'object') {
$file->status = FILE_STATUS_PERMANENT;
}
$this->config('foundation.settings')
->set('icon1_file', $form_state->getValue('icon1_file'))
->save();
$file->save();
}
The upload and saving works okay but I keep receiving this error after submitting
The file used in the First Icon Image field may not be referenced.
How are you supposed to use managed_file field in custom form plugins?