1

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);
2

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

| improve this answer | |

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.