5

I've got an asset field on a channel entry called "thumbnail". I'm using it to return a singular image, specifically for an image transform called "thumb". Looks a little like this:

{{ entry.thumbnail.first().getUrl('thumb') }}

This works fine. But I'd like to get the same information/url using a plugin (so I can perform some colour validation and other checks via PHP).

Can anyone share some wisdom on how best to approach this please?

8

Assuming you already have the entry (see Working with Elements for info about how to do that), you can interact with it exactly the same way you do in your templates - just with PHP syntax instead of Twig.

$asset = $entry->thumbnail->first();

if ($asset)
{
    $url = $asset->getUrl('thumb');
}

Though the transform won’t necessarily be available yet, since getUrl() will not generate transforms that don’t already exist by default.

That behavior can be customized with the generateTransformsBeforePageLoad config setting though, and lucky for you, you can even override the actual config value from PHP before calling getUrl(), using ConfigService::set():

craft()->config->set('generateTransformsBeforePageLoad', true);
$url = $asset->getUrl('thumb');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.