How to get Post value in a controller

Here is my model




namespace app\models;


use yii\base\Model;


class UserFormModel extends Model {


	public $username;

	public $password;


	public function rules() {

		return [

				[['username','password'], 'required'],

			    ['password', 'string', 'max' => 64],

		       ];

	}


}




Here is my form view




<?php


use yii\helpers\Html;

use yii\widgets\ActiveForm; 

?>


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


<?= $form->field($model, 'username'); ?>

<?= $form->field($model, 'password'); ?>


<?= Html::submitButton('Next', ['class' => 'btn btn-success']);?>



and here is my controller





    public function actionUser() {

        $model = new UserFormModel;

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

            $session = Yii::$app->session;

            $session->open();

            $request = Yii::$app->request->post('username');

            return $this->render('hello');

        } else {

            return $this->render('userFrom', ['model'=>$model]);

        }

    }

}




for the $request, i got nothing. why is that? thanks in advance




$request=Yii:$app->request->post('UserFormModel')['username']; //For PHP > 5.4

//or for PHP < 5.4 :

$post =Yii::$app->request->post('UserFormModel');

$request = $post['username'];



$form->field will render an input name like this ModelName[attributeName], and this translates into $_POST like this:




array('ModelName'=>array('attributeName'=>'inputValue'))



If you find yourself stuck like this again just: var_dump( [color="#660066"][size="2"]Yii[/size][/color][color="#666600"][size="2"]::[/size][/color][size="2"]$app[/size][color="#666600"][size="2"]->[/size][/color][size="2"]request[/size][color="#666600"][size="2"]->[/size][/color][size="2"]post());[/size]

2 Likes

It Will Works.

$POST_VARIABLE=Yii::$app->request->post(‘UserFormModel’);

$request = $POST_VARIABLE[‘username’];

Thank you! It works!

Nice information… :)

In your view you missed closing the ActiveForm so your submit button is not working.

<?php $form->end(); ?>