Jun200925

Creating a grid of images for an album in Drupal 6

Following on from the tutorial of creating an album based gallery in Drupal 6. This tutorial will teach you how to create a basic grid of the images in the node.

Update: I have written an updated tutorial with code to allow you to have pagination on your grid of images.

In your content type, go to Display fields and set the Full node to <Hidden>. This will take the images out of the $content variable.

Then in your theme, copy the existing node.tpl.php and create a new identical file called node-album.tpl.php (the album part with be the content type name that you used from the tutorial.)

Below the content section, add the following PHP code:

<?php
$images = $node->field_images;
if (count($images) > 0):
  $rows = array();
  $images_per_row = 3;
  $i = 0;
  $row = 0;
  foreach ($images as $image) {
    $rows[$row][$i] = '<a class="gallery-thumbs" title="'. htmlspecialchars($image['data']['description']) .'" rel="lightbox[photo_gallery-'. $node->nid .']" href="'. imagecache_create_url('lightbox', $image['filepath']) .'">'. theme('imagecache', 'thumbnail', $image['filepath'], $image['data']['title'], $image['data']['title']) .(trim($image['data']['description']) != '' ? '<br /><small>'. $image['data']['description'] .'</small></a>' : '');
    $i++;
    if ($i == $images_per_row) {
      $row++;
      $i = 0;
    }
  }
?>
<table class="views-view-grid">
  <tbody>
    <?php foreach ($rows as $row_number => $columns): ?>
      <?php
        $row_class = 'row-' . ($row_number + 1);
        if ($row_number == 0) {
          $row_class .= ' row-first';
        }
        elseif (count($rows) == ($row_number + 1)) {
          $row_class .= ' row-last';
        }
      ?>
      <tr class="<?php print $row_class; ?>">
        <?php foreach ($columns as $column_number => $item): ?>
          <td class="<?php print 'col-'. ($column_number + 1); ?>">
            <?php print $item; ?>
          </td>
        <?php endforeach; ?>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>
<?php else: ?>
  <p>No images in album</p>
<?php endif; ?>

The table code is a direct copy from views-view-grid.tpl.php so the code should look identical to the Album view.

Replace the following with your own settings:

imagecache_create_url('lightbox', $image['filepath'])

Change lightbox for the name of the imagecache preset that should open up within the lightbox.

theme('imagecache', 'thumbnail', $image['filepath'], $image['title'], $image['title'])

Change thumbnail to the name of the imagecache preset that should be displayed.

To add more columns to your grid, change the $images_per_row variable.

Update: I have written an updated tutorial with code to allow you to have pagination on your grid of images.

