Drupal 6 Tutorial: Creating a YouTube Video Gallery

Creating a gallery of your YouTube videos that you can filter by various tags is a trivial task in Drupal 6. Here's an overview of the steps you need to take to add a video gallery to your Drupal 6 site:

  • Create a video content type
  • Populate it with proper fields
  • Create a view to display these video
  • Create a few template files to help display your videos in a nice fashion
  • Make a small module to handle the JavaScript to create the YouTube player

Check out a demo of this sweet gallery on the infocus website!

Let's get to the nitty gritty of setting up this gallery.

Creating the content type

You'll want to go ahead and create a new content type, in this example we're going to name it video. Then we'll need to add some fields. I've added a text field for our youtube video ID and a taxonomy reference for our tags. Note that the wonderful File Entity and Media modules will allow you to have fieldable files easily – but they still need a lot of work to be more content-manager friendly, and are Drupal 7 only.

Creating the view

The next thing you'll need to do is set up a new view to display your gallery. In reality, your view will just show the grid of videos at the bottom of the gallery. We'll use templating and JavaScript to handle displaying the player and transitioning from one video to the other. These are the settings I used in this example:


I've got the YouTube ID Excluded from display, as well as the first link, title and summary. They are going to show when the video is clicked on.

Take note that I've given this view a page display and the filters I've placed on it.

Have you got that all set up? Cool, let's move on to making it functional!

The Template

Now we'll need to add in the player HTML and template the results from our view. I used a custom content pane in Panels to add in the player HTML, but you could also use a block that is only visible on the view page.

Here's the player HTML you need to add to a block or a pane on the view page (Or even in the header for the view):

  <div class="player-container">
    <h3 id="player-title"></h3>
    <div id="player-body"></div>
    <div id="ytapiplayer"></div>
  </div>

Here's the template that runs on the view – I kept some js in here to only run when this view is used (since we could use it elsewhere).

<?php
// views-view-unformatted--my-gallery.tpl.php
/**
 * Extended from
 * @file views-view-unformatted.tpl.php
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
 
drupal_add_js('
$(function() {
  var params = { allowScriptAccess: "always" };
  var atts = { id: "myytplayer" };
  var ytplayer;
  var firstID = $(".grid-video:first").attr("data-ytid");
  swfobject.embedSWF("http://www.youtube.com/v/"+firstID+"?enablejsapi=1&playerapiid=ytplayer&version=3&modestbranding=1",
    "ytapiplayer", "780", "439", "8", null, null, params, atts);
  $(".grid-video:first").addClass("nowplaying");
  $("#player-body").html($(".grid-video:first").children(".videoInformation").html() );
});
function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("myytplayer");
}
', 'inline');
?>
 
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

The Module

This module will simply add a bit of JavaScript to your site that will enable the YouTube player. Here's what you'll need with some explainations as to how they function:

mygallery.info

name = My Video Gallery
description = Adds a video gallery
core = 6.x
package = Gallery tweaks
 
files[]=product_video.js
files[]=swfobject.js

mygallery.module

<?php
 
/**
* Implements hook_init
*/
function mygallery_init() {
  drupal_add_js(drupal_get_path('module', 'mygallery') . '/swfobject.js');
  drupal_add_js(drupal_get_path('module', 'mygallery') . '/mygallery.js');
}

Here you can see I'm just adding the javascript to our included files. Since this is a short tutorial, I've stuck swfobject.js in the module. Normally you would want to include this by using the Libraries module.

mygallery.js

Drupal.behaviors.mygallery = function (context) {
 
  // Load video on click, apply css (for png overlay)
  $(".grid-video:not(.pv-processed)",context).each(function() {
    $(this).addClass("pv-processed");
    $(this).click(function() {
      //if this is nowplaying, return. -- Prevents reloading a video.
      if ( $(this).hasClass("nowplaying") ) {
        return;
      }
      $(".nowplaying").removeClass("nowplaying");
      var vidID = $(this).attr("data-ytid");
      thismyytplayer = document.getElementById("myytplayer");
      thismyytplayer.loadVideoById(vidID);
      $("#player-body").html($(this).children(".videoInformation").html() );
      $(this).addClass("nowplaying");
    });
  });
 
  // on exposed filter change, submit the form
  $(".page-videos select[name='type']:not(.pv-processed)").each(function() {
    $(this).addClass("pv-processed");
    $(this).change( function() {
      $("#views-exposed-form-product-video-gallery-default").submit();
    });
  });
 
}

