简体   繁体   中英

Yii2 get post request value not working

Why Yii::$app->request->post() not working?

Form:

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

   <?= $form->field($model, 'parent')
        ->dropDownList($model->AuthItemDropdown
        );
    ?>
    <?= $form->field($model, 'child[]')
        ->dropDownList($model->AuthItemDropdown,
            ['multiple'=>'multiple']  
        );
    ?>

Controller:

 public function actionCreate(){

    $model = new AuthItemChild();

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

        $parent =  Yii::$app->request->post('parent');
        echo $parent; // show nothing

        $x = Yii::$app->request->post('child');
        print_r($x);// show nothing
        exit;

But output of print_r(Yii::$app->request->post()); is:

Array
(
    [_csrf-backend] => OGd0emxoOHgJEh8ICFloPlYvJg8BEHk.VjVAMx0hTD9CKgIDNSdVOg==
    [AuthItemChild] => Array
        (
            [parent] => admin
            [child] => Array
                (
                    [0] => admin
                    [1] => create-branch
                )
        )
)

Based on your print_r(Yii::$app->request->post()); output you should call for:

$authItemChild = Yii::$app->request->post('AuthItemChild');
echo $authItemChild['parent']; // should show 'admin'

Since you are loading the model with the post, I guess you should show the loaded results, instead of trying to get the post again:

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

    $parent =  $model->parent;
    echo $parent;

    $x = $model->child;
    print_r($x);
    exit;
}

I tried to get value the same way. What i disclosed is $app->request->post() (Yii2.0.10) works different with text and select fields.

  1. Text fields are binded via $model->load(Yii::$app->request->post())
  2. For selects better way is to get value as $model->parent=$request->post("parent") with name explicitly set: <?= $form->field($model, 'parent') ->dropDownList($model->AuthItemDropdown,['id' => 'parent','name'=>'parent'] ); ?> <?= $form->field($model, 'parent') ->dropDownList($model->AuthItemDropdown,['id' => 'parent','name'=>'parent'] ); ?> By default ActiveForm determine name as YouModelName[NameOfField]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM