Answers.Body: <p>Just an additional note:</p>
  <p>If you want to append certain elements to your matrix field instead of overwriting them all you have to do</p>
  <h3>Update Craft 4.0</h3>
  <p>there is a new <code>sortOrder</code> key that makes my previous answer obsolete.</p>
  <pre class="lang-php prettyprint-override"><code>// grab all existing ids
  $existingIds = $element-&gt;getFieldValue('matrixField')-&gt;ids();
  // add a new block to the ids
  $existingIds[] = 'new1';
  
  $element-&gt;setFieldValue('matrixField', [
      'sortOrder' =&gt; $existingIds,
      'blocks' =&gt; [
          'new1' =&gt; [
              'type' =&gt; 'blockTypeHandle',
              'fields' =&gt; [
                  // the blocks custom field values...
              ]
          ]
      ]
  ]);
  // Save the entry
  Craft::$app-&gt;elements-&gt;saveElement($element);
  </code></pre>
  <h3>Old answer for Craft 3 (first versions &lt; 3.6)</h3>
  <p>Just an additional note:</p>
  <p>If you want to append certain elements to your matrix field instead of overwriting them all you have to do</p>
  <pre class="lang-php prettyprint-override"><code>/** @var \craft\fields\Matrix $field */
  $field = Craft::$app-&gt;getFields()-&gt;getFieldByHandle('matrixField');
  
  // get the existing matrixField Value, keep in mind, this is a Query and not an array
  $existingMatrixQuery = $element-&gt;getFieldValue('matrixField');
  
  // serialize the data in order to get an array like Brandon Kelly
  // created in his answer
  $serializedMatrix = $field-&gt;serializeValue($existingMatrixQuery, $element);
  
  // append the new blocks to the existing array
  $serializedMatrix['new1'] = [
      'type' =&gt; 'blockTypeHandle',
      'fields' =&gt; [
          // the block's custom field values...
      ]
  ];
  
  $element-&gt;setFieldValue('matrixField', $serializedMatrix);
  
  // Save the entry
  Craft::$app-&gt;elements-&gt;saveElement($element);
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2019-09-01T05:51:58.577Z
Answers.Text: This is perfect, thanks Robin! It's icing on the cake that Brandon has baked. :)
Answers.UserDisplayName: Lindsey D
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-05-02T08:24:13.747Z
Answers.LastActivityDate: 2024-02-29T09:17:27.630Z
Answers.LastEditDate: 2024-02-29T09:17:27.630Z
Answers.UserDisplayName: Robin Schambach
Answers.Body: <p>Saving Matrix fields programmatically got a lot easier in Craft 3 thanks to all the content refactoring.</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(),
  ]);
  
  // Set the custom field values (including Matrix)
  $entry-&gt;setFieldValues([
      'summary' =&gt; 'Some "summary" custom field value...',
      '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...
              ],
          ],
      ],
  ]);
  
  // Save the entry
  Craft::$app-&gt;elements-&gt;saveElement($entry);
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-05-10T13:00:11.533Z
Answers.Text:  That still works in Craft CMS 4 (as of writing I am using 4.4.x). Just in case someone is asking if that's only a Craft 3 thing. :)
Answers.UserDisplayName: Arvid
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-09-07T17:41:22.220Z
Answers.LastActivityDate: 2017-09-07T17:41:22.220Z
Answers.UserDisplayName: Brandon Kelly
Body: <p>How can you programmatically save an entry that has a Matrix field in Craft 3?</p>
  
  <p>(Something like <a href="https://gist.github.com/brandonkelly/8149062" rel="noreferrer">this gist</a> for Craft 2)</p>
  
Tags: <plugin-development><matrix><craft3>
Title: How to save Matrix data programmatically in Craft 3
ThreadText: # How to save Matrix data programmatically in Craft 3
  
  (Asked by: username_0 on 2017-09-07)
  
  How can you programmatically save an entry that has a Matrix field in Craft 3?
  
  (Something like [this gist](https://gist.github.com/username_0/8149062) for Craft 2)
  
  **Tags:** plugin-development, matrix, craft3
  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_0 on 2017-09-07. Score: 24 | Accepted answer
  
  Saving Matrix fields programmatically got a lot easier in Craft 3 thanks to all the content refactoring.
  
  ```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(),
  ]);
  
  // Set the custom field values (including Matrix)
  $entry->setFieldValues([
      'summary' => 'Some "summary" custom field value...',
      'matrixField' => [
          'new1' => [
              'type' => 'blockTypeHandle',
              'fields' => [
                  // the block's custom field values...
              ],
          ],
          'new2' => [
              'type' => 'blockTypeHandle',
              'fields' => [
                  // the block's custom field values...
              ],
          ],
      ],
  ]);
  
  // Save the entry
  Craft::$app->elements->saveElement($entry);
  
  ```
  
  > **Comments:**
  > **username_3**:  That still works in Craft CMS 4 (as of writing I am using 4.4.x). Just in case someone is asking if that's only a Craft 3 thing. :)  
  
  ---
  
  ### Answer by username_1 on 2018-05-02. Score: 13
  
  Just an additional note:
  
  If you want to append certain elements to your matrix field instead of overwriting them all you have to do
  
  ### Update Craft 4.0
  
  there is a new `sortOrder` key that makes my previous answer obsolete.
  
  ```php
  // grab all existing ids
  $existingIds = $element->getFieldValue('matrixField')->ids();
  // add a new block to the ids
  $existingIds[] = 'new1';
  
  $element->setFieldValue('matrixField', [
      'sortOrder' => $existingIds,
      'blocks' => [
          'new1' => [
              'type' => 'blockTypeHandle',
              'fields' => [
                  // the blocks custom field values...
              ]
          ]
      ]
  ]);
  // Save the entry
  Craft::$app->elements->saveElement($element);
  
  ```
  
  ### Old answer for Craft 3 (first versions < 3.6)
  
  Just an additional note:
  
  If you want to append certain elements to your matrix field instead of overwriting them all you have to do
  
  ```php
  /** @var \craft\fields\Matrix $field */
  $field = Craft::$app->getFields()->getFieldByHandle('matrixField');
  
  // get the existing matrixField Value, keep in mind, this is a Query and not an array
  $existingMatrixQuery = $element->getFieldValue('matrixField');
  
  // serialize the data in order to get an array like username_0
  // created in his answer
  $serializedMatrix = $field->serializeValue($existingMatrixQuery, $element);
  
  // append the new blocks to the existing array
  $serializedMatrix['new1'] = [
      'type' => 'blockTypeHandle',
      'fields' => [
          // the block's custom field values...
      ]
  ];
  
  $element->setFieldValue('matrixField', $serializedMatrix);
  
  // Save the entry
  Craft::$app->elements->saveElement($element);
  
  ```
  
  > **Comments:**
  > **username_2**: This is perfect, thanks username_1! It's icing on the cake that username_0 has baked. :)  
  
  ---
  
  