Add a field callback right before the content is saved/collected inside the transaction during element save #17004
-
I often have the requirement to ensure unique values for an element - kinda like the commerce order number.. Quite frequently I use your sequence table for this. However there is often a struggle when/where to create this unique number. Right now there are several places where / when to create this unique value and all of them are non optimal
Previously I did that during Lines 3745 to 3748 in 2578c97 #16797 my field value will be empty at this point and I don't want to set it to something random. What I basically need is a callback right before the field value is stored in order to increase the sequence value with the ability to throw an exception in case of an error so the increased sequence value will roll back as well leaving no empty values. My only real way right now would be to return a custom value like Thank you |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Your field type could override Alternatively, you could define a new class which implements use craft\base\Serializable;
class MyGeneratedValue implements Serializable
{
public function __construct(
private readonly ?string $value,
) {
}
public function serialize(): string
{
if (!isset($this->value)) {
// define it here
}
return $this->value;
}
} Then have your field type’s use craft\base\ElementInterface;
public function normalizeValue(mixed $value, ?ElementInterface $element): mixed
{
if ($value instanceof MyGeneratedValue) {
return $value;
}
return new MyGeneratedValue($value);
} |
Beta Was this translation helpful? Give feedback.
Your field type could override
isValueEmpty()
and just have it always returnfalse
regardless of the actual value.Alternatively, you could define a new class which implements
craft\base\Serializable
and stores the existing value on a property within it, and generates a new one via itsserialize()
method if it’s null.Then have your field type’s
normalizeValue()
meth…