Failed to set unsafe attribute in User model

Hi all.

I am new to Yii2, but I’ve got some experience in PHP. I´ve found the framework great so far, but there´re some things I am still struggling with. I did some research prior to come here, but it may well be I’ve just missed something very simple as I haven´t found an answer yet.

I got Yii2 Advanced App and installed it, ran a migration for the user table and then I wanted to add some fields to that table. For example, a field called "name" for the user to fill up his name. I wrote another migration and everything went well.

Then I add that new field to the User views and it shows ok, so I add a rule in the User model for it, for example:




public function rules() {

        return [

            [['password', 'passwordrepeat'], 'required', 'on' => ['admin-create']], //This works great when using the           scenario

            [['username', 'name'], 'required'],

            ['name', 'string', 'max' => 255],

            ['name', 'trim']

            [...]



I have some data in the user db table, so I go to update a user. I can update the "username", but when I change the "name" field it just keeps the same without any warning. Once I go to the debugger, I find this:

Failed to set unsafe attribute ‘name’ in ‘backend\models\User’.

I don´t think "name" attribute should be "safe" at all, as far as I understand the docs. I think I am validating it via those rules, but it refuses to update. Any ideas?

Thanks in advance.

First of all, restart PHP (or your webserver) to make sure DB schema is not cached.

Then post your model code here. What’s interesting is full code of rules() method, setX() methods, public properties.

Thanks for the answer :)

Trying things around, I found the cause for the problem. I was defining my scenarios in the model like this:




     /**

     * @inheritdoc

     */

    public function scenarios() {

        return [

            'admin-create' => ['username', 'email', 'password', 'passwordrepeat', 'status', 'role'],

            'admin-update' => ['username', 'email', 'password', 'passwordrepeat', 'status', 'role']

        ];

    }



So It seems that I am setting which fields must be considered for validation in each scenario, including fields that are “not there” and declared as Model public properties (like “password” or “passwordrepeat”). It makes sense to strictly encapsulate model field validation for specific scenarios like that, but it is a bit misleading for a newbie like me :P

I struggled a bit to find an easy explanation, but I´ve found a good one in "The Definitive Guide to Yii 2.0" section 1.2.9

Thanks again for the answer and I hope to be of some help around here eventually.