-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathJsTree.php
461 lines (383 loc) · 15.8 KB
/
JsTree.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
<?php
/**
* JsTree widget is a Yii2 wrapper for the jsTree jQuery plugin with extended
* functions.
*
* @author Nils Menrad
* @since 1.0
* @see http://jstree.com
*/
namespace kasoft\jstree;
use Yii;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\base\Widget;
use yii\web\View;
use yii\web\Response;
use yii\helpers\Url;
use kasoft\jstree\JsTreeAsset;
class JsTree extends Widget
{
// Basic Settings Model/Column Names
/*
* @var object the yii2 active record model which should be used. set to false
* if the tree should be build from a json url. note: only with a model, the
* move, delete, sort, and create functions can be used
*/
public $modelName = false;
/*
* @var string URL that will generate the needed json for buildung the tree.
* Only needed when you DON'T set the modelName Property. Otherwise not needed.
*/
public $jsonUrl = false;
/*
* @var int ID where the Tree should start loading stuff, can be NULL too
*/
public $modelFirstParentId;
/*
* @var string Name of the PrimaryKey Column e.g. 'id'
*/
public $modelPropertyId;
/*
* @var string Column Name of the Parent Key e.g. 'parent_id'
*/
public $modelPropertyParentId;
/*
* @var string Column Name of the Title/Name e.g. 'title'
*/
public $modelPropertyName;
/*
* @var string Column Name of the Position attribute e. g. 'position'
*/
public $modelPropertyPosition;
/*
* @var string Column Name for a Type attribute. This can be used to give each
* Tree item a different Type which will be used for displaying icons, prevent
* creation of child elements, etc. See jsTree Docs for explanations.
*/
public $modelPropertyType = NULL;
/*
* @var boolean Disables the ability to cascade deleting. User maybe delete
* a Tree with mutltiple Elements by accident
* !!! NOT IMPLEMENTED YET - Cascading is not possible !!!!!
*/
public $noCascadingDelete = true;
/*
* @var array Allows to define different Types of Nodes wich can have restrictions
* in creating child Elements or which have diffenet icons. See jsTree Docs for
* more informations.
*/
public $jstreeType = [];
/*@var array Messages for Userinteractions which can be set to individual Text
*/
public $jstreeMsg = NULL;
/*
* @var array Configuration for Context Menu. It is possible to choose which Elements
* should apear in the Menu. Also you can set the Text and Icons of this Elements.
* Create, Edit, Rename and Delete are possible. For Create it is possible to set up
* a Submenu which create a Node with a specific Type (See $modelPropertyType)
*/
public $jstreeContextMenue = [];
/*
* @var string Name of the Controller used for calling ajax actions.
*/
public $controller; // controller name for ajax call "cms"
/*
* @var string Name of the Action that should be called when node is clicked
*/
public $action_click;
/*
* @var string Default Action for Tree (e.g. index)
*/
public $action_default;
public $jstreeIcons=NULL;
public $jstreePlugins;
/*
* @var string ID oder Class of the JsTree Div
* If not set, it will become #jstree
*/
public $jstreeDiv;
/*
* With this state key, jstree sets a cookie to remember the state of the
* tree (e.g. which bracnhes are open, etc.)
*/
public $jstreestatekey;
/**
* @var array Configure which plugins will be active on an instance. Should be an array of strings, where each element is a plugin name.
*/
public $plugins = ["checkbox"];
/**
* @var int Open the Node with this id (e.g. 33)
*/
public $initialOpenId = false;
// NOT IMPLEMENTED, DEVEPOLMENT
public $showIcons; // Show Type/Icons in Tree
public $modelCondition; // not implementes yet, additionl conditions
public $modelAddCondition; // not implementes yet, additionl conditions
/**
* @inheritdoc
*/
public function init() {
parent::init();
$this->registerAssets();
if (empty($this->jstreeDiv))
$this->jstreeDiv = "#jstree";
if ($this->jstreeIcons===NULL)
$this->jstreeIcons = true;
if (empty($this->jstreePlugins)) {
$this->jstreePlugins = [
"contextmenu", "dnd", "search","state", "types", "wholerow", "changed"
];
}
$standardMsg = [
"confirmdelete" => "Löschen? Sine Sie sicher?",
"nothere" => "An dieser Stelle leider nicht möglich!",
"itemnotexisting" => "Das Element existiert nicht!",
"itemcantdel" => "Das Element kann nicht gelöscht werden!",
"itemnodeletchildren" => "Das Element hat weitere Unterebenen und kann daher nicht gelöscht werden!",
"newNode" => "New Entry"
];
if(!empty($this->jstreeMsg))
$this->jstreeMsg = array_merge($standardMsg,$this->jstreeMsg);
else
$this->jstreeMsg = $standardMsg;
if(empty($this->jstreeContextMenue)) {
$this->jstreeContextMenue = [
"edit" => [
"text" => "Bearbeiten",
"icon" => "glyphicon glyphicon-pencil"
],
"create" => [
"text" => "Neu",
"icon" => "glyphicon glyphicon-th-list"
],
"rename" => [
"text" => "Umbenennen",
"icon" => "glyphicon glyphicon-transfer"
],
"remove" => [
"text" => "Löschen",
"icon" => "glyphicon glyphicon-trash"
],
];
}
if (empty($this->jstreeType)) {
$this->jstreeType = [
"#" => [
"max_children" => -1,
"max_depth" => -1,
"valid_children" => -1,
"icon" => "glyphicon glyphicon-th-list"
],
"default" => [
"max_children" => -1,
"max_depth" => -1,
"valid_children" => -1,
"icon" => "glyphicon glyphicon-list-alt"
],
"online" => [
"max_children" => 0,
"max_depth" => 0,
"valid_children" => 0,
"icon" => "glyphicon glyphicon-ok-sign"
],
"offline" => [
"max_children" => 0,
"max_depth" => 0,
"valid_children" => 0,
"icon" => "glyphicon glyphicon-minus-sign"
],
];
}
$this->getView()->registerJs("var jstreediv = '" . $this->jstreeDiv . "';", View::POS_HEAD);
$this->getView()->registerJs("var jstreetype = " . Json::encode($this->jstreeType) . ";", View::POS_HEAD);
$this->getView()->registerJs("var jstreeplugins = " . Json::encode($this->jstreePlugins) . ";", View::POS_HEAD);
$this->getView()->registerJs("var jstreeicons = " . Json::encode($this->jstreeIcons) . ";", View::POS_HEAD);
$this->getView()->registerJs("var jstreeContextMenue = " . Json::encode($this->jstreeContextMenue) . ";", View::POS_HEAD);
$this->getView()->registerJs("var jstreeMsg = " . Json::encode($this->jstreeMsg) . ";", View::POS_HEAD);
$this->getView()->registerJs("var initialOpenId = " . Json::encode($this->initialOpenId) . ";", View::POS_HEAD);
// Use with ActiveRecord Model and all Actions
if ($this->modelName) {
$this->controller = Yii::$app->controller->id;
if (empty($this->action_default))
$this->action_default = "index";
if (empty($this->action_click))
$this->action_click = "update";
// Create Needed URLs for JS
// e.g. /index.php?r=site/index
// or /site/index
$baseUrl = Url::to();
$this->getView()->registerJs("var url_default = '" . Url::to([$this->controller."/".$this->action_default]) . "';", View::POS_HEAD);
$this->getView()->registerJs("var url_click = '" . Url::to([$this->controller."/".$this->action_click]) . "';", View::POS_HEAD);
if(empty($this->jstreestatekey))
$this->jstreestatekey = $this->controller;
$this->getView()->registerJs("var jstreestatekey = " . Json::encode($this->jstreestatekey) . ";", View::POS_HEAD);
if (!isset($this->showIcons))
$this->showIcons = true;
if (empty($this->modelPropertyName))
$this->modelPropertyName = "name";
if (empty($this->modelPropertyId))
$this->modelPropertyId = "id";
if (empty($this->modelPropertyParentId))
$this->modelPropertyParentId = "parent_id";
if (empty($this->modelPropertyPosition))
$this->modelPropertyPosition = "sort";
if (empty($this->modelPropertyType))
$this->modelPropertyType = "type";
// Only Display Tree with loading Data via JSON URL
} else {
$this->getView()->registerJs("var jsonurl = '" . $this->jsonUrl . "';", View::POS_HEAD);
}
if (isset($_REQUEST["easytree"])) {
$this->treeaction();
}
}
public function run() {
parent::run();
}
/**
* Registers the needed assets
*/
public function registerAssets() {
$view = $this->getView();
JsTreeAsset::register($view);
}
// AJAX call for
// -> load: return full json for tree init
// -> move: change parent id and position of node
/*
* Handelns Ajax calls of different Operations
* fulljson: return full json for tree init
* create: create new node
* rename: change the name of the node
* position: move the node, change parent id and position of node
* delete: delete node
*/
public function treeaction() {
if (isset($_REQUEST["easytree"])) {
$operation = $_REQUEST["easytree"];
if ($operation == "fulljson")
self::sendJSON(self::treeChildren($this->modelName, $this->modelFirstParentId));
if ($operation == "move") {
$modelName = $this->modelName;
$model = $modelName::findOne($_POST["id"]);
if ($model) {
$model->{$this->modelPropertyParentId} = $_POST["parent"];
$model->{$this->modelPropertyPosition} = $_POST["position"];
// find all in the same node but without already re-orderd item
$sort = $modelName::find()
->where([$this->modelPropertyParentId => $_POST["parent"]])
->andWhere(['!=', $this->modelPropertyId, $_POST["id"]])
->orderBy($this->modelPropertyPosition)
->all();
// If moved to top
if ($_POST["position"] != 0)
$pos = 0;
else
$pos = 1;
foreach ($sort as $s) {
if ($pos == $_POST["position"])
$pos++;
$s->{$this->modelPropertyPosition} = $pos;
$s->save();
$pos++;
}
if ($model->save())
self::sendJSON(array('status' => 1));
}
}
if ($operation == "create") {
$modelName = $this->modelName;
$model = new $modelName;
if (!empty($_POST["duplicate"])) {
$duplicate_model = $modelName::findOne($_POST["duplicate"]);
$model->attributes = $duplicate_model->attributes;
}
$model->{$this->modelPropertyParentId} = $_POST["parent"];
$model->{$this->modelPropertyPosition} = $_POST["position"];
if (!empty($this->modelPropertyType) && !empty($_POST["type"]))
$model->{$this->modelPropertyType} = $_POST["type"];
if (!empty($this->modelPropertyName) && !empty($_POST["text"]))
$model->{$this->modelPropertyName} = $_POST["text"];
else
$model->{$this->modelPropertyName} = $this->jstreeMsg["newNode"]??"New Entry";
if ($model->save())
self::sendJSON(array('status' => 1, 'id' => $model->{$this->modelPropertyId}));
else {
$err_txt = "";
foreach($model->errors as $err) {
$err_txt.=$err[0];
}
self::sendJSON(array('status' => 0, 'err_msg' => $err_txt));
}
}
if ($operation == "rename") {
$modelName = $this->modelName;
$model = $modelName::findOne($_POST["id"]);
$model->{$this->modelPropertyName} = $_POST["text"];
if ($model->save())
self::sendJSON(array('status' => 1));
else
print_r($model->getErrors());
}
if ($operation == "delete") {
// check for children
$check = self::treeChildren($this->modelName, $_POST["id"]);
if (empty($check)) {
$modelName = $this->modelName;
$model = $modelName::findOne($_POST["id"]);
if (!$model) {
self::sendJSON(array('status' => 0, 'error' => $this->jstreeMsg['itemnotexisting']??""));
}
else {
if ($model->delete()) {
self::sendJSON(array('status' => 1));
}
else {
self::sendJSON(array('status' => 0, 'error' => $this->jstreeMsg['itemcantdel']??""));
}
}
}
else {
self::sendJSON(array('status' => 0, 'error' => $this->jstreeMsg['itemnodeletchildren']??""));
}
}
}
else {
return false;
}
}
/*
* Load Childitems of tree
*/
public function treeChildren($modelName, $parent_id = NULL) {
$models = $modelName::find()
->where([$this->modelPropertyParentId => $parent_id])
->orderBy($this->modelPropertyPosition)
->all();
$data = [];
foreach ($models as $item) {
$name = $item->{$this->modelPropertyName};
//if tree entry id is top id, set parent to null
if ($item->{$this->modelPropertyParentId} == $this->modelFirstParentId)
$parent = "#";
else
$parent = "id" . $item->{$this->modelPropertyParentId};
$type = $item->{$this->modelPropertyType}??"default";
$data[] = ['id' => "id" . $item->{$this->modelPropertyId}, 'parent' => $parent, 'type' => $type, 'text' => $name];
$mixin = self::treeChildren($modelName, $item->{$this->modelPropertyId});
if (!empty($mixin))
$data = array_merge($data, $mixin);
}
return $data;
}
static function sendJSON($json) {
header("HTTP/1.0 200 OK");
header('Content-type: text/json; charset=utf-8');
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
echo json_encode($json);
die();
}
}
?>