- Step 1: Create a custom module
- Step 2: Controller & routing
Drupal/modules/custom/my_custom_module/src/Controller/MyCustomController2CreateMedia.php :
<?php
namespace Drupal\my_custom_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\file\Entity\File;
use Drupal\media\Entity\Media;
use Drupal\Core\File\FileSystemInterface;
/**
* Class MyCustomController2CreateMedia.
*/
class MyCustomController2CreateMedia extends ControllerBase
{
public function main()
{
$filepath = "/path/to/my-image-123.jpg";
$filename = 'my-image-123.jpg';
$title = 'My Image 123';
$alt = "A black-white picture of the hill";
$copyright = 'Jane Doe';
$image_data = file_get_contents( $filepath );
$file_repository = \Drupal::service('file.repository');
$image = $file_repository->writeData($image_data, "public://".$filename, FileSystemInterface::EXISTS_REPLACE);
$image_media = Media::create([
'name' => $filename,
'bundle' => 'my_image_bundle',
'uid' => 1,
'langcode' => 'de',
'status' => 1,
'field_image' => [
'target_id' => $image->id(),
'alt' => $alt,
'title' => $title,
],
'field_copyright' => $copyright,
]);
$image_media->save();
}
}
my_custom_module.routing.yml (in modules/custom/my_custom_module):
my_custom_module.create_media:
path: '/my_custom_module/create_media'
defaults:
_controller: '\Drupal\my_custom_module\Controller\MyCustomController2CreateMedia::main'
_title: 'My custom module : create media'
requirements:
_permission: 'access content'
options:
no_cache: 'TRUE'
my_custom_module.info.yml (in modules/custom/my_custom_module):
name: 'My Custom Module'
type: module
description: 'Create media files dynamically'
core_version_requirement: ">=10"
Neuen Kommentar schreiben