0

In my form I wanna get the username instead of the user_id, I'm getting "Trying to get property of non-object", how do I properly get the Username from the user table?

<?= $form->field($model, 'user_id')->textInput(
[
    //'value' => Yii::$app->user->getId(),
    'value' => $model->user->username,
    'readonly' => true,
    'style' => 'width:400px'
]
  )?>

Here's the model of this form

public function getUserType(){
  //Related model Class Name
  //related column name as select
  return $this->hasOne(User::className() ,['id' => 'user_id'])->select('type')->scalar();
}
swaggyboi
  • 11
  • 3

1 Answers1

1

You need the following relation in your code

public function getUser(){
    return $this->hasOne(User::className(), ['id' => 'user_id']);
}

And your code should work.

I dont think what your are doing is correct, you are making an input binded with your user ID which contain your username. When the form is submitted Yii will try to load the username string in you user_id property. If the username and the user_id aren't the same thing this will cause a validation error.

The problem arise from the fact that you are using an input binded with a form for display purpuse. You should create an input without the form like

$options = ['readonly' => true, 'style' => 'width:400px']    
Html::inputText( "username", $model->user->username, $options)

or just remove the input and write the value inside a div.

gmazzotti
  • 427
  • 4
  • 11