Answers.Body: <p>Matrix blocks are elements like entries themselves. There's an API for them even. You will want to load your matrix data into an array of <a href="http://buildwithcraft.com/docs/templating/matrixblockmodel" rel="nofollow"><code>MatrixBlockModels</code></a>, then run <a href="http://buildwithcraft.com/docs/apis/matrixservice#saveBlock" rel="nofollow"><code>craft()-&gt;matrix-&gt;saveBlock</code></a> on each one. You will need the field id and type id for the block in question, which you can get from the Fields Service (you'll need to look this up in the Craft source code) and <a href="http://buildwithcraft.com/docs/apis/matrixservice" rel="nofollow">Matrix Service</a>. You will also need the owner which can be set by running <code>setOwner</code> on the <code>MatrixBlockModel</code> and handing it the entry model.</p>
  
  <p>It gets more involved, but this should give you a start.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-07-17T14:18:45.617Z
Answers.LastActivityDate: 2014-07-17T14:18:45.617Z
Answers.UserDisplayName: Bryan Redeagle
Answers.Body: <p>Ok there are two parts to this question - how to save relationships and how to save matrix blocks whilst saving an entry.</p>
  
  <p><strong>How to save relationships</strong></p>
  
  <p>To deal with the first, it is my understanding that the entries need to exist first so you may need to create them if they aren't already. Then all you need to do is pass an array of entry ids to the relevant field:</p>
  
  <pre><code>$entry-&gt;getContent()-&gt;entriesField = $targetEntryIds;
  </code></pre>
  
  <p><strong>How to save matrix blocks whilst saving an entry</strong></p>
  
  <p>Bryan is correct in that you can create and save blocks all by themselves, however if all you want to do is add some blocks to a new entry then the following setup will work just fine:</p>
  
  <pre><code>$matrixData = array();
  
  $matrixData['new1'] = array(
    'type' =&gt; 'blockType',
    'enabled' =&gt; true,
    'fields' =&gt; array(
      'fieldOne' =&gt; 'Some string or data',
      'fieldTwo' =&gt; '12'
    )
  );
  
  // You can repeat this part for each block you want to add, just increment the newN number.
  $matrixData['new2'] = array(
    'type' =&gt; 'blockType',
    'enabled' =&gt; true,
    'fields' =&gt; array(
      'fieldOne' =&gt; 'Some more text',
      'fieldTwo' =&gt; '16'
    )
  );
  
  // set matrix field to contain those blocks before saving the entry
  $entry-&gt;setContentFromPost(array('matrixField' =&gt; $matrixData));
  </code></pre>
  
  <p><a href="https://gist.github.com/brandonkelly/8149062">This gist</a> from Brandon explains all on the Matrix front, I am merely repeating most of it here for your benefit.</p>
  
  <p>Best of luck!</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2019-03-28T21:00:49.770Z
