|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace devgroup\JsTreeWidget\actions\AdjacencyList; |
|
4
|
|
|
|
|
5
|
|
|
use DevGroup\TagDependencyHelper\NamingHelper; |
|
6
|
|
|
use Yii; |
|
7
|
|
|
use yii\base\Action; |
|
8
|
|
|
use yii\base\InvalidConfigException; |
|
9
|
|
|
use yii\caching\TagDependency; |
|
10
|
|
|
use yii\db\ActiveRecord; |
|
11
|
|
|
use yii\web\NotFoundHttpException; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Helper action to change parent_id attribute via JsTree Drag&Drop |
|
15
|
|
|
* Example usage in controller: |
|
16
|
|
|
* ``` php |
|
17
|
|
|
* public function actions() |
|
18
|
|
|
* { |
|
19
|
|
|
* return [ |
|
20
|
|
|
* 'move' => [ |
|
21
|
|
|
* 'class' => TreeNodeMoveAction::class, |
|
22
|
|
|
* 'class_name' => Category::class, |
|
23
|
|
|
* ], |
|
24
|
|
|
* ... |
|
25
|
|
|
* ]; |
|
26
|
|
|
* } |
|
27
|
|
|
* ``` |
|
28
|
|
|
*/ |
|
29
|
|
|
|
|
30
|
|
|
class TreeNodeMoveAction extends Action |
|
31
|
|
|
{ |
|
32
|
|
|
public $className = null; |
|
33
|
|
|
public $modelParentIdField = 'parent_id'; |
|
34
|
|
|
public $parentId = null; |
|
35
|
|
|
public $saveAttributes = []; |
|
36
|
|
|
|
|
37
|
|
|
public function init() |
|
38
|
|
|
{ |
|
39
|
|
|
if (!isset($this->className)) { |
|
40
|
|
|
throw new InvalidConfigException("Model name should be set in controller actions"); |
|
41
|
|
|
} |
|
42
|
|
|
if (!class_exists($this->className)) { |
|
43
|
|
|
throw new InvalidConfigException("Model class does not exists"); |
|
44
|
|
|
} |
|
45
|
|
|
if (!in_array($this->modelParentIdField, $this->saveAttributes)) { |
|
46
|
|
|
$this->saveAttributes[] = $this->modelParentIdField; |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public function run($id = null) |
|
51
|
|
|
{ |
|
52
|
|
|
$this->parentId = Yii::$app->request->get('parent_id'); |
|
53
|
|
|
$class = $this->className; |
|
54
|
|
|
if (null === $id |
|
55
|
|
|
|| null === $this->parentId |
|
56
|
|
|
|| (null === $model = $class::findOne($id)) |
|
57
|
|
|
|| (null === $parent = $class::findOne($this->parentId))) { |
|
58
|
|
|
throw new NotFoundHttpException; |
|
59
|
|
|
} |
|
60
|
|
|
/** @var ActiveRecord $model */ |
|
61
|
|
|
$model->{$this->modelParentIdField} = $parent->id; |
|
62
|
|
|
TagDependency::invalidate( |
|
63
|
|
|
Yii::$app->cache, |
|
64
|
|
|
NamingHelper::getCommonTag($class) |
|
65
|
|
|
); |
|
66
|
|
|
return $model->save(true, $this->saveAttributes); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|