Custom Service for Youtube URL in Drupal 8, 9, 10

28 / Jan / 2024 by shubham.joshi 0 comments

Overview

When working with YouTube video integration in Drupal, you often come across which proper YouTube URL we use in our application for playing videos. Sometimes, a few URLs worked on a few browsers, and some didn’t. However, to overcome this kind of problem, we already have a contributed module in Drupal named YouTube Field, which provides a simple field that allows you to add a YouTube video to a content type, user, or any other Drupal entity. But if the requirement is more than we have to do customization as per requirement.

In this blog, I present one case study of my Drupal project where I had to integrate YouTube URLs on entities and place their proper URLs in iframe. I need to play a YouTube video in an iframe.

Problem Statement

We already have the YouTube Field module, which provides inline video support in iframe. But if a page contains more than 100 videos, then the performance of that page decreases. We have to create a feature in such a way that only the image will display first in the list, and on clicking the image play button, Iframe loads video URLs in pop up and plays the video. While loading URLs in pop-up iframe sometimes URLs get broken or distorted due to not proper YouTube URLs.

In Drupal, users can upload different URL patterns of YouTube videos, but some URL videos will not be able to play in iframe. Content editors are not technically aware of proper YouTube URLs.

Solution

To overcome this, I have created a common service that can be used throughout applications for fetching proper YouTube URLs. You can call this service in your custom code and create a proper YouTube URL before placing it in iframe. You can also create twig extension functions that help you sort out this problem in views or in twigs directly.

Code

/**
* Get Youtube Embed URL.
*
* @param string $url
* URL of youtube.
*
* @return string
* Embed URL of youtube.
*/
public function getYoutubeEmbedUrl($url) {
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_-]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))([a-zA-Z0-9_-]+)/i';
if (preg_match($longUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
if (preg_match($shortUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
return 'https://www.youtube.com/embed/' . $youtube_id;
}

Conclusion

In this way, we can achieve proper YouTube URLs. You can call this service and pass the existing URL of YouTube, and it will return a proper URL. If you don’t have much customization or only a single video will be there on a single page you can use the Youtube Field module.

If you still have any questions, leave a comment and join the discussion. Happy reading!

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *