Skip to content

Commit 07602bf

Browse files
committed
Fix #4249 variants not saving it the SKU auto format caused duplicates
1 parent c6f67e1 commit 07602bf

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Release Notes for Craft Commerce
22

3+
## Unreleased
4+
5+
- Fixed a bug where variants weren’t being saved for product types with a Variant SKU Format that could cause duplicate SKUs. ([#4249](https://github.com/craftcms/commerce/issues/4249))
6+
37
## 5.6.1.1 - 2026-03-27
48

59
- Fixed a bug where PDF Link Duration didn’t save. ([#4265](https://github.com/craftcms/commerce/issues/4265))

src/elements/Variant.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
use craft\helpers\Db;
4343
use craft\helpers\ElementHelper;
4444
use craft\helpers\Html;
45+
use craft\helpers\Sequence;
4546
use craft\helpers\UrlHelper;
4647
use craft\models\FieldLayout;
4748
use Throwable;
@@ -725,6 +726,29 @@ public function updateSku(Product $product): void
725726
$language = Craft::$app->language;
726727
Craft::$app->language = $this->getSite()->language;
727728
$this->sku = Craft::$app->getView()->renderObjectTemplate($type->skuFormat, $this);
729+
730+
// Ensure there isn't a clash with an existing SKU when using auto formats
731+
$skuExists = (new Query())
732+
->select(['sku'])
733+
->from(Table::PURCHASABLES)
734+
->where(['sku' => $this->getSku()]);
735+
736+
// Make sure it isn't for the purchasable we are currently saving
737+
if ($this->id) {
738+
$skuExists->andWhere(['not', ['id' => $this->id]]);
739+
}
740+
741+
if ($skuExists->exists()) {
742+
// If there is a clash, we need to append a number to the end.
743+
do {
744+
$seq = Sequence::next('sku::' . $this->sku);
745+
$newSku = $this->sku . '-' . $seq;
746+
$skuExists->andWhere(['sku' => $newSku]);
747+
} while ($skuExists->exists());
748+
749+
$this->sku = $newSku;
750+
}
751+
728752
Craft::$app->language = $language;
729753
}
730754
}

0 commit comments

Comments
 (0)