CakePHP Tree Behavior Ordering Issue

Today I found a simple issue with CakePHP’s Tree Behavior.

When saving a model with an empty parent_id Tree Behavior recalculates left and right node.

The consequence is to alter an existing order putting the record at the end of the list.

This problem manifests only with root items with an empty parent_id. Sub trees are safe from this issue!

The Solution:

A basic solution may be to disable Tree Behavior when saving a root item:

// Model beforeSave() callback
if ( empty($this->data[$this->alias]['parent_id']) ) {
    $this->Behaviors->disable('Tree');
}

This works form be because I change Tree items order with TreeBehavior::moveDown() and TreeBehavior::moveUp() methods.

Powered By DT Author Box

Written by MPeg

MPeg

Hi, i’m Marco (aka MPeg) and i’m very appassionate in web interfaces developing. I like so much code style and optimization. I spoke PHP, Javascript, HTML5, CSS3 My best friends are CakePHP, CakePOWER, jQuery, LESS, TwitterBootstrap, Underscore, Backbone, Sencha Touch, jQueryUI, jQuery Mobile.

Author’s Website

Posted in CakePHP, Tips & Tricks and tagged , , , , , , . Bookmark the permalink. RSS feed for this post. Leave a trackback.

Swedish Greys - a WordPress theme from Nordic Themepark.