Yii2: Prevent empty string in attribute of ActiverRecord Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Yii2: Prevent empty string in attribute of ActiverRecord without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

Answer

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

public function rules()
{
    return [
       // ...
       ['attribute', 'default', 'value' => null],
       // ...
    ];
}
We are here to answer your question about Yii2: Prevent empty string in attribute of ActiverRecord - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji