yiisoft / yii2

Yii 2: The Fast, Secure and Professional PHP Framework
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
14.24k stars 6.91k forks source link

DynamicModel Atribute Declaration #16108

Closed buttflattery closed 6 years ago

buttflattery commented 6 years ago

As per documentation for the DynamicModel under Adhoc Validation example hows attributes being passed to the model as new DynamicModel(compact('attribute_name_1','attribute_name_2')) where as this does not work and does not declare the model attributes

What steps will reproduce the problem?

$model = new DynamicModel(compact('finance_needed'));

print_r($model->attributes);

What is the expected result?

it should display

[
'finance_needed=>''
]

What do you get instead?

It shows empty array as if no attributes were declared if i try to validate like this it throws the exception

Setting unknown property: yii\base\DynamicModel::finance_needed

Additional info

If i change it to a normal array like below

new DynamicModel(['finance_needed']);

then it works correctly and declare the attribute for the model

Q A
Yii version 2.0.15?
PHP version 5.6.35-1+ubuntu14.04.1+deb.sury.org+1
Operating system ubuntu14.04.1
alex-code commented 6 years ago

The docs could be a bit misleading for anyone who just copy pastes the example.

It uses compact which will ignore any variables it can't find.

This won't work

{
  $model = new DynamicModel(compact('finance_needed'));
  print_r($model->attributes);
}

While this will

{
  $finance_needed = 'my value here';
  $model = new DynamicModel(compact('finance_needed'));
  print_r($model->attributes);
}

If you don't need to provide values during initialisation then just pass the attribute name as you have new DynamicModel(['finance_needed']);

samdark commented 6 years ago

https://github.com/yiisoft/yii2/commit/033f2b4a13d31a5f202810eef9fad6e2c2f5e7bd

samdark commented 6 years ago

Thanks for reporting.