In order to make a managed_file field permanent I did this in my module configuration form:
<?php namespace Drupalmy_moduleForm; use DrupalCoreFormConfigFormBase; use DrupalCoreFormFormStateInterface; /** * Class MymoduleSettings. */ class MymoduleSettings extends ConfigFormBase { /** * {@inheritdoc} */ public function getFormId() { return 'my_module_settings'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config('my_module.settings'); $form['my_module_title'] = [ '#type' => 'textfield', '#title' => $this->t('Title'), '#description' => $this->t("Enter the title"), '#maxlength' => 64, '#size' => 64, '#required' => TRUE, '#default_value' => $config->get('my_module_title'), ]; $form['mymodule_icon'] = [ '#type' => 'managed_file', '#title' => $this->t('Icon'), '#description' => $this->t("Upload the image file for the icon"), '#upload_location' => 'public://', '#upload_validators' => [ 'file_validate_extensions' => ['gif png jpg jpeg'], ], '#default_value' => $config->get('my_module_icon'), ]; return parent::buildForm($form, $form_state); } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { parent::submitForm($form, $form_state); $this->config('my_module.settings') ->set('my_module_title', $form_state->getValue('my_module_title')) ->set('my_module_icon', $form_state->getValue('my_module_icon')) ->save(); // First we just grab the file ID for the icon we uploaded, if any. $icon_field = $form_state->getValue('my_module_icon'); $file_id = empty($icon_field) ? FALSE : reset($icon_field); if (!empty($file_id)) { // Make this a permanent file so that cron doesn't delete it later. $file = File::load($file_id); $file->status = FILE_STATUS_PERMANENT; $file->save(); $file_usage = Drupal::service('file.usage'); $file_usage->add($file, 'my_module', 'file', $file_id); } } /** * {@inheritdoc} */ protected function getEditableConfigNames() { return [ 'my_module.settings', ]; } }
but I’m getting warning to use dependency injection principle in this case:
File::load calls should be avoided in classes, use dependency injection instead
and
Drupal calls should be avoided in classes, use dependency injection instead
I looked through Dependency Injection for a Form but still not sure that I really get it.
Can someone explain me what I need to do in this particular case so I can get a better view on this issue and figure it out?