75 Responses to “Creating a grid of images for an album in Drupal 6”

  1. Rik

    Great! I finally tried this as well, and it works fine.
    I changed rel=’lightbox’ into rel=’lightshow’ so that my images turn into a slideshow.
    But I lost my captions. Any idea what I should change? Thanks.

  2. MixedUpMedia

    Thank you so very much for sharing this code. Just wanted to add that another setting that might need to be customized is in the first line of PHP code:
    $images = $node->field_images

    My custom field was called field_gallery instead of field_images, and it took a “duh” moment to realize why the page kept returning “No Images in Album.”

  3. Markus

    Thank you very much for your great tutorials: they were easy to follow and more than helpful. Simply brilliant!!

    Is there any way of limiting the number of images that are shown on the frontpage? I am thinking of something like only the first row of the album. Probably, this can be down fairly easy by changing your PHP code, but unfortunately I am not very familiar with PHP. Can you point me into the right direction?
    Thanks a lot!

    • Change this line:
      $rows[$row][$i] = '<a class="gallery-thumbs"................' : '');
      To:
      if ($row == 0) $rows[$row][$i] = '<a class="gallery-thumbs"................' : '');

  4. hey I have a question – when I am adding an image to this gallery (which works great by the way!) I enter a description too.. I was expecting this to show up when you open an image that is inside an album within lightbox. So lightbox opens up, shows you the image, but no description. Where can I add in this functionality? I have had a play with node-album.tpl.php but not much joy ($description) pretty long shot but I’m an html/css person, php i a mystery – Thanks!

  5. Ok it seems that, in my album content type – in my images fields, I have title chosen – so when you upload photos you enter a title, this should be fine. I enter a title and save it – I can see the title on hover, but even in the source code of my album, the titles are just title=”" , nothing in there… help! going crazy here!

  6. could someone post their node-album.tpl.php up here that works with lightbox2 and captioning from description? Would be really useful for a few people I’m sure… Thanks!

  7. Markus

    @admin:
    Thank you James for your quick reply! Adding the if-clause restricts the view to the first row of images for both, the teaser as well as the full node. However, for the album node itself I would like to keep all rows. Only on the frontpage one row would be sufficient.

    So, my idea was to insert a teaser break . I had some tries experimenting with the PHP code, but I have not been successful so far. Any help would be appreciated…
    Thanks!

    • @Markus, In which case change the line you changed before to this:
      if ($row == 0 && $page == 0) $rows[$row][$i] = '<a class="gallery-thumbs"................' : '');

      @softsystems, If you are using the description field rather than the title field in the imagefield for the Content type, try changing:
      $image['title']
      To:
      $image['description']
      On the line after foreach ($images as $image) {

  8. @admin, I did try that actually, I also tried w=switching from using the Title attribute, and the description, and both at the same time.

    In my node-album.tpl.php I have the following:

    on line 20

    field_images;
    if (count($images) > 0):
    $rows = array();
    $images_per_row = 5;
    $i = 0;
    $row = 0;
    foreach ($images as $image) {
    $rows[$row][$i] = ‘nid .’]” href=”‘. imagecache_create_url(‘lightbox’, $image['filepath']) .’”>’. theme(‘imagecache’, ‘thumbnail’, $image['filepath'], $image['title'], $image['title']) .(trim($image['title']) != ” ? ”. $image['title'] .’‘ : ”);
    $i++;
    if ($i == $images_per_row) {
    $row++;
    $i = 0;
    }
    }
    ?>

    there are quite a few @image['title']‘s in there – should I change all of them to description and try that?

    However, you would have thought that my just using the title in the content type would have made this not a problem in the first place…

    any ideas? thanks for you fast reply – im desperado!

  9. anyway i tried replacing everything in that block i posted with ‘description’ and no joy.

    If you go here: http://www.none.org.nz/node/31

    In this gallery, the first image has a description saved on it in the album. But I still cant see it in lightbox. Thanks again

    • @softsystems, Do you want the Content type description (body field) as the Lightbox caption text? If so replace the following:
      htmlspecialchars($image['title'])
      With:
      htmlspecialchars($node->body)

  10. Markus

    @admin:
    Finally I got there…
    Apart from your replacement
    if ($row == 0 && $page == 0) $rows[$row][$i] = '<a class="gallery-thumbs"................' : '');
    that limited the number of images on the front page to the first row, I had to add the following elseif-clause
    elseif ($page != 0) $rows[$row][$i] = '<a class="gallery-thumbs"................' : '');
    Otherwise no images at all were shown on the album node itself.

    Thanks for your help and your patience, James!!

  11. thankyou thankyou thankyou!

  12. oh, its not using the description of the individual images though… just the album description,and all my other details. any code for the thumbnail/image dscroptions i can put here instead? thanks so much for your help!

  13. nevermind, i just changed it to htmlspecialchars($node->title) and away we go! thanks!

  14. ack. so its still just using the album title, not the description I have assigned to each image as I uploaded it to the album – hopefully you know what I mean here – any more ideas? sorry for the spam!

  15. the image title attribute is showing up on hover in the block of my grid view/album view. However, inside the album (page view) when I hover it shows the album title, not the image title. this is my problem – do i need to add another view maybe? or is there a little bit of code I can add to the node-album.tpl.php to get the image title to attach to the thumbnails in my grid view on the page?

    • @softsystems, on the line before the “$rows[$row][$i] = …….”, type in the following:
      var_dump($image);exit;
      Refresh the page, go in to source code view in your browser. Find the bit of text that you put in for the description, then find the key which should be on the line before it. This needs to be put within the htmlspecialchars() function. Eg:
      htmlspecialchars($image['description'])

  16. @admin – that var_dump code just breaks the whole page

    this is a snippet of my code now:

    foreach ($images as $image) {
    var_dump($image);exit;
    $rows[$row][$i] = ‘<a class="gallery-thumbs" title="'. htmlspecialchars($image['description']) .

    I just tried putting in the description suggestion anyway, I couldnt really get in anywhere to see the source code as the page was busted. Did I put it in the wrong place?

    • @softsystems, No that is right, and it should break your page, but it should give you some code. From that code you can find where the description is. I will set it up again and make sure the code works correctly.

  17. surely other people would want their image descriptions (as included in your tut) to show up in their lightbox as they browse images? Can you upload a tweaked node-album.tpl.php file – as I’m sure a lot of people are interested in this function. Or is this function supposed to work anyway if you do this tutorial and I messed it up somewhere… let us know! Thanks again for your help, I’d be totally lost without it

  18. Yeah that would be great if you could set it up again – sorry to really work you on this one!

    so when ibroke it with the ‘dump’ code, i got this

    array(11) { ["fid"]=> string(2) “54″ ["list"]=> string(1) “1″ ["data"]=> array(3) { ["description"]=> string(1) “1″ ["title"]=> string(1) “1″ ["alt"]=> string(0) “” } ["uid"]=> string(1) “1″ ["filename"]=> string(12) “P1010232.JPG” ["filepath"]=> string(34) “sites/default/files/P1010232_0.JPG” ["filemime"]=> string(10) “image/jpeg” ["filesize"]=> string(6) “128518″ ["status"]=> string(1) “1″ ["timestamp"]=> string(10) “1250923843″ ["nid"]=> string(2) “31″ }

    so then i removed the var_dump($image);exit;
    and changed my code to this htmlspecialchars($image['description'])

    but nothing, maybe I am picking out the wrong part of the code it spat out? nearly there i think! thanks again for sticking this out – ss

    • @softsystems, When you upload a new album does it give the option of adding a description to each image once uploaded or does it say Title? If neither you may need to modify the field_image CCK imagefield so that you can type it in. From the code you posted, $image['description'] should print out 1, not nothing.

  19. Yes I have the option of adding a description, I have also enabled title. I have typed them both in and saved them for each image I have uploaded to my albums so that I can test this to get the captions working :) I have followed your tutorial/s exactly, multiple times.

    I know the captions should theoretically be working, thats why this is so odd… theres something definately missing from the node-album.tpl.php – any progress on the new version? Or just uploading an node-album.tpl.php version that works with captions inside lightbox? Thanks again

    • @softsystems, Silly mistake from me, it should be:
      $image['data']['description']
      So replace any instances of $image['description'] or $image['title'] with it. I will update the tutorial with it.

      • First, let me thank you for a wonderful series of tutorials.

        For about a month I have been experimenting with several online photo album tutorials which either failed to meet my requirements or failed to deliver as promised. Your tutorial is by far the most comprehensive, as it takes one all the way to pagination. Also lightbox was a novel and slick way to page through the images in a gallery.

        Second, while your solution appears to be the best I have seen so far, I still have not been able to get it to work.

        1) After adding and saving the descriptions for each successfully uploaded image NO descriptions get stored. When I upload a new album it gives me the option of adding a description to each image once uploaded. However, Going back to view the album content shows that all the description fields are empty. A var_dump confirms that both my description and title fields are empty.

        2) My field_image CCK appears to be okay. I reviewed the field_image CCK imagefield several times against your previous tutorial.

        3) I do not know why the descriptions are not being saved. Your tutorial is the first I have seen/attempted which allows for the addition of an unlimited number of image files to the album content type. Are each of the files saved as a separate node? Or are there several image files attached to each album node? Would you happen to have an idea why my descriptions are not being saved?

        4) Another notable photo album solution was communicated in a quickly covered video tutorial by Jeff Eaton of Lullabot (http://www.lullabot.com/articles/photo-galleries-views-attach). While his solution fell apart in terms of pagination, it has an interesting architecture. His solution uses the node reference URL module, and the Views Attach Module and a couple of somewhat non-intuitive embedded views. There is a nice teaser post with an album overview photo, and then a nice gallery similar to yours. What is nice about his solution architecture is that each photo is a node which gets associated with an album node, which gives the admin a lot of control and flexibility in terms of creating views.

        I may try to merge your paging solution with Eaton’s technique, if I am unable to get the descriptions to work.

        Thanks for your help.

        • Not sure about the descriptions. Is the database updated with your description?

          This solution has all the images attached to it’s relevant node.

          The Lullabot solution sound like a better solution for flexibility but I am not sure what the problems are for adding pagination, I guess it depends on the queries being ran by Views.

        • James, thanks for the help. While I am not exactly sure how to verify that the database updated with my description, I was able to export the structure and dump the data for the album content type table. Browsing the table revealed no additional information (at least that I could find).

          Exporting the table structure for table `content_type_album_fotos`, I get the following.

          CREATE TABLE `content_type_album_fotos` (
          `vid` int(10) unsigned NOT NULL DEFAULT ’0′,
          `nid` int(10) unsigned NOT NULL DEFAULT ’0′,
          PRIMARY KEY (`vid`),
          UNIQUE KEY `vid` (`vid`),
          KEY `nid` (`nid`)
          ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

          Dumping data for table `content_type_album_fotos`, I get the following.

          INSERT INTO `content_type_album_fotos` VALUES(66, 66);
          INSERT INTO `content_type_album_fotos` VALUES(67, 67);

          —-

          While I am a relative newbie to mySQL and phpMyAdmin, this table structure and data dump appear to me to be inconsistent with a setup which would record the descriptions of multiple images (files) added to a node. If so, this would explain why the database fails to take and retain the descriptions I provide. Any thoughts?

          As I stated in my prior comment, after entering the descriptions for multiple images associated with the album content and then clicking save, the descriptions on the page instantly disappear, never to return.

          I have setup the album content type properly (as far as I can tell) to accept multiple image files with descriptions. I must have configured something at least partially correct, since I am able to upload multiple images and to have them all for later recall, and displaying in a grid of images. Also after uploading I am given a dialog box to enter a description for the image file.

          This is the result from my var_dump, which shows the uploaded jpg image, but nothing stored for either description or title.

          array(12) { ["fid"]=> string(2) “95″ ["list"]=> string(1) “1″ ["data"]=> array(13) { ["fid"]=> string(2) “95″ ["width"]=> string(4) “3968″ ["height"]=> string(4) “2232″ ["duration"]=> string(1) “0″ ["audio_format"]=> string(0) “” ["audio_sample_rate"]=> string(1) “0″ ["audio_channel_mode"]=> string(0) “” ["audio_bitrate"]=> string(1) “0″ ["audio_bitrate_mode"]=> string(0) “” ["tags"]=> array(0) { } ["description"]=> string(0) “” ["alt"]=> string(0) “” ["title"]=> string(0) “” } ["uid"]=> string(1) “1″ ["filename"]=> string(12) “P1040001.JPG” ["filepath"]=> string(46) “sites/multisite_name.sitename.local/files/P1040001.JPG” ["filemime"]=> string(10) “image/jpeg” ["filesize"]=> string(7) “4680336″ ["status"]=> string(1) “1″ ["timestamp"]=> string(10) “1278149007″ ["nid"]=> string(2) “67″ ["view"]=> string(638) ”

          Thanks again for your help.

        • From the var_dump, the file ID is 95, so if you search your files table in PHPMyAdmin you will be able to find out if the data is saved in to the database or not. By the looks of the var_dump, it isn’t which implies there may be a problem with filefield or imagefield.

  20. OH HOORAY!!!! sorry i pestered you so much but thats ironed it right out, awesome! Thanks so much

  21. Rik

    Great, I got it working too now.
    Many thanks for that!

  22. mxn

    I’ve been trying to setup a gallery using image_fupload instead of the regular image. what settings should I change or be using to group the images in their respective albums? thanks.

    • @mxn, I haven’t tried it, but it should just be a matter of replacing the imagefield with the image_fupload CCK item.

  23. mxn

    Thanks for the response.

    The thing is that when I use image_fupload, the pictures do not group together. I’ve tried doing it through views, but I still do not get that final result. I’m thinking that maybe there are some strings I need to change here, but I am not sure what they are.

    I dont know if this helps, but I have selected imagecache:thumbnail under site configuration>images>imagefuploadsettings. I hope something can be worked out.

    Thanks.

    • @mxn, have you followed this tutorial or are you using the Image module?

      I have just set up a test site with Image fUpload and it works fine.

  24. mxn

    Yes I have. I think I may have found the problem. I unchecked the other modules, fupload, etc… and I couldn’t get it to work normally. I ended up noticing that the node-album.tpl.php was in the root directory and not under the theme’s root. I will try again with fupload and let you know if that was it. Thanks again.

  25. opend

    Great tutorial! Exactly what my project needed. Thanks so much for posting this. This grid to images is icing to the cake.

  26. evo

    this was awesome, thanks admin,

    any idea how to set a pager like you can set in views for the node view of an album?

    Thanks for the tutorial

  27. Brian

    I followed your directions and got this working as advertised – thanks for a great way to create a photo album. I am having trouble with the album grid – specifically changing the filepath inimagecache_create_url(‘lightbox’, $image['filepath']) to my settings.

    Does “theme” get replaced with the name of my theme?

    I tried setting filepath to default\files\imagecache\thumbnail – the images do not appear. Not sure what to use as the files in this path are named like .jpeg_0

  28. Brian

    This is also confusing:

    rel=”lightbox[photo_gallery-'. $node->nid .']
    looking through the directions, nothing was called photo_gallery

    • @Brian, You shouldn’t need to change the filepath. As for the rel=”" code, that is used to group all the images together in the lightbox, so you can use the next and previous buttons.

  29. Brian

    OK – Recopied the source above and got my album to display in a grid. Lightbox is correctly showing the individual descriptions added for each picture when creating the album. However, when hovering over the image while in lightbox, I keep getting the description of the first image – the description is correct at the bottom, just the hover is incorrect. If I click on the link for say the third image, it’s description is displayed on hover for every other image. I looked at your responses above, but no one seems to have noticed this. Can this be fixed?

    • @Brian, Change $image['data']['title'] to $image['data']['description']

  30. Brian

    Changed all instances – still the same behaviour. The description in the popup on rollover while displaying the photos in lightbox is the same as the first image clicked. In Normal Gallery view, the rollover description of each picure is correct.

    Sorry to be a pest…

    • @Brian, sorry which one is correct? The tool tip when you put your mouse over the image? or the description in the lightbox?

  31. Brian

    Thats OK The description in lightbox is correct. The tool tip in lightbox is incorrect. When you click on an image in the grid created from the code above, lightshow starts. When you hover over the image, the tool tip is correct. When you procede to the next image in lightbox and hover over the image, the tool tip is for the first image. All other tool tips – in lightbox only are for the first image clicked on. I’m using IE8.

    • @Brian, Sounds like that may be a problem with the Lightbox module rather than the code.

  32. Brian

    I’ll look into it and let you know. Appreaciate your responses, paitence and great instructional style :)

  33. alekth

    This worked for me but only to an extent, I lost the “dowload original” in lightbox.

    I found this on the drupal forums, it’s to be added in modules/filefield/filefield.css

    div.field-field-images img {
    display: inline;
    float: left;
    margin: 5px;
    text-align: left;
    }

    images in field-field-images is the machine name.
    Went with that solution in the end since it kept lightbox stuff intact, it’s not a grid but it comes close.

  34. Vandalf

    Hi,
    First, let me thank you a thousand times for making such an easy-to-follow tutorial, with such an excellent result!
    However, I have one tiny struggle. Everything is looking very good, but I’d like to increase the spacing between both rows and columns. I’ve tried to adjust the “Separator” in the Row style, but that does not seem to work at all. Tried both the   and setting a px, an em, or a % number, but nothing made a difference.

    Probably should let you know that I’m using a contributed theme called Mistylook. Perhaps the problem is there? If so, could you give me a tip as to what to look for, because I cannot seem to find the correct line.

    Again, thanks a million for this tutorial, and thanks in advance for any help on my problem!

    • @Vandalf in your CSS file, you could add a line for .views-whatever-your-table-class-is td img { padding: 5px; }

      • Vandalf

        Ah! Of course! That is brilliant! Thank you so much for your quick reply! It now looks exactly as I wanted! :)

  35. Makoto

    Hi, good day.

    I wanna thank you and congratulate you for making such an incredibly easy tutorial. It was very easy to follow and the results are really impressive.

    I was wondering, Is it possible to add pages to an album? I mean, in the case I had more than 9 images in an album I want to show just 9 images in Page 1, 9 images in Page 2 and so on.

    If possible, How can I achieve it?

  36. Jason

    First part of this, where it says go to your content type I’m assuming this is the Album content type we created in the album based image gallery tutorial.. however when I go to Display Fields all I see is Images, no Node field? Am I missing something here?

    Great tutorial though, wish I’d seen this a week ago!

    • @Jason, yes, that should be hide Images for full node and teaser if you wish.

      • Jason

        Hah sorry, my bad – totally missed that… was nearing the end of a long day! Thanks for the perfect tutorials on this!

  37. [...] I have now written a tutorial on creating a grid of images within an album using the node-album.tpl.php method. « Fatal error: Unsupported operand types in email_registration.module on line 61 Creating [...]

  38. Thank you very much for your tutorials. I have been using them for the last few days and feel like i’ve learned a lot. (seriously)

    Have you dealt with the lightbox2 arrow key navigation issue in firefox? http://drupal.org/node/349843

    i was wondering how you have dealt with it. (if at all)
    My site that has this issue is http://www.crmw.net/edwight/node/4
    (made this site before finding your tutorials)

    Thanks for your time.

    • I hadn’t used the arrow keys before but I see the issue. This will be an issue with the Lightbox2 module and will have to wait for the maintainer to fix the problem.

  39. DexVex

    Hi, i follow your tutorial, but something is not matching, it works well without grid and pagination, but with grid and pagination, the images did not show in the content, but the pagination do, i’ve inserted 12 pics.

    So must be on the code, can you give me a clue of what’s happening?

    Thanks

    • Make sure that you haven’t given different names to your content field for your images.

      • DexVex

        yes i did, but a in the code, i replace the field_images for the name i’ve gave, and in the database query i did the same thing. It find the pics because the pagination works fine, just, the pics dont shows up;

        ps: i did this on another site that worked fine, and i followed the same steps

        thanks again

  40. devajeet

    Seriously, thank you so much!!

    Its awesome!!
    I am new to drupal, and I was scratching my head for hours until I found this tutorial.

    Thanks a lot!

  41. Cristina

    Great tutorial. I made a mistake somewhere though, I have the images twice now, once one per row and second time two per row, as i defined in the template. Any idea where to look to fix this?
    http://www.friendshostel.ro/node/24
    Thank you.

    • You need to go in to your content type, the edit your content type for your album and chose Display fields, then set your images field to for both the teaser and full node.

      • Carlos

        You need to go in to your content type, the edit your content type for your album and chose Display fields, then set your images field to for both the teaser and full node.

        I am having the same issue…. set your images field to for both the teaser and full node…. what is ?

      • Carlos

        ok for some reason it edited out my words there on my reply earlier, lol. I am also having the same issue where you say set your images field to………..for both the teaser and full node.

        What is ………..

    • Carlos

      I figured it out… Christina both the teaser and full node should be set to hidden…

  42. Interesting tutorial; thanks.

    Matt

Leave a Reply