I have spreadsheet that i'm parsing and I have available to me a Entry ID and the Asset filename. Can I add the asset to the entry by the filename?

Im targeting the product entry with:

$product = Entry::find()->section('products')->id($data[3]);
$productImages = ($product->productImages) ? $product->productImages : array();
$name = explode('?', basename($data[2])); 
$pushImageId = Asset::find()->filename($name[0])->id; // $name[0] = myfilename.jpg
$productImages = array_push($productImages,$pushImageId);

The handle for the asset field is: productImages

So when I run this i get this error:

Exception: Argument 1 passed to craft\services\Elements::saveElement() must implement interface craft\base\ElementInterface, instance of craft\elements\db\EntryQuery given



Based on the answer from robin in this question How to save Asset field of an Entry programmatically in Craft 3

It you just need to attach the asset ID's as an array. So i re-wrote the following code to create a new array of the original asset ids plus the new one. And it worked!

$product = Entry::find()->section('products')->id($data[3])->one();
$name = explode('?', basename($data[2]));
$pushImageIds = Asset::find()->filename($name[0])->ids(); // $name[0] = myfilename.jpg
$newProductImagesArray = array();
foreach($product->productImages as $image){


1 Answer 1


You need to fetch the asset and set it as a field value to your entry

$pushImageId = Asset::find()->filename($name[0])->ids();

id will display the id property of your query. You won't fetch any results with it ids() will return an array of asset ids

$product->setFieldValue ('productImages', $productImages);

Will set the relation and finally you can store the element

Edit: and you need to fetch the product as well. Currently you just create the query for it


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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