I'm trying to set some defaults for newly created products. That is, when a new product is created, I want to set some settings to specific default values, but users should be allowed to change those.
use craft\commerce\elements\Product;
use craft\events\ModelEvent;
use yii\base\Event;
Event::on(
Product::class,
Product::EVENT_BEFORE_SAVE,
function (ModelEvent $e) {
if (!$e->isNew) {
return;
}
$e->sender->freeShipping = true;
$e->sender->defaultVariant->hasUnlimitedStock = true;
},
);
This is working, but the default values are only set when the product is first saved. This means that the user presses + New Product from the product index list, then sees the full product edit form without my defaults. Only after the users clicks Save is the hook triggered, and my default values are set. So if the user has already changed those options, they are overwritten.
I think the problem is that Commerce products don't have full draft support. For entries, the default values are set before the user sees the edit form for the first time, because pressing + New entry creates an unpublished draft in the database immediately, triggering the EVENT_BEFORE_SAVE
hook. But products don't do this, they present an empty edit form with nothing saved in the database before the first save, so the hook isn't triggered.
This also presents another problem: If there are validation errors, the hook triggers multiple times, because the product is always new ($e->isNew
) until it is saved successfully. So the default values will be set multiple times, overwriting the values set by the editor, until the product is saved successfully at least once.
Is there another hook I could use, or another way to solve this?
- Craft 4.4.7.1
- Craft Commerce 4.2.7