Inheritance: extends yii\db\ActiveRecord
 /**
  * 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]);
 }
Exemplo n.º 2
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getTranslations()
 {
     return $this->hasMany(ImageLang::className(), ['image_id' => 'id']);
 }