Jump to content

Thumbnail Module: Test If An Image Field Contains A Thumbnail


bytesource
 Share

Recommended Posts

Hi, 

I wrote a helper function that takes an image field instance and returns its respective <img> ... /> HTML.

After installing the Thumbnail module I wanted to always output the thumbnail if present. 

In order to determine of an image has an additional thumbnail, I tested for the 'getThumb' method that is added by the module to  PageImage. However, the following code always returned the path to the original image, even if a thumbnail was present:

$url = method_exists($image, 'getThumb') ? $image->getThumb('thumbnail') : $image->url;
 

This leads me to the following questions:

  1. Why does the above code not work?
  2. Is there a better way to differentiate between a 'normal' image field and one that can contain a thumbnail?

Cheers, 

Stefan

Link to comment
Share on other sites

Hi bytesource,

1) This won't work because the getThumb method is added dynamically with a hook. Most likely 'method_exists' will look for static methods in classes, that's because false is returned.

2) After taking a short look at the description of the module, this could work:

if ($imageField->type == 'FieldtypeCropImage') {
  //... Thumbnails
}
Link to comment
Share on other sites

I think that you could do this: 

if(count($image->getHooks('getThumb'))) {
  $url = $image->getThumb('thumbnail'); 
} else {
  $url = $image->url(); 
}

another way:

try {
  $url = $image->getThumb('thumbnail'); 
} catch(Exception $e) {
  $url = $image->url(); 
}
  • Like 1
Link to comment
Share on other sites

@Wanze

I tried your code, but $image->type does not produce any output. 

I have to admint I am not quite sure what FieldtypeCropImage stands for. As far as I understand $image is still an instance of PageImage, with a dynamically added 'getThumb' method. Indeed, the following always returns 'original image'

if ($image instanceof PageImage) echo "original image";
else echo "thumbnail";
// => original image
 

@ryan

I like your second suggestion. It works perfectly.

Cheers, 

Stefan

Link to comment
Share on other sites

Sorry, I was wrong.

type exists on the field object. So this should also work:

if ($fields->get('yourImageFieldName')->type == 'FieldtypeCropImage') {
  // Thumbnail

FieldtypeCropImage is the Fieldtype used by a thumbnails image field.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...