robsch
robsch

Reputation: 9728

Yii2: Prevent empty string in attribute of ActiverRecord

What's the best way to prevent that an empty string gets inserted into a field of an MySQL's InnoDB table? Allowed values are strings with more than zero characters or NULL.

I'm asking that because ActiveRecord model objects often get loaded with view's form data which don't know and thus don't send NULL values. In such a case I'd prefer that a NULL gets stored instead of the empty string.

Should I define a rule? Should I implement a setter? Use a trigger?

Upvotes: 9

Views: 3779

Answers (1)

soju
soju

Reputation: 25312

You should simply use the default validator, add this rule to your model :

public function rules()
{
    return [
       // ...
       ['attribute', 'default', 'value' => null],
       // ...
    ];
}

Upvotes: 15

Related Questions