2

I want to get the id of an asset I've set for a feature image on an entry.

To find the entry I'm using the slug as the criteria like so:

$entry = Entry::find() 
  ->slug('0002')
  ->one();

In the returned object I'm expecting to see an array somewhere for custom field values listing the asset Id's, but it's drawing a blank

[_behaviors:yii\base\Component:private] => Array
        (
            [customFields] => craft\behaviors\CustomFieldBehavior Object
                (
                    [hasMethods] => 
                    [summary] => 
                    [featureImage] => 
                    [geopolygon] => [{"col1":"11","col2":"22"},{"col1":"11","col2":"2"},{"col1":"3","col2":"2"},{"col1":"","col2":""}]
                    [_customFieldValues:craft\behaviors\CustomFieldBehavior:private] => Array
                        (
                        )

                    [owner] => craft\elements\Entry Object
 *RECURSION*
                    [_attachedEvents:yii\base\Behavior:private] => Array
                        (
                        )

                )

        )

I know this entry does have a featureImage because it shows up in the admin and I can also view it on the frontend. I can also see all other custom values I've saved for the entry. What am I missing here?

2

In the returned object I'm expecting to see an array somewhere for custom field values listing the asset Id's, but it's drawing a blank

The reason for this is that entry fields are lazy-loaded, meaning Craft only queries the values from the database once you access them using their field handle (or execute the entity query you get through the field handle, like with the asset field). You can change this using Eager-Loading.

Without eager-loading, to get the asset you need to use the field handle (featureImage, in your case) to get an AssetQuery. Then you can use that to get the images (assets) in your field.

$entry = Entry::find() 
  ->slug('0002')
  ->one();

/** @var \craft\elements\Asset */
$featureImage = $entry->featureImage->one();

$featureImageId = $featureImage->id;

See Working with assets field data and Querying assets. The object returned by AssetQuery::one() is an instance of \craft\elements\Asset.

2
  • Ok, that is interesting. Thank you. How come other entry fields though are being loaded in this lazy-load? In the object I pasted above there is a geopolygon array there that has been loaded. Or does it just apply to assets?
    – Robert
    Apr 7 at 5:41
  • 1
    @Robert Not sure, it might depend on the fieldtype.
    – MoritzLost
    Apr 7 at 7:55

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.