I'm trying to validate a custom Element in my Craft 3 plugin.
Where should I be putting my validation rules?
I have two classes: one for the Element
, one for the ActiveRecord
(e.g. Invoice
and InvoiceRecord
).
One of the requirements is that one of its field (e.g. number
) has to be unique.
If I override rules()
on the Element, the validation occurs normally but the unique
rule throws an error:
Call to undefined method Invoice::getDb()
Now if I try to add the unique
rule to my Record's rule()
override, it does seem to fail validation and prevent saving the record, but no validation error is thrown (Craft flashes the "saved successfully" message and returns to the element index, but without the new/updated element).
I understand that the record's validation is called only in afterSave
, so technically validation has already been done:
public function afterSave(bool $isNew)
{
if ($isNew)
{
$record = new InvoiceRecord();
$record->id = $this->id;
}
else
{
$record = InvoiceRecord::findOne($this->id);
}
$record->number = $this->number; // Has to be unique
$record->save();
parent::afterSave($isNew);
}
But I don't understand how to get my validation working for something rather simple.
I can't find anything about validation in the Craft 3 plugin docs or migration docs from Craft 2, does anybody know?