How to pass user id in form


I have created a table called posts and linked the posts table to the user table with a author_id foreign key.

I have also created a controller, model and crud for the posts page.

In the posts page I would like to have the user id passed in the form in the _form.php view file automatically without inputting it myself by hand. How to do this please?

All I am trying to do is get the user id inside the form so it is stored in the grid for that user.

Here is the _form.php code:


use yii\helpers\Html;

use yii\widgets\ActiveForm;

/* @var $this yii\web\View */

/* @var $model frontend\models\Posts */

/* @var $form yii\widgets\ActiveForm */


<div class="posts-form">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'posts_title')->textInput(['maxlength' => 100]) ?>

    <?= $form->field($model, 'posts_description')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'author_id')->textInput() ?>

    <div class="form-group">

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>


    <?php ActiveForm::end(); ?>


Thank you,


hey i’m quite new as well, but this is an easy one :)

In your controller you will call something like:

return $this->render('view', ['userid' => $userid]);

Get userid from Yii::$app->user->identity->id

In form you can then reference that $userid variable

hope that helps

Thanks YesIAm,

I will give it a shot.

I think my problem with Yii is not understanding the logic but knowing all the keywords/vocabulary…absolute nightmare at the moment.

For example, this "identity" class, where does it comes from?

Do I need to add anything at the top of the view file like "use …\identity\

Thank you,


So if I understand, I need do to this:

   public function actionCreate()


        $model = new Posts();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->posts_id]);


        } else {

            return $this->render('create', [

                'model' => $model,

                'view', 'id' => $model->posts_id,




and in the form I can echo ‘Yii::$app->user->identity->id’;

am I correct?

Thank ou,