/** * Updates an existing Image model. * If update is successful, the browser will be redirected to the 'view' page. * @param string $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); $gallery = Gallery::findOne(Yii::$app->session->get('gallery.gallery-id')); if (Yii::$app->request->getIsPost()) { $post = Yii::$app->request->post(); // Ajax request, validate the models if (Yii::$app->request->isAjax) { // Populate the model with the POST data $model->load($post); // Create an array of translation models and populate them $translationModels = ArrayHelper::index($model->getTranslations()->all(), 'language'); Model::loadMultiple($translationModels, $post); // Validate the model and translation $response = array_merge(ActiveForm::validate($model), ActiveForm::validateMultiple($translationModels)); // Return validation in JSON format Yii::$app->response->format = Response::FORMAT_JSON; return $response; // Normal request, save models } else { // Wrap everything in a database transaction $transaction = Yii::$app->db->beginTransaction(); // Validate the main model if (!$model->load($post)) { return $this->render('update', ['model' => $model]); } // Add the translations foreach (Yii::$app->request->post(StringHelper::basename(ImageLang::className()), []) as $language => $data) { foreach ($data as $attribute => $translation) { $model->translate($language)->{$attribute} = $translation; } } if (!$model->save()) { return $this->render('update', ['model' => $model]); } $transaction->commit(); // Set flash message Yii::$app->getSession()->setFlash('image-success', Yii::t('app', '{item} has been updated', ['item' => $model->name])); return $this->redirect('index'); } } return $this->render('update', ['model' => $model, 'gallery' => $gallery]); }
/** * Performs validation on the provided model and $_POST data * * @param \infoweb\pages\models\Page $model The page model * @param array $post The $_POST data * @return array */ protected function validateModel($model, $post) { $languages = Yii::$app->params['languages']; // Populate the model with the POST data $model->load($post); // Create an array of translation models and populate them $translationModels = []; // Insert if ($model->isNewRecord) { foreach ($languages as $languageId => $languageName) { $translationModels[$languageId] = new SettingValue(['language' => $languageId]); } // Update } else { $translationModels = ArrayHelper::index($model->getTranslations()->all(), 'language'); } Model::loadMultiple($translationModels, $post); // Validate the model and translation $response = array_merge(ActiveForm::validate($model), ActiveForm::validateMultiple($translationModels)); // Return validation in JSON format Yii::$app->response->format = Response::FORMAT_JSON; return $response; }