1

I've got $entryA with a Matrix field.

I want to programatically create a new $entryB and copy the Matrix field from $entryA to $entryB. How do I go about this?

1 Answer 1

2

The blocks in a Matrix field are all elements, with their owner ID set to the corresponding entry. This is how you could copy them (untested):

use craft\elements\MatrixBlock;

foreach ($entryA->matrixFieldHandle->all() as $matrixBlockA) {
    $matrixBlockB = new MatrixBlock();
    $matrixBlockB->fieldId = $matrixBlockA->fieldId;
    $matrixBlockB->typeId = $matrixBlockA->typeId;
    $matrixBlockB->ownerId = $entryB->id;
    $matrixBlockB->siteId = $entryB->siteId;
    $matrixBlockB->enabled = $matrixBlockA->enabled;
    $matrixBlockB->sortOrder = $matrixBlockA->sortOrder;
    $matrixBlockB->setFieldValues($matrixBlockA->getFieldValues());

    Craft::$app->getElements()->saveElement($matrixBlockB);
}

Things can get tricky if you have multiple sites and the entries do or do not get propagated (etc), but this is how it works in a nutshell.

For the above code to work, you have to first save Entry B, to get an entry ID for it. So, create Entry B, fill 'normal' fields, save Entry B, create Matrix B, save Matrix B.

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.