I'm creating a cron job to automatically import new entries (vacancies).
I have an entry that I use as a template with some standard data fields and matrix fields. If it's an entry that has not been imported before I create a new entry as a duplicate of the template entry.
$entry = Craft::$app->getElements()->duplicateElement($entryTemplate);
The template already has the matrix blocks but only placeholder data that I want to overwrite like this:
// existing matrix fields (already created or from template)
$matrixBlocks = $entry->myMatrixBlock;
/** @var MatrixBlock $matrixBlock */
foreach($matrixBlocks as $matrixBlock) {
$matrixBlock->setFieldValues(['contactText' => 'random text']);
$success = Craft::$app->elements->saveElement($matrixBlock);
}
The strange thing is that the ownerId of the matrixBlock isn't the value of the $entry->id nor is it the value of the template id. It generated a new ownerId. It works correctly when I import it a second time because the owner id is now correct.