Dear Experts,

I have stuck with a problem in drupal 8. Actually I need to create node programmatically but content type contains two media fields, one field for Image and another for YouTube link so problem is, I don't know how to submit data for these fields programmatically.
Can you help me urgently please?!

Thanks

CommentFileSizeAuthor
Untitled-1.jpg145.63 KBmahpari
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

mahpari created an issue. See original summary.

marcoscano’s picture

Assigned: mahpari » Unassigned
Priority: Critical » Normal
Issue tags: -media bundle drupal8 node image field video field +D8Media

Support requests are not supposed to be prioritized, and try to use the already existing tags :)

If these fields are just entity_reference fields, you only need to pass the id of the target entities you want to refer to on each of them. It will be necessary then to have already created beforehand the media entities you want to refer to.

A good place to look for examples of this are the tests inside the module, for example this one:
http://cgit.drupalcode.org/media_entity/tree/tests/src/Kernel/TokensTest...

mahpari’s picture

Thank you Dear Marcos for your respond but I want to add media programmatically when node is created.

here is my code if you have time can you please have a look, it is very urgent as I am reaching to deadline.

$node = Node::create([
// The node entity bundle.
'type' => 'article',
'langcode' => 'en',
'created' => $created_date,
'changed' => $created_date,
// The user ID.
'uid' => 1,
'moderation_state' => 'published',
'title' => $title,
'field_article_section' => array('target_id'=>$section_target_id),
'field_author' => 111,
'field_article_main_image' => array('image' => [
'target_id' => $file->id()
],
'field_media_in_library'=> 1
),

'field_article_main_video' => array(
'field_media_video_embed_field' => $youtubeID,
'field_media_in_library'=> 1
),

'field_article_body_summary' => [
'summary' => substr(strip_tags($text), 0, 100),
'value' => $text,
'format' => 'rich_text'
]
]);

Thanks,
Mahpari

mahpari’s picture

$node = Node::create([
		  // The node entity bundle.
		  'type' => 'article',
		  'langcode' => 'en',
		  'created' => $created_date,
		  'changed' => $created_date,
		  // The user ID.
		  'uid' => 1,
		  'moderation_state' => 'published',
		  'title' => $title,
		  'field_article_section' => array('target_id'=>$section_target_id),
		  'field_author' => 111,
		  'field_article_main_image' => array('image' => [
			  'target_id' => $file->id()
			  ],
			  'field_media_in_library'=> 1
			),
			
		  'field_article_main_video' => array(
		  	  'field_media_video_embed_field' => $youtubeID,
			  'field_media_in_library'=> 1
			),	
		 
		  'field_article_body_summary' => [
			'summary' => substr(strip_tags($text), 0, 100),
			'value' => $text,
			'format' => 'rich_text'
		  ]
		]);
$node->save();
marcoscano’s picture

You need to create the media entities before creating the node.

Something like this should work (untested):

    // ...

    // Assuming the image is already uploaded to your server:
    $fid = '123'; // The fid of the image you are going to use.
    $image_media = Media::create([
      'bundle' => 'your_image_bundle_name_here',
      'uid' => '1',
      'langcode' => Language::LANGCODE_DEFAULT,
      'status' => Media::PUBLISHED,
      'your_image_field_name_here' => [
        'target_id' => $fid,
        'alt' => t('foo'),
        'title' => t('bar'),
      ],
    ]);
    $image_media->save();

    // Then do the same for the video media entity.
    // $video_media = ... ->save();

    $node = Node::create([
      // The node entity bundle.
      'type' => 'article',
      'langcode' => 'en',
      'created' => $created_date,
      'changed' => $created_date,
      // The user ID.
      'uid' => 1,
      'moderation_state' => 'published',
      'title' => $title,
      'field_article_section' => array('target_id'=>$section_target_id),
      'field_author' => 111,
      'field_article_main_image' => ['target_id' => $image_media->id()],
      'field_article_main_video' => array(
        // ... the same as before
      ),
      'field_article_body_summary' => [
        'summary' => substr(strip_tags($text), 0, 100),
        'value' => $text,
        'format' => 'rich_text'
      ]
    ]);
    $node->save();
mahpari’s picture

Thanks a lot, let me try it and I will come back to you with the result.

mahpari’s picture

Status: Active » Fixed

Thank you Marcos, your code works like a charm. you saved me!

Have a great time.

Regards,
Mahpari

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

killua99’s picture

Anything has changes since the last example code?

I'm trying create medias exactly how are you showing here, the thing in my case are. I can see a thumbnail image on the media overview, the node. But when I edit the media the image field is empty. The file entity is showing the file is been using 2 times, and one of them is on the media. Weird case is the media seems to lose the reference. How could double check / fix this situation ?

Mojiferous’s picture

Killua99 I had the same issue, and it was because of the langcode, if I removed the langcode value from the array it saved the image correctly!

killua99’s picture

Thanks you mojiferous! I did what you said and it works! This code should be added in the Module Documentation.

1an’s picture

Hi I am looking for a similar solution but I need to find the image fid before I start this process? I am trying to use it for a migration where there are multiple nodes that have the same image. Currently a media entity is being created for each one and I would like to assign one media entry to each node.

I have been unable to find a solution in my research as yet.

Greenskin85’s picture

1an just generate a lookup array while migrating. something like


if (!isset($lookup[FILE_IDENTIFIER_FROM_SOURCE])) {

  $media = Media::create([/* Creat yourr media file*/]);
  $lookup[FILE_IDENTIFIER_FROM_SOURCE] = $media;

}

$media_id = $lookup[FILE_IDENTIFIER_FROM_SOURCE]->id();

You might just save the media ID when no need of more info

sarguna raj M’s picture

Hi @marcoscano,
tired #5 but it's not working and getting error as "The website encountered an unexpected error. Please try again later.
Error: Undefined class constant 'PUBLISHED'".

Thanks.

Alex G’s picture

@sarguna raj M

You should replace:
'status' => Media::PUBLISHED

With
'status' => 1,