How do I add a block to a matrix that already has content via a plugin? I'm building a plugin that adds blocks to a matrix in an entry from the front end. I got it up and running by following the answer in this post: 

How to save a matrix content of a new entry in my plugin?

How do I check if the matrix already has blocks when I fetch the entry? And then, once I know if the matrix already has blocks, how do I retain the existing data while saving new blocks via the plugin?
You can save Matrix blocks directly, without having to re-save the entry.

Craft 2

Use MatrixService::saveBlock():



$block = new MatrixBlockModel();
$block-&gt;fieldId = 5;
$block-&gt;ownerId = 100;
$block-&gt;ownerLocale = 'en_us';
$block-&gt;typeId = 2;
$block-&gt;sortOrder = 10;

$block-&gt;setContentFromPost(array(
    'fieldHandle' =&gt; 'value',
    // ...
));

$success = craft()-&gt;matrix-&gt;saveBlock($block);


Craft 3

Use craft\services\Elements::saveElement():

use Craft;
use craft\elements\MatrixBlock;

$block = new MatrixBlock();
$block-&gt;fieldId = 5;
$block-&gt;ownerId = 100;
$block-&gt;siteId = 1;
$block-&gt;typeId = 2;
$block-&gt;sortOrder = 10;

$block-&gt;setFieldValues([
    'fieldHandle' =&gt; 'value',
    // ...
]);

$success = Craft::$app-&gt;elements-&gt;saveElement($block);