Answers.Text: When using this on an entry it adds the new block as expected but it will delete any old blocks that were present. How can we avoid this?
Answers.UserDisplayName: Radmation
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-07-17T14:48:03.390Z
Answers.LastActivityDate: 2014-07-17T14:48:03.390Z
Answers.UserDisplayName: Josh Angell
Body: <p>I have a section of type channel with a matrix field. I want to know how I would save the matrix content while I save the entry as well. I know I can save the entry as follows:</p>
  
  <pre><code>    $entry = new EntryModel();
      $content = array('productName' =&gt; $data[0]['Product'][0], 'productQuantities' =&gt; $data[0]['Product'][1]);
      $entry-&gt;sectionId = 10;
      $entry-&gt;typeId = 10;
      $entry-&gt;postDate   = date('Y-m-d');
      $entry-&gt;authorId   = 1;
  
      $result = $entry-&gt;setContentFromPost($content);
  
      $entry-&gt;getContent()-&gt;title = "Fancy Title";
  
      craft()-&gt;entries-&gt;saveEntry($entry);
  </code></pre>
  
  <p>The content variable above stores the content matrix block for this entry should have. So the Matrix has two fields within it one is of entry type and the other is numerical. I want to set these two fields before "craft()->entries->saveEntry($entry);". Please someone tell me how this is possible. I know for the entries type field I have to create a relation but please help me by letting me know how to do that as well as how to create this new matrix block containing that relation etc.</p>
  
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2021-09-15T16:53:36.083Z
Comments.Text: If you've come here looking for a Craft 3 answer see https://craftcms.stackexchange.com/questions/1101/how-to-save-a-matrix-content-of-a-new-entry-in-my-plugin
Comments.UserDisplayName: Alex Kendrick
Tags: <plugin-development><entries><matrix>
Title: How to save a matrix content of a new entry in my plugin?
ThreadText: # How to save a matrix content of a new entry in my plugin?
  
  (Asked by: username_0 on 2014-07-15)
  
  I have a section of type channel with a matrix field. I want to know how I would save the matrix content while I save the entry as well. I know I can save the entry as follows:
  
  ```
      $entry = new EntryModel();
      $content = array('productName' => $data[0]['Product'][0], 'productQuantities' => $data[0]['Product'][1]);
      $entry->sectionId = 10;
      $entry->typeId = 10;
      $entry->postDate   = date('Y-m-d');
      $entry->authorId   = 1;
  
      $result = $entry->setContentFromPost($content);
  
      $entry->getContent()->title = "Fancy Title";
  
      craft()->entries->saveEntry($entry);
  
  ```
  
  The content variable above stores the content matrix block for this entry should have. So the Matrix has two fields within it one is of entry type and the other is numerical. I want to set these two fields before "craft()->entries->saveEntry($entry);". Please someone tell me how this is possible. I know for the entries type field I have to create a relation but please help me by letting me know how to do that as well as how to create this new matrix block containing that relation etc.
  
  **Tags:** plugin-development, entries, matrix
  
  > **Comments:**
  > **username_1**: If you've come here looking for a Craft 3 answer see https://craftcms.stackexchange.com/questions/1101/how-to-save-a-matrix-content-of-a-new-entry-in-my-plugin  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_3 on 2014-07-17. Score: 5 | Accepted answer
  
  Ok there are two parts to this question - how to save relationships and how to save matrix blocks whilst saving an entry.
  
  **How to save relationships**
  
  To deal with the first, it is my understanding that the entries need to exist first so you may need to create them if they aren't already. Then all you need to do is pass an array of entry ids to the relevant field:
  
  ```
  $entry->getContent()->entriesField = $targetEntryIds;
  
  ```
  
  **How to save matrix blocks whilst saving an entry**
  
  username_2 is correct in that you can create and save blocks all by themselves, however if all you want to do is add some blocks to a new entry then the following setup will work just fine:
  
  ```
  $matrixData = array();
  
  $matrixData['new1'] = array(
    'type' => 'blockType',
    'enabled' => true,
    'fields' => array(
      'fieldOne' => 'Some string or data',
      'fieldTwo' => '12'
    )
  );
  
  // You can repeat this part for each block you want to add, just increment the newN number.
  $matrixData['new2'] = array(
    'type' => 'blockType',
    'enabled' => true,
    'fields' => array(
      'fieldOne' => 'Some more text',
      'fieldTwo' => '16'
    )
  );
  
  // set matrix field to contain those blocks before saving the entry
  $entry->setContentFromPost(array('matrixField' => $matrixData));
  
  ```
  
  [This gist](https://gist.github.com/brandonkelly/8149062) from Brandon explains all on the Matrix front, I am merely repeating most of it here for your benefit.
  
  Best of luck!
  
  > **Comments:**
  > **username_4**: When using this on an entry it adds the new block as expected but it will delete any old blocks that were present. How can we avoid this?  
  
  ---
  
  ### Answer by username_2 on 2014-07-17. Score: 4
  
  Matrix blocks are elements like entries themselves. There's an API for them even. You will want to load your matrix data into an array of [`MatrixBlockModels`](http://buildwithcraft.com/docs/templating/matrixblockmodel), then run [`craft()->matrix->saveBlock`](http://buildwithcraft.com/docs/apis/matrixservice#saveBlock) on each one. You will need the field id and type id for the block in question, which you can get from the Fields Service (you'll need to look this up in the Craft source code) and [Matrix Service](http://buildwithcraft.com/docs/apis/matrixservice). You will also need the owner which can be set by running `setOwner` on the `MatrixBlockModel` and handing it the entry model.
  
  It gets more involved, but this should give you a start.
  
  
  ---
  
  