d-nnis
d-nnis

Reputation: 81

Yii: Compute custom field for model

I find the documentation and tutorial of Yii 2.0 a bit short.

In a Yii 2.0 Model I would like to add a hidden field with a computed value, let's call it def_id. The model contains fields such as firstname, lastname, email etc. The computed value would be some combination of those three fields. (It is supposed to be some custom type of the logical, unique auto-increment.)

My question: where do I compute def_id with the other given fields so that Create and Update will write def_id into the database-table?

Upvotes: 0

Views: 45

Answers (1)

Mihai P.
Mihai P.

Reputation: 9367

There is no hidden field in the model, there are just fields. If it is calculated field you do not have to even show it on screen so there is no point in putting in a hidden field.

You can however add it to the before save function for the model

public function beforeSave() 
{
    if ($this->isNewRecord) {
        //calculate what you need            
    } else {
        //recalculate if needed
    }
    return parent::beforeSave();
}

Upvotes: 2

Related Questions