Craft CMS Asked on July 28, 2021
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:yiibaseComponent:private] => Array
(
[customFields] => craftbehaviorsCustomFieldBehavior Object
(
[hasMethods] =>
[summary] =>
[featureImage] =>
[geopolygon] => [{"col1":"11","col2":"22"},{"col1":"11","col2":"2"},{"col1":"3","col2":"2"},{"col1":"","col2":""}]
[_customFieldValues:craftbehaviorsCustomFieldBehavior:private] => Array
(
)
[owner] => craftelementsEntry Object
*RECURSION*
[_attachedEvents:yiibaseBehavior: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?
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 craftelementsAsset */
$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 craftelementsAsset.
Correct answer by MoritzLost on July 28, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP