Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

model->attributes in Yii2 always has NULL value

I have one temporary model as viewModel. In my CRUD actions (for example actionCreate) I want to get this viewModel data and assign that to a ActiveRecord model. I used below code but my model object atrribute always show NULL value for attributes:

$model = new _Users();
if ($model->load(Yii::$app->request->post())) {
    Yii::info($model->attributes,'test'); // NULL
    $attributesValue =[
            'title' => $_POST['_Users']['title'],
            'type' => $_POST['_Users']['type'],
        ];
    $model->attributes = $attributesValue;
    Yii::info($model->attributes,'test'); // NULL

    $dbModel = new Users();
    $dbModel->title = $model->title;
    $dbModel->type = $model->type . ' CYC'; // CYC is static type code
    Yii::info($dbModel->attributes,'test'); // NULL

    if ($dbModel->save()) {
            return $this->redirect(['view', 'id' => $dbModel->id]); // Page redirect to blank page
        }
}
else {
        return $this->render('create', [
            'model' => $model,
        ]);
}

I think $model->load(Yii::$app->request->post()) not working and object attribute being NULL. Is it Yii2 bug or my code is incorrect??

like image 231
b24 Avatar asked Jul 18 '14 11:07

b24


5 Answers

If there is no rule for your attribute the $model->load() will ignore those not in the rules of the model.

Add your attributes to the rules function

public function rules()
{
    return [
        ...
        [['attribute_name'], 'type'],
        ...
    ];
}
like image 55
Jason G Avatar answered Nov 12 '22 09:11

Jason G


Declare attribute as private then

echo $yourModel->attribute 

work as expected

like image 27
noc_nokout Avatar answered Sep 28 '22 05:09

noc_nokout


To fetch data for an individually attributes(db-fields) in yii2.0 then you should just do as:

echo $yourModel->getAttribute('email');
like image 3
Amjad Ali Chauhdry Avatar answered Nov 12 '22 07:11

Amjad Ali Chauhdry


ActiveRecord $attributes is a private property Use $model->getAttribute(string)

like image 1
Alex Avatar answered Nov 12 '22 08:11

Alex


You can use following codes:

$model = new _Users();
$model->attributes=Yii::$app->request->post('_Users');
$model->title= $model->title
$model->type = $model->type . ' CYC'; // CYC is static type code
#$model->sampleAttribute='Hello World';
like image 1
Mahmut Aydın Avatar answered Nov 12 '22 07:11

Mahmut Aydın