I have an application using CakePHP 2.x and jstree 3.2.1. I'm trying to figure out how it's possible to specify the position of a node when writing it to the database with CakePHP. The position itself comes from jstree...
When I drag and drop items with jstree the request URL gives me:
-
id
- The ID of the node being dragged. -
parent_id
- The (parent) ID which the node has been dropped under. -
position
- this is an integer which starts at 0 and represents the position at whichid
has been dropped underparent_id
. For example, aposition
of2
means it should appear in 3rd position (3rd, not 2nd, because they start at 0).
CakePHP has methods in it's Tree Behaviour that allow you to move nodes in its Tree up and down. These methods are called moveUp()
and moveDown()
respectively.
I don't understand how it's possible to use the data provided from jstree with Cake's Tree behaviour such that you could update/save positions correctly.
Passing position
to moveUp()
or moveDown()
would produce the wrong result. Why?
- If jstree provides
position = 2
and you were moving the 10th item in a list callingmoveUp(2)
through CakePHP means it would go into the 8th position, not the 2nd as intended. Similarly,moveDown(2)
would move it to the 12th, which is not the desired outcome.
The schema that Cake has for it's Tree Behavior does not have a "position" field. Rather it uses lft
and rght
fields. The schema has:
-
id
- ID of each individual tree node (auto increment) -
parent_id
- parent ID of the node.NULL
if top level (no parent). -
lft
,rght
- for MPTT logic. Cake generates these values automatically. They can be used to determine the order usingORDER BY lft ASC
. But they are not the same values asposition
provided by jstree, and are unique for every row -
name
- text name of the node.
For example, consider the following tree:
- D (
id
=149
)- 1 (
id
=150
,parent_id
=149
) - 2 (
id
=153
,parent_id
=149
) - 3 (
id
=154
,parent_id
=149
) - 4 (
id
=155
,parent_id
=149
) - 5 (
id
=156
,parent_id
=149
)
- 1 (
In the database Cake stores this as follows:
If I was to use jstree to drag and drop "2" so it appears between "3" and "4" it would make a request containing the following GET variables:
id
= 153
. This is the ID of "2"
parent_id
= 149
. This is the ID of "D" which is the parent node of "2".
position
= 2
. This means the 3rd position (3rd because positions start from 0).
But I cannot regenerate the lft
and rght
values from this data? And moveUp()
/moveDown()
are not helpful here because position
cannot be passed in a way that would make this work.
The tree should be in the following order. id
and parent_id
should not change, but lft
and rght
must, because everything under "D" has effectively been re-ordered:
- D
- 1
- 3
- 2 (moved)
- 4
- 5
Can anyone help with this?