Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 949
robsch Avatar asked Sep 22 '15 11:09

robsch


1 Answers

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

public function rules()
{
    return [
       // ...
       ['attribute', 'default', 'value' => null],
       // ...
    ];
}
like image 126
soju Avatar answered Oct 20 '22 00:10

soju