The JavaScript here handles what happens when a user changes the exposed filter options, or clicks on the thumbnails to play a new video.

Once you've written the module and enabled it in your site, your gallery should be functioning!

Happy coding!


Hi Chris, thanks for your tutorial here! I' m trying to do exactly the same thing and I followed your tutorial, but there seems to be some inconsistencies.

First, in the mygallery.info file you declare two files:
files[]=product_video.js
files[]=swfobject.js

the code of which is never given!

The same happens in file mygallery.module where you refer to the swfobject.js file which is not given.

Also, for the now playing overlay I should use some CSS coding so could you give us this too?

Thanks, in advance and continue the good work!!


OK I found the swfobject.js! I didn't know that it was a publicly available project. Now it works!!! Amazing! Thank you very much for your tutorial!


Hi, again! I would like to use the views pager for using more videos that are too many to put in the same page. Currently your code cannot work with pager. Everytime you go to the next page the video stops. Is it possible to have the video continue playing and with ajax to move to the second page of the view?


Hi Chris, I managed to create a node gallery where the player is loaded by a custom node tpl.php I created, and the view is attached to this node gallery by using the module views attach. So the result now is that the video can play on the player while you can move from page to page in the views results by using ajax, without affecting/stopping the video. I also managed to overlay a play icon on the currently playing video of the views.

The only problem I'm facing now is that when you move to another views page and come back the nowplaying class is not remembered, resulting in losing the overlaying icon!! By studing your code I realized that your nowplaying class is assigned only during click!! So after moving to other views pages which are called via ajax, the nowplaying class is lost. Do you have any idea how can I make it persistent, or at least how can I trigger a javascript function to be called in every views ajax event where we should check if the video thumbnail should have a nowplaying class or not?
A thought is also to check during the views generation every item and if the item has the same Id with the video now playing to assign a class. Could this work? How can I read from the views template file the id of the video that is currently in the player?

Any help would be really appreciated!


You could add in some javascript inside of the Drupal.behaviors.mygallery method, and by default, will be called after each views call. I'm avoiding binding click events, etc to multiple elements by making use of adding the pv-processed class along with using the context variable in those selectors. If you removed them and had something like this: http://pastebin.com/mc0gdWD9 you can see when it is being called. Check out this for more information on Drupal behaviors and context: http://drupal.org/node/304258#drupal-behaviors


I am trying to follow this on a D7 and have come stuck on the "Rewrite the output of this field" particularly the [view_node] where is that coming from.
Thank you for such a wonderful article

Regards Tim


Hi Christ: Nice tutorial and I am trying to set up one video gallery by following your steps. In the View page, you have setup 2 Taxonomy: Term exposed. Would you please explain in detail about how to set them up? I am also not sure why there are 2 of them.

Thanks in advance.


Thanks for posting this!
Is "product_video.js" really supposed to say "mygallery.js"? Would you be able to double-check that all file-names/references are correct? That would be much appreciated. I have followed the steps, but it's still not working, so I'm trying to figure out what is going wrong..

Add new comment

Restricted HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <h4> <h5> <h6>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>&lt;code&gt;</code>, <code>&lt;blockcode&gt;</code>, <code>&lt;apache&gt;</code>, <code>&lt;c&gt;</code>, <code>&lt;cpp&gt;</code>, <code>&lt;css&gt;</code>, <code>&lt;drupal5&gt;</code>, <code>&lt;drupal6&gt;</code>, <code>&lt;html&gt;</code>, <code>&lt;java&gt;</code>, <code>&lt;javascript&gt;</code>, <code>&lt;mysql&gt;</code>, <code>&lt;php&gt;</code>, <code>&lt;python&gt;</code>, <code>&lt;ruby&gt;</code>, <code>&lt;sql&gt;</code>, <code>&lt;xml&gt;</code>. The supported tag styles are: <code>&lt;foo&gt;</code>, <code>[foo]</code>.

About the Author

Chris Svajlenka, Development Team Lead

Chris is a web developer with many years of experience developing web applications. PHP is his go-to language, with experience with others such as Ruby and Python. He has provided systems administration to large organizations and enjoys hunting down bugs in code.

Chris enjoys a love of documentaries with an emphasis on nature, the cosmos, and sustainable business practices. He also has a love for plants, gardening and a fine IPA.