-->

Yii2 non-DB (or virtual) attribute isn't popul

2019-09-16 14:24发布

问题:

I've defined a virtual attribute:

class ContactForm extends Model {

    public $name; // is not a DB field

I've noticed that it is not populated during massive assignment (after submitting the form, in $model->load($_POST)). Can it be somehow populated along with DB attributes? Or am I doing something wrong that is not populated however it should be? Thanks!

回答1:

Docs: Massive Assignments

Like normal models, Active Record instances also enjoy the massive assignment feature. Using this feature, you can assign values to multiple attributes of an Active Record instance in a single PHP statement, like shown below. Do remember that only safe attributes can be massively assigned, though.

Docs: Safe Attributes

For this reason, a special validator aliased safe is provided so that you can declare an attribute to be safe without actually validating it. For example, the following rules declare that both title and description are safe attributes.

You have to do some sort of validation on your attribute, if you don't have any validation needs - define it as safe.

public function rules()
{
    return [
        [['name'], 'safe'],
    ];
}