Yii2 get post request value not working

左心房为你撑大大i 提交于 2020-01-05 04:43:10

问题


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
                )
        )
)

回答1:


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'



回答2:


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;
}



回答3:


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'] ); ?> By default ActiveForm determine name as YouModelName[NameOfField]


来源:https://stackoverflow.com/questions/38597229/yii2-get-post-request-value-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!