Getting an exception "Attempting to duplicate an unsaved element." when publishing a draft that contains a matrix that was not modified in the draft but was modified in the source entry (has a yellow M).
I have found that clearing the cache at this point prevents this error, but I do not fully understand the ramifications of clearing the cache at this point.
public function duplicateBlocks(MatrixField $field, ElementInterface $source, ElementInterface $target, bool $checkOtherSites = false)
{
$elementsService = Craft::$app->getElements();
/** @var MatrixBlockQuery $query */
$query = $source->getFieldValue($field->handle);
/* add this line to prevent "Attempting to duplicate an unsaved element." */ $query->clearCachedResult();
/** @var MatrixBlock[] $blocks */
if (($blocks = $query->getCachedResult()) === null) {
$blocksQuery = clone $query;
$blocks = $blocksQuery->anyStatus()->all();
}
$newBlockIds = [];

Able to reproduce this, and will look into it.
Figured out this temporary workaround that doesnt require an internal code modification and works for any field type that has similar issues, like super table.
@brandonkelly can you think of any obvious reason this could cause probs if we put this into service while awaiting a permanent fix?
use craft\elements\db\ElementQuery;
use craft\events\ElementEvent;
use craft\services\Elements;
use yii\base\Event;
Event::on(
Elements::class,
Elements::EVENT_AFTER_SAVE_ELEMENT,
function(ElementEvent $event) {
$duplicatedElement = $event->element->duplicateOf;
if(!$duplicatedElement || !$duplicatedElement->getFieldLayout()) {
return;
}
foreach ($duplicatedElement->getFieldValues() as $query) {
if($query instanceof ElementQuery) {
$query->clearCachedResult();
}
}
}
);
The root issue here is that Matrix block changes weren’t getting propagated to drafts when Current revision changes were getting merged into the draft, leaving the Matrix field in a bit of a weird state for the draft. Just fixed that for the next release, which also fixes the “Attempting to duplicate an unsaved element” error. Going to PR similar fixes to Super Table and Neo now.
Craft 3.6.11.2 is out now with the fix for Matrix fields ✨