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?
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It only takes a minute to sign up.
Sign up to join this communityThe 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.