php - How to call data from database based on user who login and display in form column/field in yii2?
Get the solution ↓↓↓i want to display the username based on user that login to the application and put it inside field form (username)
this is code for my form<?= $form->field($model, 'username')->textInput(['maxlength' => true])?>
this is code for calling the username based on the login user
<?=Yii::$app->user->identity->username ?>
but i dont know how to put the username inside the textinput
Answer
Solution:
You should set a necessary value in the model object that passes to ActiveFrom widget:
<?= $model->username = Yii::$app->user->identity->username; ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]); ?>
Answer
Solution:
It's good practice to load your model data in your controller.
In your TestController
public function actionTest(){
$model = new User();
$model->username = Yii::$app->getUser()->getIdentity()->username;
if($model->load(Yii::$app->getRequest()->post()){
$model->save();
// and ...
}
return $this->render('view', ['model'=>$model]);
}
In your view file
<?= $form->field($model, 'username')->textInput(['maxlength' => true])?>
In this case if you want to prevent user from changing value of user name change your controller code to something like this:
public function actionTest(){
$model = new User();
$model->username = Yii::$app->getUser()->getIdentity()->username;
if($model->load(Yii::$app->getRequest()->post()){
// Overwrite user input.
$model->username = Yii::$app->getUser()->getIdentity()->username;
$model->save();
// and ...
}
return $this->render('view', ['model'=>$model]);
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: deprecated: directive 'allow_url_include' is deprecated in unknown on line 0
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.