コード例 #1
0
 /**
  * Updates an existing Poll 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);
     if ($model->isLocked()) {
         throw new HttpException(403, Yii::t('app', 'This poll cannot be edited because it has already been accessed by a voter'));
     }
     $modelOptions = $model->options;
     if ($model->load(Yii::$app->request->post())) {
         $oldIDs = ArrayHelper::map($modelOptions, 'id', 'id');
         $modelOptions = Model::createMultiple(Option::classname(), $modelOptions);
         Model::loadMultiple($modelOptions, Yii::$app->request->post());
         $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelOptions, 'id', 'id')));
         // ajax validation
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
             return ArrayHelper::merge(ActiveForm::validateMultiple($modelOptions), ActiveForm::validate($model));
         }
         // validate all models
         $valid = $model->validate();
         $valid = Model::validateMultiple($modelOptions) && $valid;
         if ($valid) {
             $transaction = \Yii::$app->db->beginTransaction();
             try {
                 if ($flag = $model->save(false)) {
                     if (!empty($deletedIDs)) {
                         Option::deleteAll(['id' => $deletedIDs]);
                     }
                     foreach ($modelOptions as $modelOption) {
                         $modelOption->poll_id = $model->id;
                         if (!($flag = $modelOption->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, 'modelOptions' => empty($modelOptions) ? [new Option(), new Option()] : $modelOptions]);
 }