8

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?

Stephen Bowling
  • 712
  • 3
  • 12

1 Answers1

13

You can save Matrix blocks directly, without having to re-save the entry.

Craft 2

Use MatrixService::saveBlock():

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

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

$success = craft()->matrix->saveBlock($block);

Craft 3

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

use Craft;
use craft\elements\MatrixBlock;

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

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

$success = Craft::$app->elements->saveElement($block);
Brandon Kelly
  • 34,307
  • 2
  • 71
  • 137
  • 1
    Thanks, that worked for me.

    Here's a gist that shows how this can be used to create a new entry if there isn't one for the block to be added to yet if anyone else needs to do this: https://gist.github.com/bwlng/5c0bdeff62fabe247c87

    Would resaving the entry after adding all the blocks update the search keywords?

    – Stephen Bowling Jul 26 '14 at 01:15
  • @StephenBowling Yes that’s a possibility. Just updated the code example showing how you could re-save the entry's content after saving the new matrix block. – Brandon Kelly Jul 27 '14 at 15:03
  • @BrandonKelly how has this changed in Craft 3? I don't see a MatrixBlockModel. – cmal Nov 20 '18 at 21:49
  • 1
    @cmal just updated my answer for Craft 3. – Brandon Kelly Nov 21 '18 at 13:41