2

I'm learning to write my own modules, so there's a lot that I still don't know. I have looked at other modules/plugins, videos, but I arrived at a dead end.

I'm writing a module that generates formatted, responsive html tags. The module sets a function that can be invoked from within a template --this is working already. The main arguments it takes are the entry object (entry), the image field handle (fieldHandle) that needs to be queried, and the desired image transforms (transforms array) that are required.

With that I want to obtain the image loaded to the field, and access the urls of the transforms.

I was able to get this to work on a macro, but I'm having a hard time with how to do the same from within a module.

If anyone has an example or suggestions it would be really appreciated.

Thank you

NOTE: just in case, I'm not interested in assets bundles associated with the module. I'm trying to query an asset from a entry uploaded though the back end.

1 Answer 1

1

You can access the field in the entry by using the normal array syntax, $entry[$fieldHandle]. Depending on whether or not the field is eager-loaded, this will now be either an ElementQuery, which you can run ->all() on, or an array of assets.

When you have the asset, you can use $asset->getUrl($transform) to get the URL to a transformed image.

use craft\elements\db\ElementQuery;

...

$elements = $entry[$fieldHandle];
$assets = ($elements instanceof ElementQuery) ? $elements->all() : $elements;

if (is_array($assets) && !empty($assets)) {
    foreach ($assets as $asset) {
        foreach ($transforms as $transform) {
            $transformedUrl = $asset->getUrl($transform);
        }
    }
}
1
  • Dear André Elvan, thank you so much for your generous input. this is exactly what I was looking for. I finished the module I was creating and it all is working very well. Very much appreciated.
    – mauricio
    Oct 7, 2021 at 18:35

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.