set default value for active record field ?

I have class Book extends from ActiveRecord and a required tax_rate field




class Book extends \yii\db\ActiveRecord

{

    public function rules()

    {

        return [

            

            ['tax_rate', 'required']

        ];

    }




I want to set tax_rate to 0 when I create a new instance of Book





$book = new Book(); # tax_rate should be 0



The reason is when I submit the form, I dont want to see "Tax Rate can not be blank".

I know about "default" in validation, but a field is only get the default value after it passes the validation. So using "default" does not fix my issue.

You can override init() method:




class Book extends \yii\db\ActiveRecord

{

    public function init()

    {

        parent::init();

    

        $this->tax_rate = 0;

    }



1 Like

perfect, thanks for sharing :)

p/s: didnt know you wrote Yii2 book. iam going to check it out