I have a master and detail form(gridview) in an activeform and i intend to update both simultaneously
The problem is that its saving an extra duplicate record in the details model. When uncommented ($model->save()) updates the details model properly
My code is
$model = $this->findModel($id);
$marksdetailsmodels = MarksDetail::find()->where(['marks_master_id'=>$id])->indexBy('id')->all();//
if (Yii::$app->request->post()) {
$transaction = Yii::$app->db->beginTransaction();
try {
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if (Model::loadMultiple($marksdetailsmodels, Yii::$app->request->post()) && Model::validateMultiple($marksdetailsmodels)
) {
$count = 0;
foreach ($marksdetailsmodels as $index => $detail) {
// populate and save records for each model
$detail->last_date_of_exam = Yii::$app->formatter->asDate($detail->last_date_of_exam,'yyyy-MM-dd HH:mm:ss');
if ($detail->save()) {
$count++;
}
}
$model->save(); //<!---the problem is here
$transaction->commit();//exit;
Yii::$app->session->setFlash('success', "Processed {$count} records successfully.");
//
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->goBack();
}
}
} catch (Exception $e) {
$transaction->rollback();
}
}
the Yii::$app->request->post() array is as follows
Array
(
[_csrf] => bP5Sxo_84zN4NVExojmHdb8OXTp_dzFwlgI46tBiAYwWpB_x_6WGRU0BOnjSXrEz81YcSTMoAEDPa2K_uBQ31Q==
[MarksMaster] => Array
(
[date_of_exam] => 03-Jan-1970, [unit] => 5, [total_marks] => 70, [class] => 3
)
[MarksDetail] => Array
(
[1] => Array ([id] => 1, [marks] => 10, [rating] => 3, [last_date_of_exam] => 2018-03-01)
[2] => Array ([id] => 2, [marks] => 20, [rating] => 2, [last_date_of_exam] => 2018-03-02)
[5] => Array ([id] => 5, [marks] => 30, [rating] => 1, [last_date_of_exam] => 2018-03-03)
)
)