Jethi Mayank
Jethi Mayank

Reputation: 53

File::load in drupal8 custom module controller

i have created one custom module, in the controller file i used File::load static method. but when I'm run phpcs for check coding standards it will give an error as

File::load calls should be avoided in classes, use dependency injection instead

anyone can please tell how to create dependency injection for this.

Upvotes: 0

Views: 1208

Answers (1)

matperry
matperry

Reputation: 11

The be achieved by using Drupal\Core\Entity\EntityTypeManagerInterface.

use Drupal\Core\Entity\EntityTypeManagerInterface;

class MyForm extends FormBase {

 /**
  * The storage handler class for files.
  *
  * @var \Drupal\file\FileStorage
  */
 protected $fileStorage;

 /**
  * This is an example.
  *
  * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity
  *   The Entity type manager service.
  */
  public function __construct(EntityTypeManagerInterface $entity) {
    $this->fileStorage = $entity->getStorage('file');
  }
  ....
 }

From there you can update the File::load($fid) to $this->fileStorage->load($fid)

Upvotes: 1

Related Questions