- Issue created by @zawlinnoo
- Assigned to mayurgajar
- ð®ð³India mayurgajar
This is the code, I used to create a media and node programmatically
// Stored file
$image_url = {image url};
$image_content = file_get_contents($image_url);
$filename = basename($image_url);
$file_repository = \Drupal::service('file.repository');$image = $file_repository->writeData($image_content, "private://". $filename, FileSystemInterface::EXISTS_REPLACE);
// Create a media
$media_storage = \Drupal::entityTypeManager()->getStorage('media');
$media = $media_storage->create([
'bundle' => 'image',
'uid' => 1,
'status' => 1,
'field_media_image' => [
'target_id' => $image->id(),
'alt' => $text,
'title' => $text,
],
]);
$media->setName($text)->setPublished(TRUE)->save();// Create a node
$node = Node::create([
'type' => 'article',
'title' => 'new article',
'field_blog_image' => [
'target_id' => $media->id(),
'alt' => 'Hello world',
'title' => 'Goodbye world'
],
]);
$node->save();With this code, we are able to add media and node..
Next step, Create a view of article node and display title and media image - we are able to create a view with title and media image and it rendering correctPlease add any other scenarios if you are still facing any issue to create a media and its view.
For better understanding debug your code like, first check file is created or not.. then check media is created or not and last check node is successfully saved or not - Issue was unassigned.
- Status changed to Closed: works as designed
about 1 month ago 4:45am 12 January 2025 - ð³ð¿New Zealand quietone
It appears that a solution was provided in #6 so I am closing this Support Request.
The Drupal Core issue queue is not the ideal place for support requests. The 'support request' option is there for filing support issues for contributed modules and themes. There are several support options listed on our support page â (Community > Support at the top of Drupal.org) and there is Drupal Slack â . You may get better replies in one of those places.