4

I am using managed file type to upload image in my custom form (Drupal-8). I am able to retrieve the given image while editing by using the below code

$form['image_field'] = array(
   '#type' => 'managed_file',
   '#title' => t('Image'),
   '#default_value' => array($fid),
); 

While i am trying to save once edit, i am getting the "The file used in the Image field may not be referenced." error.

enter image description here

Please let me know to over come this error and let me what this error trying to convey.

2

Check \Drupal\file\Element\ManagedFile for answer, it appears that your file is being saved as permanent, but there is no entry in file_usage table:

if ($file = File::load($fid)) {
      if ($file->isPermanent()) {
        $references = static::fileUsage()->listUsage($file);
        if (empty($references)) {
          // We expect the field name placeholder value to be wrapped in t()
          // here, so it won't be escaped again as it's already marked safe.
          $form_state->setError($element, t('The file used in the @name field may not be referenced.', ['@name' => $element['#title']]));
        }
      }
    }

If you want to store your files permanently, you need to make sure they've got usage entries, to do so, you can tweak you form submit handler a little bit, here's some quick example:

// get file fid wherever it is
$values = $form_state->getValues();
$fid = $values['my_file_field'];

// call file usage service and load file
$file_usage = \Drupal::service('file.usage');
$file = File::load($fid);

// set file status permanent
if(!$file->isPermanent()){
  $file->setPermanent();
}

// check file usage , if it's empty, add new entry
$usage = $file_usage->listUsage($file);
if(empty($usage)){
  // let's assume it's image
  $file_usage->add($file,'mymodule','image',$fid);
}
$file->save();

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.