/
NestedSortableAction.php
81 lines (63 loc) · 2.29 KB
/
NestedSortableAction.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace claudejanz\yii2nested;
use Yii;
use yii\base\Action;
use yii\helpers\Html;
class NestedSortableAction extends Action {
public $modelclass;
public $scenario = '';
/**
* column name of sorting value
* @var string
*/
public $orderBy = 'weight';
/**
* value of root elements in sorting value
* depends on db settings 0 or null
*/
public $rootValue = null;
/**
* column name of parent id
* @var string
*/
public $parentId = 'parent_id';
public function run() {
// Get the JSON string
$jsonstring = $_GET['jsonstring'];
// Decode it into an array
$jsonDecoded = json_decode($jsonstring, true, 64);
// Run the function above
$readbleArray = $this->parseJsonArray($jsonDecoded);
// Loop through the "readable" array and save changes to DB
foreach ($readbleArray as $key => $value) {
// $value should always be an array, but we do a check
if (is_array($value)) {
$modelclass = $this->modelclass;
$pks = (array)$modelclass::primaryKey();
$model = $modelclass::find()->where([
join(',',$pks) => $value['id'],
])->one();
if ($this->scenario) {
$model->setScenario($this->scenario);
}
$model->{$this->orderBy} = $key;
$model->{$this->parentId} = $value['parentID'];
$model->save(false);
}
}
// Echo status message for the update
echo Html::tag('div',Yii::t('claudejanz', "Order Updated on {date}",['date'=>Yii::$app->formatter->asDatetime(time())]),['class'=>'alert alert-success']);
}
public function parseJsonArray($jsonArray, $parentID = null) {
$return = array();
foreach ($jsonArray as $subArray) {
$returnSubSubArray = array();
if (isset($subArray['children'])) {
$returnSubSubArray = $this->parseJsonArray($subArray['children'], $subArray['id']);
}
$return[] = array('id' => $subArray['id'], 'parentID' => $parentID);
$return = array_merge($return, $returnSubSubArray);
}
return $return;
}
}