- 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.