I have the channel entry to which the matrix block belongs and I have the ID of the block itself. Does anybody know the correct approach for deleting the matrix block on the entry?
Context: module (PHP) not template.
You can use the Elements service to delete any element, including matrix blocks:
use craft\elements\MatrixBlock;
/** @var craft\services\Elements $elementsService */
$elementsService = Craft::$app->getElements();
$myMatrixBlockId = 123;
// delete a matrix block directly
$matrixBlock = MatrixBlock::find()->id($myMatrixBlockId)->one();
$elementsService->deleteElement($matrixBlock, false);
// delete a matrix block by ID
$elementsService->deleteElementById($myMatrixBlockId, null, null, false);
The second argument to deleteElement
(and the fourth argument to deleteElementById
) controls if you want a hard delete (true
) or a soft-delete (false
). A hard delete removes the block from the database completely, while a soft delete keeps it in the database and only marks it as deleted, allowing it to be restored.