2017-09-04 66 views
0

我不是在Yii2的dropDownList中抓取选定的值($ model-> attribute),可能会出错?由于如何获取Yii2中dropDownList的值?

这是位于上查看代码:

$command = $connection->createCommand('SELECT att1 
              FROM table 
               ORDER By table_id ASC'); 
    $rows = $command->queryAll(); 
    $command->execute(); 

    $listData = ArrayHelper::index($rows, null, 'table_id'); 

然后在同一查看我打电话$的ListData

<div class="row"> 
     <div class="col-lg-9"> 

      <?php Pjax::begin(['enablePushState' => false]); ?> 

      <?php $form = ActiveForm::begin(['id' => 'test-form', 'options' => ['data-pjax' => true] 
      ]); ?> 

       <?= $form->field($model, 'attribute')->dropDownList($listData, ['prompt'=>'List of attributes.']); ?> 


       <div class="form-group"> 
        <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'test-button']) ?> 
       </div> 

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

     </div> 
</div> 

这是控制器:

public function actionTest() 
    { 
     $model = new TestForm(); 

      if ($model->load(Yii::$app->request->post()) && $model->validate()) { 
        $model->insertTest(); 
       return $this->renderAjax('test', ['model' => $model]);  

      } else { 
       return $this->renderAjax('test', ['model' => $model]); 
      } 

    } 

该模型具有$属性的定义,insertTest()是一个函数,它使用$属性值que ry到数据库。因为你需要一个一维数组

+0

您需要向我们展示如何启动'$ model'。可能在控制器中并从POST/GET请求中加载..? – lubosdz

回答

1

您从表中只att1选择,所以你应该映射此列

$listData = ArrayHelper::index($rows, 'att1'); 

调试尝试修改actionTest评论$模型 - > insertTest();并使用$ model-> save(); 如果该值被保存在数据库,那么你应该检查你$模型 - > insertTest()函数

public function actionTest() 
    { 
     $model = new TestForm(); 

      if ($model->load(Yii::$app->request->post()) && $model->validate()) { 
       // $model->insertTest(); 
       $model->save(); 
       return $this->renderAjax('test', ['model' => $model]);  

      } else { 
       return $this->renderAjax('test', ['model' => $model]); 
      } 

    } 
+0

谢谢你的回答,它是一个更好的方式来生成dropDownList的列表,但是在抓取字段($ model,'attribute') - > dropDownList($ listData,[ 'prompt'=>'属性列表'。 ?> –

+0

你有什么问题..你有没有数据在列表中? ..提交时你有没有价值? ..解释更好请 – scaisEdge

+0

dropDownList显示这样的值的列表:0 \ n属性1 1 \ n属性2 2 \ n属性3 3 \ n属性4 ...问题是,如果我选择属性3例如该值不是在提交之后被变量$属性抓住。我可能做错了什么?谢谢。 –

0

里面我找到了解决这个问题。

通过这种方式,表单无法保存提交的信息。

$command = $connection->createCommand('SELECT att1 
               FROM table 
                ORDER By table_id ASC'); 
    $rows = $command->queryAll(); 
    $command->execute(); 

    $listData = ArrayHelper::index($rows, null, 'table_id'); 

但是,通过这种方式,窗体能够抓取选定的值并将其放入变量中。

$rows = table::find()->all(); 
$listData = ArrayHelper::map($rows,'table_id','att1'); 
1

你应该ArrayHelper使用地图

$listdata = ArrayHelper::map(CategoryModel::find()->orderBy(['table_id' => SORT_ASC])->all(), 'table_id', 'table_text'); 

注: 'table_text' 是将显示在下拉菜单标签表属性。

相关问题