3

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

1 Answer 1

4

That's because you have to insert an array of ids rather than a single id

$craftCategoryIds

is an array.

$featureImageId

is an integer. Even if you have just a single element you need to insert an array

'featuredImage' => [$featureImageId]

will work

1
  • Naturally this works for all element types (i.e. Entries/Asset fields). Thanks Robin - that was driving me crazy.
    – JamesNZ
    Commented Apr 3, 2018 at 1:00

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.