我正在使用etrepat/baum laravel包以及jstree jQuery插件来管理类别。
在jstree中,有一个用于移动节点的 move_node.jstree 方法。它有一些有用的属性来获取有关移动操作的信息,例如parent
,old
_parent
,...和position
,它返回父节点中移动的子节点的新位置。
另一方面,也有移动节点的方法。(here)。但是没有像makeNthChildOf()
这样的方法可以用来将子节点放在父节点的特定位置。像:
$node->makeNthChildOf(newPosition , $parent)
现在在客户端移动节点我写了这个:
$treeview.on('move_node.jstree', function (e, data) {
$.post('/move', {
'CategoryID': data.node.id,
'newParent': data.parent,
'oldParent': data.old_parent
}, function (res) {
data.instance.open_node(data.parent);
}, 'json');
});
在laravel中:
public function move (Request $request)
{
$data = $request->only('newParent', 'oldParent', 'CategoryID');
$currentNode = Category::find($data['CategoryID']);
if ($data['newParent'] == '#') {
$currentNode->makeRoot();
} else {
$currentNode->makeChildOf($data['newParent']);
}
return ['success' => true];
}
但是上面的代码不能做我想要的,只能将节点从父节点移动到另一个父节点。
我想知道有没有其他方法来执行该功能?
答案 0 :(得分:0)
好的,我相信我找到了实现这个目标的方法。我把它快速地扔到了一起,很抱歉这些丑陋的代码:
首先,我使用ajax,因此我使用节点信息
构建表单数据formData = "node_id=" + data.node.id + "&name=" + data.node.text + "&_token=" + $("input[name=_token]").val() + "&parent=" + data.parent + "&position=" + data.position + "&old_position=" + data.old_position + "&old_parent=" + data.old_parent;
接下来,我们创建一个快速辅助函数来确定当前节点所处的位置。它将循环遍历父节点的所有后代并按字面计算它们。
private function findPosition($decendants, $position) {
$i = 0;
foreach ($decendants as $decendant) {
if ($i == $position) {
return $decendant;
}
$i++;
}
}
然后我们可以将节点移动到它的正确位置:
//We first need to account for moving within same node, but below it's current position. Without this the node will be moved 1 position off.
if ($parent == $old_parent) {
if ($position > $old_position) {
$position = $position +1;
}
}
$parent = BaumTest::find($parent);
$decendants = $parent->getImmediateDescendants();
$moveTo = $this->findPosition($decendants, $position);
$node = BaumTest::find($node_id);
//If the parent we are moving to doesn't have any decendents, just move it now
if ($parent->isLeaf()) {
$node->makeChildOf($parent);
return array("error"=>false, "successMessage"=>"Sucessfully Moved!");
}
//This takes care of it we are moving it into the last position
if (is_null($moveTo)) {
$node->makeLastChildOf($parent);
return array("error"=>false, "successMessage"=>"Sucessfully Moved!");
}
$node->moveToLeftOf($moveTo);