Reputation: 2499
In my Yii2 project, I have related models. Example: A model Customer would have an attribute address_id that relates to another model Address. In the Customer model have the exist validator that checks that the row exists in the address table.
Typically, on create or update, this validation is ignored if address = null
. My problem is that sometimes FE would send the address = 0
indicating the absence of an address.
In this case, I need to not only ignore validation, but to set address = null
. This can be done beforeSave of course, but I'm trying to check if there's some built-in way through which I can do this
Upvotes: 1
Views: 619
Reputation: 6456
You can use the filter validator for normalization of an input data. For example:
class Customer extends ActiveRecord
{
public function rules()
{
return [
['address_id', 'filter', 'filter' => function ($value) {
return $value == 0 ? null : $value;
}],
// other validators
];
}
}
Upvotes: 2