How to save a matrix content of a new entry in my plugin? 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' =&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);


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.
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-&gt;getContent()-&gt;entriesField = $targetEntryIds;


How to save matrix blocks whilst saving an entry

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:

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


This gist from Brandon explains all on the Matrix front, I am merely repeating most of it here for your benefit.

Best of luck!