public function run() { Yii::setAlias('@unclead-examples', realpath(__DIR__ . '/../')); $models = $this->getItems(); $request = Yii::$app->getRequest(); if ($request->isPost && $request->post('ajax') !== null) { $data = Yii::$app->request->post('Item', []); foreach (array_keys($data) as $index) { $models[$index] = new Item(); } Model::loadMultiple($models, Yii::$app->request->post()); Yii::$app->response->format = Response::FORMAT_JSON; $result = ActiveForm::validateMultiple($models); return $result; } if (Model::loadMultiple($models, Yii::$app->request->post())) { // your magic } return $this->controller->render('@unclead-examples/views/tabular-input.php', ['models' => $models]); }
/** * Updates an existing Tour model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); $modelsCustomField = $model->customFields; if ($model->load(Yii::$app->request->post())) { $oldIDs = ArrayHelper::map($modelsCustomField, 'id', 'id'); $modelsCustomField = Model::createMultiple(CustomField::classname(), $modelsCustomField); Model::loadMultiple($modelsCustomField, Yii::$app->request->post()); $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsCustomField, 'id', 'id'))); // ajax validation if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ArrayHelper::merge(ActiveForm::validateMultiple($modelsCustomField), ActiveForm::validate($model)); } // validate all models $valid = $model->validate(); $valid = Model::validateMultiple($modelsCustomField) && $valid; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $model->save(false)) { if (!empty($deletedIDs)) { CustomField::deleteAll(['id' => $deletedIDs]); } foreach ($modelsCustomField as $modelCustomField) { $modelCustomField->tour_id = $model->id; if (!($flag = $modelCustomField->save(false))) { $transaction->rollBack(); break; } } } if ($flag) { $transaction->commit(); return $this->redirect(['view', 'id' => $model->id]); } } catch (Exception $e) { $transaction->rollBack(); } } } return $this->render('update', ['model' => $model, 'modelsCustomField' => empty($modelsCustomField) ? [new CustomField()] : $modelsCustomField]); }