Drupal Programmatically Add Youtube Video to Video Field


Drupal 8 gives various type of fields includes the video field. In the video field there is an option to add different kind of videos like upload, youtube, vimeo, wistia videos to the drupal fields. When you create a node programmatically we have to set values to the custom fields. Normally we set the values to the fields in the following way,


Unfortunately it wont work for the video field, we have to do it in a different way like the following code,

First have to get the filename from the youtube link, youtube video link will be in different kind of format. So there is Regex pattern to grab the filename from it. The preg_match function grab the video id from the $youtube_link and stored the video details into the $matches variable.

The $matches variables hold some video meta information including the filename in the id value. Check the following code,

$data = '';
$youtube_link = 'https://www.youtube.com/watch?v=Uh5mEat46fc';
preg_match('/^https?:\/\/(www\.)?((?!.*list=)youtube\.com\/watch\?.*v=|youtu\.be\/)(?<id>[0-9A-Za-z_-]*)/', $youtube_link, $matches);
$filename = $matches['id'];
$filename = substr($name, strpos($name, "=") + 1);
$file = file_save_data($data, 'public://' . $filename, FILE_EXISTS_REPLACE);
$file->setFileUri('youtube://' . $filename);

Actually here we save the empty file with video id as the filename. It won;t hold any data just only for the reference, then we set MimeType as video/youtube and set the File URI with the youtube video URI(youtube://{filename}). Then save the file. Finally we can set this file id as the target id of the video field. And set the data value with the serialized $matches variable.

$node->field_youtube = [
 'target_id' => $file->id(),
 'data' => serialize($matches),

Finally just save the node. It will add the youtube video to the video field in your node.