Yii2获取发布请求值不起作用

时间:2016-07-26 18:20:26

标签: yii2 yii2-advanced-app

为什么Yii::$app->request->post()无效?

形式:

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

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

控制器:

 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;

print_r(Yii::$app->request->post());的输出是:

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

3 个答案:

答案 0 :(得分:2)

根据您的print_r(Yii::$app->request->post());输出,您应该致电:

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

答案 1 :(得分:1)

由于您使用帖子加载模型,我猜您应该显示加载的结果,而不是尝试再次发布帖子:

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

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

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

答案 2 :(得分:0)

我试图以同样的方式获得价值。我透露的是 $ app-&gt; request-&gt; post()(Yii2.0.10)与文本和选择字段的工作方式不同。

  1. 文本字段通过$model->load(Yii::$app->request->post())
  2. 绑定
  3. 对于选择,更好的方法是获取$model->parent=$request->post("parent") 的值,并明确设置名称: <?= $form->field($model, 'parent') ->dropDownList($model->AuthItemDropdown,['id' => 'parent','name'=>'parent'] ); ?> 默认情况下,ActiveForm将名称确定为YouModelName[NameOfField]