activerecordyii2yii2-modelyii2-validation

Yii2: How to set default attribute values in ActiveRecord?


This may seem like a trivial question, however all of the obvious solutions that I can think of have their own flaws.

What we want is to be able to set any default ActiveRecord attribute value for new records only, in a way that makes it readable before and during validation and does not interfere with derived classes used for search.

The default values need to be set and ready as soon as we instantiate the class, so that (new MyModel)->attr returns the default attr value.

Here are some of the possibilities and the problems they have:

So what is the right way to set default attribute values? Is there any other way without the outlined problems?


Solution

  • 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

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