Yii2 non-DB (or virtual) attribute isn't populated during massive assignment?
Asked Answered
S

1

1

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!

Shaver answered 21/2, 2016 at 23:30 Comment(3)
Have you tried assigning the model attributes with $model->load(Yii::$app->request->post()) ?Salbu
What would be the difference to $model->load($_POST)?Shaver
Looking ar https://github.com/yiisoft/yii2/blob/master/framework/web/Request.php#L453 in an ordinary form there is probably (?) no difference but it is the Yii2-way of doing things. In case you have a application/json request, there are differences.Salbu
S
4

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'],
    ];
}
Semiliquid answered 22/2, 2016 at 7:16 Comment(1)
Crazy! It works! The one that wonders me, why we don't become a warning or an error message. Something. But okay.Shaver

© 2022 - 2024 — McMap. All rights reserved.