arkxl
arkxl

Reputation: 13

Yii2 $model->_attributes assignment does not work in new version

I inherited a project that was created with Yii2, ver. 2.0.4, with the task to update said project to a more current version of Yii2 (2.0.15) because of the incompatibility of the older one with PHP 7.2+.

I noticed that there is a lot of use of assigning arrays to a model:

$model->_attributes = $array;

With the new version this results in an exception

'yii\base\UnknownPropertyException' with message 'Setting unknown property: app\models\model::_attributes'

For the time being I created a workaround with the following function:

function customSetAttributes(&$model, $array) {
    foreach($model->attributeLabels() as $model_key => $model_label) {
        if(!isset($array[$model_key])) continue;
        $model->$model_key = $array[$model_key];
    }
}

Also, the getter function now has a similar issue.

What I would like to know:

Upvotes: 1

Views: 255

Answers (1)

rob006
rob006

Reputation: 22144

ActiveRecord::$_attributes was always private and never should be used in this way. I guess that previous developer edited framework core files in vendor directory and make this property protected/public.

You may try to emulate this behavior by creating virtual attribute using getter and setter:

public function get_attributes() {
    return $this->getAttributes();
}

public function set_attributes($values) {
    $this->setAttributes($values, false);
}

But this will not always work and it is more like an ugly hack to make crappy code work. I strongly suggest to fix code to use setAttributes() instead of _attributes.

Also you should compare yii2 package from vendor directory with source from https://github.com/yiisoft/yii2-framework/releases/tag/2.0.4 - you may find more places where core was edited.

Upvotes: 3

Related Questions