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);
$product->productImages($productImages);
Craft::$app->elements->saveElement($product);
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
Thanks!
Solution
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){
array_push($newProductImagesArray,$image->id);
}
array_push($newProductImagesArray,$pushImageIds[0]);
$product->setFieldValue('productImages',$newProductImagesArray);
Craft::$app->getElements()->saveElement($product);