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();
}
8
  • What is your $model? Do you have relation to user in this model? Commented Apr 19, 2018 at 15:20
  • What do you mean by what is my $model, yes the user model has a relation in this model Commented Apr 19, 2018 at 15:27
  • You're trying to get relation by $model->user - so i'm asking, what's exacly is your $model (which class), and is in this $model - do you have defined relation to User? Commented Apr 19, 2018 at 15:33
  • var_dump($model->user) and check what's in there first. Commented Apr 19, 2018 at 15:36
  • @DEarTh it says null. Commented Apr 19, 2018 at 15:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.