[ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => [ 'POST' ], ], ], 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'allow' => true, 'roles' => [ '@' ], ], ], ], ]; } public function actions() { return [ 'index' => [ 'class' => Index::className(), 'columns' => [ 'title' => [ 'type' => Index::ACTION_COL, ], 'author' => [ 'type' => Index::RELATION_COL, 'columnConfig' => [ 'relationField' => 'secondname', ], ], 'created_at' => [ 'type' => Index::DATETIME_COL, ], 'status' => [ 'type' => Index::STRING_COL, ], 'on_main' => [ 'type' => Index::STATUS_COL, ], ], 'model' => Book::className(), 'hasLanguage' => false, 'enableMassDelete' => true, 'modelPrimaryKey' => 'id', 'defaultSort' => [ 'created_at' => 'DESC' ], 'create' => true, ], ]; } public function actionCreate() { /** * @var Book $model; */ $model = new Book(); $authors = Author::find()->all(); $data = ArrayHelper::map($authors, 'id', 'secondname'); if ($model->load(\Yii::$app->request->post()) && $model->save()) { $model->saveImage(UploadedFile::getInstanceByName('file')); return $this->redirect('index'); } else { return $this->render( 'create', [ 'model' => $model, 'data' => $data ] ); } } public function actionUpdate($id) { /** * @var Book $model; */ $model = $this->findModel($id); if ($model->load(\Yii::$app->request->post()) && $model->save()) { $model->saveImage(UploadedFile::getInstanceByName('file')); return $this->redirect('index'); } else { return $this->render( 'update', [ 'model' => $model, ] ); } } public function findModel($id) { $model = Book::find() ->where([ 'id' => $id ]) ->one(); if ($model !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } public function actionDelete($id) { if (file_exists(\Yii::getAlias('@storage/books/') . $id)) { $this->removeDirectory(\Yii::getAlias('@storage/books/') . $id); } $this->findModel($id) ->delete(); return $this->redirect([ 'index' ]); } public static function removeDirectory($dir) { if ($objs = glob($dir . "/*")) { foreach ($objs as $obj) { is_dir($obj) ? self::removeDirectory($obj) : unlink($obj); } } rmdir($dir); } public function actionDeleteImage() { \Yii::$app->response->format = Response::FORMAT_JSON; $book = Book::find() ->where([ 'id' => \Yii::$app->request->post('id') ]) ->one(); if ($book !== null){ if (file_exists( \Yii::getAlias('@storage/books/') . $book->id . '/' . \Yii::$app->request->post('image') )) { unlink( \Yii::getAlias('@storage/books/') . $book->id . '/' . \Yii::$app->request->post( 'image' ) ); } $book->image = null; $book->save(); return \GuzzleHttp\json_encode('success'); } return \GuzzleHttp\json_encode('error'); } }