Yii2: How to set default attribute values in ActiveRecord?

There's two ways to do this.

$model => new Model();

Now $model has all the default attributes from the database table.

Or in your rules you can use:

[['field_name'], 'default', 'value'=> $defaultValue],

Now $model will always be created with the default values you specified.

You can see a full list of core validators here http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html


This is a hangup with Yii's bloated multi-purpose ActiveRecords

In my humble opinion the form models, active records, and search models would be better off split into separate classes/subclasses

Why not split your search models and form models?

abstract class Creature extends ActiveRecord {
    ...
}

class CreatureForm extends Creature {

    public function init() {
        parent::init();
        if ($this->isNewRecord) {
            $this->number_of_legs = 4;
        }
    }
}

class CreatureSearch extends Creature {

    public function search() {
        ...
    }
}

The benefits of this approach are

  • You can easily cater for different validation, set up and display cases without resorting to a bunch of ifs and switches
  • You can still keep common code in the parent class to avoid repetition
  • You can make changes to each subclass without worrying about how it will affect the other
  • The individual classes don't need to know about the existence of any of their siblings/children to function correctly

In fact, in our most recent project, we are using search models that don't extend from the related ActiveRecord at all