|
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 multiple deletion of models from backend grid |
|
12
|
|
|
* @package app\backend\actions |
|
13
|
|
|
*/ |
|
14
|
|
|
class MultipleDelete 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
|
|
|
$items = Yii::$app->request->post('items', []); |
|
58
|
|
|
if (!empty($items)) { |
|
59
|
|
|
/** @var \yii\db\ActiveRecord $modelName fake type for PHPStorm (: */ |
|
60
|
|
|
$items = $modelName::find()->where(['in', 'id', $items])->all(); |
|
61
|
|
|
foreach ($items as $item) { |
|
62
|
|
View Code Duplication |
if ($this->markAsDeleted === true) { |
|
63
|
|
|
$item->setAttribute($this->deletedMarkAttribute, $this->deletedMarkValue); |
|
64
|
|
|
$item->save(); |
|
65
|
|
|
} else { |
|
66
|
|
|
$item->delete(); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
Yii::$app->session->setFlash('info', Yii::t('app', 'Objects deleted')); |
|
72
|
|
|
return $this->controller->redirect($this->redirect); |
|
|
|
|
|
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|
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: