public function beforeDelete() { if (parent::beforeDelete()) { foreach ($this->codes as $code) { if ($code->delete() === false) { return false; } } foreach ($this->members as $member) { if ($member->delete() === false) { return false; } } Option::deleteAll('poll_id = :poll_id', [':poll_id' => $this->id]); //foreach ($this->options as $option) { //if ($option->delete() === false) { //return false; //} //} return true; } return false; }
/** * 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]); }