Using this answer on how to save data on Craft 3, I want to save also an asset field, but I cannot find out how.
It works for a Category field using the ids of the categories but not with ids of Assets.
Here is the code:
use craft\elements\Entry;
use craft\elements\MatrixBlock;
// Figure out the section & entry type
$section = Craft::$app->sections->getSectionByHandle('news');
$entryTypes = $section->getEntryTypes();
$entryType = reset($entryTypes);
// Create an entry
$entry = new Entry([
'sectionId' => $section->id,
'typeId' => $entryType->id,
'fieldLayoutId' => $entryType->fieldLayoutId,
'authorId' => 1,
'title' => 'My Entry',
'slug' => 'my-entry',
'postDate' => new DateTime(),
]);
// search categories and retrieve therir ids
$categorySlugs = ['cat1','cat2','cat3'];
$craftCategoryIds = [];
foreach ($categorySlugs as $cs) {
$craftCategoryIds[] = Category::find()->wpSlug($cs)->one()->id;
}
// get a an asset to be used as a featureImage
$featureImageId = Asset::find()->myField('123')->one()->id;
// Set the custom field values (including Matrix)
$fieldValues = [
'summary' => 'Some "summary" custom field value...',
'categories' => $craftCategoryIds, // <-- this works, categories are assigned
'featuredImage' => $featureImageId, // <-- doesn't work, featured image is not set
'matrixField' => [
'new1' => [
'type' => 'blockTypeHandle',
'fields' => [
// the block's custom field values...
],
],
'new2' => [
'type' => 'blockTypeHandle',
'fields' => [
// the block's custom field values...
],
],
],
]);
$entry->setFieldValues($fieldValues)
// Save the entry
Craft::$app->elements->saveElement($entry);