Create Media / Image-Bundle programmatically (Drupal)

  • 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

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Suche

Neueste Kommentare

  • 1 month 1 week ago
    Install APCu (PHP 8.1, Plesk)

    Problem:

  • 2 months 1 week ago
    Linux mv: das Verschieben von 'new' nach 'old' ist nicht möglich: Das Verzeichnis ist nicht leer

    Hilft "cp -avf old new && rm -rvf old" nicht?

  • 7 months 2 weeks ago
    [preflight] The following restricted PHP modes have non-empty values: {open_basedir}. This configuration is incompatible with drush.

    Same with Drush 13 + PHP 8.3

  • 7 months 2 weeks ago
    Acronis CyberProtect Agent For Linux (Strato Root Server)

    Initializing...

    Error : Failed to install the required package 'RPM' by using APT. Please install it manually. 

    Exit


    Solution:

  • 7 months 2 weeks ago
    Acronis CyberProtect Agent For Linux (Strato Root Server)

    So habe es installiert und dann mit Hilfe von Key/Code (über Website von Acronis Cyber Protect) aktiviert:

  • 7 months 2 weeks ago
    No route found for the specified format html. Supported formats: csv, json. (Drupal Routing)

    I have a view with a path like /my-content-export to export entivies as JSON or CSV.

  • 7 months 2 weeks ago
    InvalidArgumentException: The controller for URI "/admin/flush" is not callable.

    admin_toolbar 3.5.2 is the reason. Patch coming ...

  • 6 months 1 week ago
    PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock

    Drupal 10.4:

  • 8 months 2 weeks ago
    Server install & config : Debian 12 + Plesk + Apache + nginx + MariaDB + Solr

    Tools & Settings >> Security Policy :

     Allow only secure FTPS connections 

  • 10 months ago
    MariaDB Server Performance Optimieren

     

    /usr/sbin/mariadbd --help --verbose | grep "query.*size"