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!

user2511599
  • 796
  • 1
  • 13
  • 38
  • 1
    Have you tried assigning the model attributes with $model->load(Yii::$app->request->post()) ? – WeSee Feb 22 '16 at 06:26
  • What would be the difference to `$model->load($_POST)`? – user2511599 Feb 22 '16 at 18:01
  • 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. – WeSee Feb 22 '16 at 20:05

1 Answers1

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'],
    ];
}
Jørgen
  • 3,467
  • 6
  • 33
  • 49
  • Crazy! It works! The one that wonders me, why we don't become a warning or an error message. Something. But okay. – user2511599 Feb 22 '16 at 18:01