Yii2从CheckBoxList插入数据

问题描述 投票:0回答:1

在我的表格中:

 <?= 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。

yii2 checkboxlist yii2-basic-app
1个回答
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.