1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace app\backend\actions; |
4
|
|
|
|
5
|
|
|
use app; |
6
|
|
|
use yii; |
7
|
|
|
use yii\base\Action; |
8
|
|
|
use yii\base\InvalidConfigException; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Action for deletion one model from backend grid |
12
|
|
|
* @package app\backend\actions |
13
|
|
|
*/ |
14
|
|
|
class DeleteOne extends Action |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var string Model name, ie. `Product::className()` |
18
|
|
|
*/ |
19
|
|
|
public $modelName = null; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var bool Mark as deleted instead of calling `delete()` |
23
|
|
|
*/ |
24
|
|
|
public $markAsDeleted = false; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var string Attribute that stores deleted state |
28
|
|
|
*/ |
29
|
|
|
public $deletedMarkAttribute = 'is_active'; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var mixed Deleted state value(ie. 1 for is_deleted or 0 for is_active) |
33
|
|
|
*/ |
34
|
|
|
public $deletedMarkValue = 0; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @var array Route to redirect after deletion |
38
|
|
|
*/ |
39
|
|
|
public $redirect = ['index']; |
40
|
|
|
|
41
|
|
View Code Duplication |
public function init() |
42
|
|
|
{ |
43
|
|
|
if (!isset($this->modelName)) { |
44
|
|
|
throw new InvalidConfigException("Model name should be set in controller actions"); |
45
|
|
|
} |
46
|
|
|
if (!class_exists($this->modelName)) { |
47
|
|
|
throw new InvalidConfigException("Model class does not exists"); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @inheritdoc |
53
|
|
|
*/ |
54
|
|
|
public function run() |
55
|
|
|
{ |
56
|
|
|
$modelName = $this->modelName; |
57
|
|
|
$id = Yii::$app->request->get('id', null); |
58
|
|
|
if (!empty($id)) { |
59
|
|
|
/** @var \yii\db\ActiveRecord $modelName fake type for PHPStorm (: */ |
60
|
|
|
$item = $modelName::findOne($id); |
61
|
|
|
if ($item === null) { |
62
|
|
|
throw new yii\web\NotFoundHttpException; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
View Code Duplication |
if ($this->markAsDeleted === true) { |
66
|
|
|
$item->setAttribute($this->deletedMarkAttribute, $this->deletedMarkValue); |
67
|
|
|
$item->save(); |
68
|
|
|
} else { |
69
|
|
|
$item->delete(); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
Yii::$app->session->setFlash('info', Yii::t('app', 'Object removed')); |
75
|
|
|
return $this->controller->redirect($this->redirect); |
|
|
|
|
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
It seems like the method you are trying to call exists only in some of the possible types.
Let’s take a look at an example:
Available Fixes
Add an additional type-check:
Only allow a single type to be passed if the variable comes from a parameter: