Answers.Body: <p>That's because you have to insert an array of ids rather than a single id</p>
  
  <pre><code>$craftCategoryIds
  </code></pre>
  
  <p>is an array.</p>
  
  <pre><code>$featureImageId
  </code></pre>
  
  <p>is an integer. Even if you have just a single element you need to insert an array</p>
  
  <pre><code>'featuredImage' =&gt; [$featureImageId]
  </code></pre>
  
  <p>will work</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-04-03T01:00:09.747Z
Answers.Text: Naturally this works for all element types (i.e. Entries/Asset fields). Thanks Robin - that was driving me crazy.
Answers.UserDisplayName: JamesNZ
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2018-03-21T22:03:50.600Z
Answers.LastActivityDate: 2018-03-21T22:03:50.600Z
Answers.UserDisplayName: Robin Schambach
Body: <p>Using <a href="https://craftcms.stackexchange.com/questions/21864/how-to-save-matrix-data-programmatically-in-craft-3">this</a> answer on how to save data on Craft 3, I want to save also an asset field, but I cannot find out how.</p>
  
  <p>It works for a Category field using the ids of the categories but not with ids of Assets.</p>
  
  <p>Here is the code:</p>
  
  <pre class="lang-php prettyprint-override"><code>use craft\elements\Entry;
  use craft\elements\MatrixBlock;
  
  // Figure out the section &amp; entry type
  $section = Craft::$app-&gt;sections-&gt;getSectionByHandle('news');
  $entryTypes = $section-&gt;getEntryTypes();
  $entryType = reset($entryTypes);
  
  // Create an entry
  $entry = new Entry([
      'sectionId' =&gt; $section-&gt;id,
      'typeId' =&gt; $entryType-&gt;id,
      'fieldLayoutId' =&gt; $entryType-&gt;fieldLayoutId,
      'authorId' =&gt; 1,
      'title' =&gt; 'My Entry',
      'slug' =&gt; 'my-entry',
      'postDate' =&gt; new DateTime(),
  ]);
  
  // search categories and retrieve therir ids
  $categorySlugs = ['cat1','cat2','cat3'];
  $craftCategoryIds = [];
  foreach ($categorySlugs as $cs) {
      $craftCategoryIds[] = Category::find()-&gt;wpSlug($cs)-&gt;one()-&gt;id;
  }
  
  // get a an asset to be used as a featureImage
  $featureImageId = Asset::find()-&gt;myField('123')-&gt;one()-&gt;id;
  
  // Set the custom field values (including Matrix)
  $fieldValues = [
      'summary' =&gt; 'Some "summary" custom field value...',
      'categories' =&gt; $craftCategoryIds, // &lt;-- this works, categories are assigned
      'featuredImage' =&gt; $featureImageId, // &lt;-- doesn't work, featured image is not set
      'matrixField' =&gt; [
          'new1' =&gt; [
              'type' =&gt; 'blockTypeHandle',
              'fields' =&gt; [
                      // the block's custom field values...
              ],
          ],
          'new2' =&gt; [
              'type' =&gt; 'blockTypeHandle',
              'fields' =&gt; [
                      // the block's custom field values...
              ],
          ],
      ],
  ]);
  
  $entry-&gt;setFieldValues($fieldValues)
  
  // Save the entry
  Craft::$app-&gt;elements-&gt;saveElement($entry);
  </code></pre>
  
Tags: <plugin-development><assets>
Title: How to save Asset field of an Entry programmatically in Craft 3
ThreadText: # How to save Asset field of an Entry programmatically in Craft 3
  
  (Asked by: username_0 on 2018-03-21)
  
  Using [this](https://craftcms.stackexchange.com/questions/21864/how-to-save-matrix-data-programmatically-in-craft-3) 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:
  
  ```php
  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);
  
  ```
  
  **Tags:** plugin-development, assets
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_1 on 2018-03-21. Score: 4 | Accepted answer
  
  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
  
  > **Comments:**
  > **username_2**: Naturally this works for all element types (i.e. Entries/Asset fields). Thanks username_1 - that was driving me crazy.  
  
  ---
  
  