1

I want to reset a matrix field to have no blocks in it. In a plugin, I would normally set a matrix field by doing something like this:

$blocks = [];
$i = 1;
foreach ($itemsArray as $item) {
    $blocks['new' . $i] = [
        'type' => 'myBlockTypeHandle',
        'fields' => [
            'someBlockFieldHandle1' => $item['value1'],
            'someBlockFieldHandle2' => $item['value2'],
            'someBlockFieldHandle3' => $item['value3'],
        ],
    ];
    ++$i;
}

$entry->setFieldValues([
    'myMatrixField' => $blocks,
]);
Craft::$app->elements->saveElement($entry);

But I want to do the opposite and set the matrix field to have no blocks. I have tried setting the field to an empty array but it doesn't work:

$entry->setFieldValues([
    'myMatrixField' => [],
]);
Craft::$app->elements->saveElement($entry);

There are no errors on save but the empty array gets ignored and my matrix field still has its data in it. I've tried setting it to empty nested arrays and to null but they all get ignored.

How do I reset a matrix field?

1

Ok I'm a dummy. A matrix block is an element like an Entry, Asset, etc. So I need to delete it like an element instead of treat it like an array:

$blocks = $entry->myMatrixField->all();

if (! empty($blocks)) {

    $elementsService = Craft::$app->getElements();

    foreach ($blocks as $block) {
        /* @var \craft\elements\MatrixBlock $block */

        $elementsService->deleteElement($block);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.