The Drop Times: Unmanaged Files in Drupal: Rendering an Unmanaged File in a Block (Part 3)

The Block Plugin Class


public function build(): array {
$uri = $this->handler->getRandomFile();

```
if (!$uri) {
return [
'#markup' => '<p>No unmanaged files found.</p>',
];
}

return [
'#theme' => 'image',
'#uri' => $uri,
'#alt' => $this->t('Random unmanaged file'),
'#cache' => [
'max-age' => 1,
],
];
```

}

Figure 4. The block’s build method.

Enable and Place the Block


public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
private FileHandler $handler,
private FileUrlGeneratorInterface $urlGen,
)
{
parent::__construct($configuration, $plugin_id, $plugin_definition);
}

Figure 2. The constructor with injected services.

The Factory Method

namespace Drupalunmanaged_filesPluginBlock;

use DrupalCoreBlockBlockBase;
use DrupalCoreFileFileUrlGeneratorInterface;
use Drupalunmanaged_filesServiceFileHandler;
use SymfonyComponentDependencyInjectionContainerInterface;
use DrupalCorePluginContainerFactoryPluginInterface;

final class UnmanagedFilesBlock extends BlockBase implements ContainerFactoryPluginInterface {

Figure 1. The block plugin definition.

The Constructor

The class extends BlockBase and implements ContainerFactoryPluginInterface, which lets us inject our file handler and URL generator services from Drupal’s service container.

In Part 4, we’ll explore how to render unmanaged files directly in Twig templates, giving developers a more flexible way to use the handler inside their theme layer.
public static function create(ContainerInterface $c, array $configuration, $plugin_id, $plugin_definition): self {

$handler = $c->get('unmanaged_files.handler');

```

$urlGen = $c->get('file_url_generator');

return new self(
$configuration,
$plugin_id,
$plugin_definition,
$handler,
$urlGen,
);
```

}

Figure 3. The factory method for dependency injection.

The Build Method

The build() method is what Drupal calls to render the block. It asks the file handler for a random unmanaged file. If a file is found, it returns a render array using the image theme. If no file is found, it returns a simple message. The max-age cache metadata is set to 1 second so that refreshing the page quickly rotates images.

Similar Posts