Search code examples
yii2checkboxlistyii2-basic-app

Yii2 insert data from CheckBoxList


In my Form:

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

]); ?>

In my Controller:

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,
        ]);
    }
}

I just try this way to insert data as above its works but the data inserted just last one or last CheckBox from the list. I tried to print the id that in foreach and there is more than one id.


Solution

  • That is beacuse you're reusing the same instace for each save() inside of foreach, so you're overwriting the same model over and over. You need to place $model = new Package() inside of 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);
    }