Moutinho
Moutinho

Reputation: 349

Yii2 - Attributes in DynamicModel

I created a yii\base\DynamicModel in controller and I have one form with attributes from this model. I need access these attributes after submitting form in controller.

controller.php

public function actionCreate()
{
    $model = new DynamicModel([
        'name', 'age', 'city'
    ]);

    if($model->load(Yii::$app->request->post())){
        $model->age = $model->age + 5;
        /*
         * code....
         * */
        return $this->redirect(['index']);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

But $model->age, $model->name etc. returns nothing.

I could only access the attribute this way: Yii::$app->request->get('DynamicModel')['age']

What is the correct way to access these attributes?

Upvotes: 2

Views: 3215

Answers (1)

rob006
rob006

Reputation: 22174

You need to configure validation rules in order to automatically load attributes by load():

$model = new DynamicModel(['name', 'age', 'city']);
$model->addRule(['name', 'age', 'city'], 'safe');

if ($model->load(Yii::$app->request->post())) {
// ...

Using safe will accept values as is without actual validation, but you may consider adding real validation rules to ensure correct state of your model.

Upvotes: 3

Related Questions