Yii2从CheckBoxList插入数据

时间:2019-03-17 06:00:56

标签: yii2 checkboxlist yii2-basic-app

以我的形式:

 <?= GridView::widget([
 'id' => 'griditems',
 'dataProvider' => $dataProvider,
  'columns' => [
   'receiver_name',
   'receiver_phone',
   'item_price',
   'shipment_price',
   ['class' => 'yii\grid\CheckboxColumn'],
  ],

]); ?>

在我的控制器中:

public function actionCreate()
{
    $model = new Package();
    $searchModel = new ShipmentSearch();
    $searchModel->shipment_position=1; // الشحنه في مقر الشركة
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    if ($model->loadAll(Yii::$app->request->post())){ 
        $select = Yii::$app->request->post('selection');

        foreach($select as $id){
            $shipment= shipment::findOne((int)$id);
            $model->company_id=1;
            $model->shipment_id=$shipment->id;
            $model->send_from=$shipment->send_from;
            $model->send_to=$shipment->send_to;
            $model->save(false);

        }
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
            'dataProvider'=>$dataProvider,
        ]);
    }
}

我只是尝试以这种方式插入数据,但其插入的数据只是列表中的最后一个或最后一个CheckBox。我尝试打印id中的foreach,并且有多个ID。

1 个答案:

答案 0 :(得分:1)

那是因为您要为foreach内部的每个save()重新使用相同的实例,因此您要一遍又一遍地覆盖相同的模型。您需要将$model = new Package()放在foreach内:

foreach($select as $id){
    $shipment= shipment::findOne((int)$id);
    $model = new Package();
    $model->company_id=1;
    $model->shipment_id=$shipment->id;
    $model->send_from=$shipment->send_from;
    $model->send_to=$shipment->send_to;
    $model->save(false);
}