I create a Dynamic Form with two tables
1.courses, Model Class is Courses
2.course_instructors, Model Class is CourseInstructors
I was able to Insert (Create)
But when I tried to Edit, I clicked on the Update button, but nothing is happening
CoursesController
public function actionUpdate($id)
{
$modelCourse = $this->findModel($id);
$modelsInstructor = $modelCourse->courseInstructors;
if ($modelCourse->load(Yii::$app->request->post())) {
$oldIDs = ArrayHelper::map($modelsInstructor, 'id', 'id');
$modelsInstructor = Model::createMultiple(CourseInstructors::classname(), $modelsInstructor);
Model::loadMultiple($modelsInstructor, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsInstructor, 'id', 'id')));
// validate all models
$valid = $modelCourse->validate();
$valid = Model::validateMultiple($modelsInstructor) && $valid;
$modelCategory->updated_by = Yii::$app->getid->getId();
$modelCategory->updated_at = new \yii\db\Expression('NOW()');
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($modelCourse);
}
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $modelInstructor->save(false)) {
if (!empty($deletedIDs)) {
CourseInstructors::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsInstructor as $modelInstructor) {
$modelInstructor->course_id = $modelCourse->id;
if (! ($flag = $modelInstructor->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $modelCourse->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('update', [
'modelCourse' => $modelCourse,
'modelsInstructor' => (empty($modelsInstructor)) ? [new CourseInstructors] : $modelsInstructor
]);
}
Model
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $item) {
if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
$models[] = $multipleModels[$item['id']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
7653
What could have caused the problem, and how do I resolve it.