我需要创建2个删除功能(相册和照片)。不知何故,它在控制器中只有一个删除功能。如何在控制器中创建2删除功能?我仍然是OOP和Yii2的初学者。
这些是我要解释的示例。
GalleryController.php
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
public function actionDeletePhoto($id)
{
$this->findModelPhoto($id)->delete();
return $this->redirect(['index']);
}
答案 0 :(得分:1)
尝试一下:
视图:
<?= Html::a('<i class="fa fa-trash"></i>',
['/controller/delete-photo'],
[
'class' => 'photo-dlt',
'title' => Yii::t('app', 'Delete photo'),
'data' => [
'method' => 'post',
'confirm' => Yii::t('app', 'Do you want to delete this photo?'),
'params' => ['id' => $photo->id],
],
]
); ?>
在控制器中
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
'delete-photo' => ['POST'] // add this line of code
],
],
];
}
public function actionDeletePhoto()
{
$path = "path/to/photo";
$id = Yii::$app->request->post('id');
$model = $this->findModelPhoto($id);
unlink($model->image, $path);
$model->delete();
return $this->redirect(['index']);
}
答案 1 :(得分:0)
尝试这种方式:
public function actionDelete($id)
{
$this->findModel($id)->delete();
$this->findModelPhoto($id)->delete();
return $this->redirect(['index']);
}
或有另一种方法,有时删除可能会引起问题,因此在数据库中再添加一个称为“状态”的列,并将其设置为1表示活动,而将0设置为被动,则可以通过轻松更改它们的作用来创建行状态如下:
public function actionDelete($id)
{
$model = Model::find()->where(['id'=>$id])->one();
$model->status=0;
$model->save(false);
Yii::$app->session->setFlash('danger', "smth is deleted!");
return $this->redirect(['index']);
}