Skip to content

Instantly share code, notes, and snippets.

@pixelmord
Forked from steffenr/file_media_entity.php
Last active October 12, 2022 13:32
Show Gist options
  • Save pixelmord/cb69d07f3d8b8620925f1678f1e6dc93 to your computer and use it in GitHub Desktop.
Save pixelmord/cb69d07f3d8b8620925f1678f1e6dc93 to your computer and use it in GitHub Desktop.
[Drupal 8] Create file/ media_entity programmatically
<?php
$filesystem = \Drupal::service('file_system');
// Create file entity.
$image = File::create();
$image->setFileUri($destination);
$image->setOwnerId(\Drupal::currentUser()->id());
$image->setMimeType('image/' . pathinfo($destination, PATHINFO_EXTENSION));
$image->setFileName($filesystem->basename($destination));
$image->setPermanent();
$image->save();
// Create media entity with saved file.
$image_media = Media::create([
'bundle' => 'image',
'uid' => \Drupal::currentUser()->id(),
'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
'status' => Media::PUBLISHED,
'field_image' => [
'target_id' => $image->id(),
'alt' => t('Placeholder image'),
'title' => t('Placeholder image'),
],
]);
$image_media->save();
<?php
/**
* @file
* Contains Drupal\mymodule\Plugin\Block\ImageRenderExampleBlock.
*/
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\file\Entity\File;
/**
* Provides a 'ImageRenderExampleBlock' block.
*
* @Block(
* id = "mymodule_imagerenderexampleblock",
* admin_label = @Translation("MyModule Image Render Example"),
* )
*/
class ImageRenderExampleBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
// Load file with file id 1.
$file = File::load(1);
if ($file) {
$variables = array(
'style_name' => 'thumbnail',
'uri' => $file->getFileUri(),
);
// The image.factory service will check if our image is valid.
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$variables['width'] = $image->getWidth();
$variables['height'] = $image->getHeight();
}
else {
$variables['width'] = $variables['height'] = NULL;
}
$logo_build = [
'#theme' => 'image_style',
'#width' => $variables['width'],
'#height' => $variables['height'],
'#style_name' => $variables['style_name'],
'#uri' => $variables['uri'],
];
// Add the file entity to the cache dependencies.
// This will clear our cache when this entity updates.
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($logo_build, $file);
// Return the render array as block content.
return [
'logo' => $logo_build,
];
} else {
// Image not found, return empty block.
return [];
}
}
}
<?php
/**
* @file
* Contains Drupal\mymodule\Plugin\Block\ImageRenderExampleBlockResponsive.
*/
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\file\Entity\File;
/**
* Provides a 'ImageRenderExampleBlockResponsive' block.
*
* @Block(
* id = "mymodule_imagerenderexampleblockresponsive",
* admin_label = @Translation("MyModule Image Render Example Responsive"),
* )
*/
class ImageRenderExampleBlockResponsive extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
// Load file with file id 1.
$file = File::load(1);
if ($file) {
$variables = array(
'responsive_image_style_id' => 'responsive_thumbnail',
'uri' => $file->getFileUri(),
);
// The image.factory service will check if our image is valid.
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$variables['width'] = $image->getWidth();
$variables['height'] = $image->getHeight();
}
else {
$variables['width'] = $variables['height'] = NULL;
}
$logo_build = [
'#theme' => 'responsive_image',
'#width' => $variables['width'],
'#height' => $variables['height'],
'#responsive_image_style_id' => $variables['responsive_image_style_id'],
'#uri' => $variables['uri'],
];
// Add the file entity to the cache dependencies.
// This will clear our cache when this entity updates.
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($logo_build, $file);
// Return the render array as block content.
return [
'logo' => $logo_build,
];
} else {
// Image not found, return empty block.
return [];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment