Class TreeBehavior
Tree Behavior.
Enables a model object to act as a node-based tree. Using Modified Preorder Tree Traversal
- Object
-
ModelBehavior
-
TreeBehavior
See: http://en.wikipedia.org/wiki/Tree_traversal
Link: http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html
Copyright: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
License: MIT License
Location: Cake/Model/Behavior/TreeBehavior.php
Properties summary
-
$_defaults
protectedDefaultsarray
-
$_deletedRow
protectedUsed to preserve state between delete callbacks.array
-
$errors
publicErrorsarray
Inherited Properties
Method Summary
- _getMax() protectedget the maximum index value in the table.
- _getMin() protectedget the minimum index value in the table.
- _getNode() protectedReturns a single node from the tree from its primary key
- _getOptions() protected
Convenience method to create default find() options from $arg when it is an associative array.
- _recoverByParentId() protected_recoverByParentId
- _setChildrenLevel() protectedSet level for descendents.
- _setParent() protectedSets the parent of the given node
- _sync() protectedTable sync method.
- afterDelete() publicAfter delete method.
- afterSave() publicAfter save method. Called after all saves
- beforeDelete() publicStores the record about to be deleted.
- beforeFind() publicRuns before a find() operation
- beforeSave() publicBefore save method. Called before all saves
- childCount() publicGet the number of child nodes
- children() publicGet the child nodes of the current model
- formatTreeList() publicFormats result of a find() call to a hierarchical array used for HTML select boxes.
- generateTreeList() publicA convenience method for returning a hierarchical array used for HTML select boxes
- getLevel() publicReturns the depth level of a node in the tree.
- getParentNode() publicGet the parent node
- getPath() publicGet the path to the given node
- moveDown() publicReorder the node without changing the parent.
- moveUp() publicReorder the node without changing the parent.
- recover() publicRecover a corrupted tree
- removeFromTree() publicRemove the current node from the tree, and reparent all children up one level.
- reorder() publicReorder method.
- setup() publicInitiate Tree behavior
- verify() publicCheck if the current tree is valid.
Method Detail
_getMax()source protected
_getMax( Model $Model , string $scope , string $right , integer $recursive -1 , boolean $created false )
get the maximum index value in the table.
Parameters
-
Model
$Model
- Model Instance.
- string
$scope
- Scoping conditions.
- string
$right
- Right value
- integer
$recursive
optional -1 - Recursive find value.
- boolean
$created
optional false - Whether it's a new record.
Returns
integer_getMin()source protected
_getMin( Model $Model , string $scope , string $left , integer $recursive -1 )
get the minimum index value in the table.
Parameters
-
Model
$Model
- Model instance.
- string
$scope
- Scoping conditions.
- string
$left
- Left value.
- integer
$recursive
optional -1 - Recurursive find value.
Returns
integer_getNode()source protected
_getNode( Model $Model , integer|string $id )
Returns a single node from the tree from its primary key
Parameters
-
Model
$Model
- Model using this behavior
- integer|string
$id
- The ID of the record to read
Returns
array|booleanThe record read or false
_getOptions()source protected
_getOptions( array $arg )
Convenience method to create default find() options from $arg when it is an associative array.
Parameters
- array
$arg
- Array
Returns
arrayOptions array
_recoverByParentId()source protected
_recoverByParentId( Model $Model , integer $counter 1 , integer|string|null $parentId null )
_recoverByParentId
Recursive helper function used by recover
Parameters
-
Model
$Model
- Model instance.
- integer
$counter
optional 1 - Counter
- integer|string|null
$parentId
optional null - Parent record Id
Returns
integercounter
_setChildrenLevel()source protected
_setChildrenLevel( Model $Model , integer|string $id )
Set level for descendents.
Parameters
-
Model
$Model
- Model using this behavior.
- integer|string
$id
- Record ID
_setParent()source protected
_setParent( Model $Model , integer|string|null $parentId null , boolean $created false )
Sets the parent of the given node
The force parameter is used to override the "don't change the parent to the current parent" logic in the event of recovering a corrupted table, or creating new nodes. Otherwise it should always be false. In reality this method could be private, since calling save with parent_id set also calls setParent
Parameters
-
Model
$Model
- Model using this behavior
- integer|string|null
$parentId
optional null - Parent record Id
- boolean
$created
optional false - True if newly created record else false.
Returns
booleantrue on success, false on failure
_sync()source protected
_sync( Model $Model , integer $shift , string $dir '+' , array $conditions array() , boolean $created false , string $field 'both' )
Table sync method.
Handles table sync operations, Taking account of the behavior scope.
Parameters
-
Model
$Model
- Model instance.
- integer
$shift
- Shift by.
- string
$dir
optional '+' - Direction.
- array
$conditions
optional array() - Conditions.
- boolean
$created
optional false - Whether it's a new record.
- string
$field
optional 'both' - Field type.
afterDelete()source public
afterDelete( Model $Model )
After delete method.
Will delete the current node and all children using the deleteAll method and sync the table
Parameters
-
Model
$Model
- Model using this behavior
Returns
booleantrue to continue, false to abort the delete
Overrides
ModelBehavior::afterDelete()
afterSave()source public
afterSave( Model $Model , boolean $created , array $options array() )
After save method. Called after all saves
Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the parameters to be saved.
Parameters
-
Model
$Model
- Model using this behavior.
- boolean
$created
- indicates whether the node just saved was created or updated
- array
$options
optional array() - Options passed from Model::save().
Returns
booleantrue on success, false on failure
Overrides
ModelBehavior::afterSave()
beforeDelete()source public
beforeDelete( Model $Model , boolean $cascade true )
Stores the record about to be deleted.
This is used to delete child nodes in the afterDelete.
Parameters
-
Model
$Model
- Model using this behavior.
- boolean
$cascade
optional true - If true records that depend on this record will also be deleted
Returns
booleanOverrides
ModelBehavior::beforeDelete()
beforeFind()source public
beforeFind( Model $Model , array $query )
Runs before a find() operation
Parameters
-
Model
$Model
- Model using the behavior
- array
$query
- Query parameters as set by cake
Returns
arrayOverrides
ModelBehavior::beforeFind()
beforeSave()source public
beforeSave( Model $Model , array $options array() )
Before save method. Called before all saves
Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the parameters to be saved. For newly created nodes with NO parent the left and right field values are set directly by this method bypassing the setParent logic.
Parameters
-
Model
$Model
- Model using this behavior
- array
$options
optional array() - Options passed from Model::save().
Returns
booleantrue to continue, false to abort the save
See
Model::save()Overrides
ModelBehavior::beforeSave()
childCount()source public
childCount( Model $Model , integer|string|boolean $id null , boolean $direct false )
Get the number of child nodes
If the direct parameter is set to true, only the direct children are counted (based upon the parent_id field) If false is passed for the id parameter, all top level nodes are counted, or all nodes are counted.
Parameters
-
Model
$Model
- Model using this behavior
- integer|string|boolean
$id
optional null - The ID of the record to read or false to read all top level nodes
- boolean
$direct
optional false - whether to count direct, or all, children
Returns
integernumber of child nodes
Link
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::childCountchildren()source public
children( Model $Model , integer|string $id null , boolean $direct false , string|array $fields null , string $order null , integer $limit null , integer $page 1 , integer $recursive null )
Get the child nodes of the current model
If the direct parameter is set to true, only the direct children are returned (based upon the parent_id field) If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted.
Parameters
-
Model
$Model
- Model using this behavior
- integer|string
$id
optional null - The ID of the record to read
- boolean
$direct
optional false - whether to return only the direct, or all, children
- string|array
$fields
optional null - Either a single string of a field name, or an array of field names
- string
$order
optional null - SQL ORDER BY conditions (e.g. "price DESC" or "name ASC") defaults to the tree order
- integer
$limit
optional null - SQL LIMIT clause, for calculating items per page.
- integer
$page
optional 1 - Page number, for accessing paged data
- integer
$recursive
optional null - The number of levels deep to fetch associated records
Returns
arrayArray of child nodes
Link
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::childrenformatTreeList()source public
formatTreeList( Model $Model , array $results , array $options array() )
Formats result of a find() call to a hierarchical array used for HTML select boxes.
Note that when using your own find() call this expects the order to be "left" field asc in order to generate the same result as using generateTreeList() directly.
Options:
- 'keyPath': A string path to the key, i.e. "{n}.Post.id"
- 'valuePath': A string path to the value, i.e. "{n}.Post.title"
- 'spacer': The character or characters which will be repeated
Parameters
-
Model
$Model
- Model using this behavior
- array
$results
- Result array of a find() call
- array
$options
optional array() - Options
Returns
arrayAn associative array of records, where the id is the key, and the display field is the value
generateTreeList()source public
generateTreeList( Model $Model , string|array $conditions null , string $keyPath null , string $valuePath null , string $spacer '_' , integer $recursive null )
A convenience method for returning a hierarchical array used for HTML select boxes
Parameters
-
Model
$Model
- Model using this behavior
- string|array
$conditions
optional null - SQL conditions as a string or as an array('field' =>'value',...)
- string
$keyPath
optional null - A string path to the key, i.e. "{n}.Post.id"
- string
$valuePath
optional null - A string path to the value, i.e. "{n}.Post.title"
- string
$spacer
optional '_' - The character or characters which will be repeated
- integer
$recursive
optional null - The number of levels deep to fetch associated records
Returns
arrayAn associative array of records, where the id is the key, and the display field is the value
Link
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::generateTreeListgetLevel()source public
getLevel( Model $Model , integer|string|null $id null )
Returns the depth level of a node in the tree.
Parameters
-
Model
$Model
- Model using this behavior
- integer|string|null
$id
optional null - The primary key for record to get the level of.
Returns
integer|booleanInteger of the level or false if the node does not exist.
getParentNode()source public
getParentNode( Model $Model , integer|string $id null , string|array $fields null , integer $recursive null )
Get the parent node
reads the parent id and returns this node
Parameters
-
Model
$Model
- Model using this behavior
- integer|string
$id
optional null - The ID of the record to read
- string|array
$fields
optional null - Fields to get
- integer
$recursive
optional null - The number of levels deep to fetch associated records
Returns
array|booleanArray of data for the parent node
Link
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getParentNodegetPath()source public
getPath( Model $Model , integer|string|null $id null , string|array|null $fields null , integer|null $recursive null )
Get the path to the given node
Parameters
-
Model
$Model
- Model using this behavior
- integer|string|null
$id
optional null - The ID of the record to read
- string|array|null
$fields
optional null - Either a single string of a field name, or an array of field names
- integer|null
$recursive
optional null - The number of levels deep to fetch associated records
Returns
arrayArray of nodes from top most parent to current node
Link
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getPathmoveDown()source public
moveDown( Model $Model , integer|string|null $id null , integer|boolean $number 1 )
Reorder the node without changing the parent.
If the node is the last child, or is a top level node with no subsequent node this method will return false
Parameters
-
Model
$Model
- Model using this behavior
- integer|string|null
$id
optional null - The ID of the record to move
- integer|boolean
$number
optional 1 - how many places to move the node or true to move to last position
Returns
booleantrue on success, false on failure
Link
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveDownmoveUp()source public
moveUp( Model $Model , integer|string|null $id null , integer|boolean $number 1 )
Reorder the node without changing the parent.
If the node is the first child, or is a top level node with no previous node this method will return false
Parameters
-
Model
$Model
- Model using this behavior
- integer|string|null
$id
optional null - The ID of the record to move
- integer|boolean
$number
optional 1 - how many places to move the node, or true to move to first position
Returns
booleantrue on success, false on failure
Link
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveUprecover()source public
recover( Model $Model , string $mode 'parent' , string|integer|null $missingParentAction null )
Recover a corrupted tree
The mode parameter is used to specify the source of info that is valid/correct. The opposite source of data will be populated based upon that source of info. E.g. if the MPTT fields are corrupt or empty, with the $mode 'parent' the values of the parent_id field will be used to populate the left and right fields. The missingParentAction parameter only applies to "parent" mode and determines what to do if the parent field contains an id that is not present.
Parameters
-
Model
$Model
- Model using this behavior
- string
$mode
optional 'parent' - parent or tree
- string|integer|null
$missingParentAction
optional null 'return' to do nothing and return, 'delete' to delete, or the id of the parent to set as the parent_id
Returns
booleantrue on success, false on failure
Link
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::recoverremoveFromTree()source public
removeFromTree( Model $Model , integer|string|null $id null , boolean $delete false )
Remove the current node from the tree, and reparent all children up one level.
If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted after the children are reparented.
Parameters
-
Model
$Model
- Model using this behavior
- integer|string|null
$id
optional null - The ID of the record to remove
- boolean
$delete
optional false - whether to delete the node after reparenting children (if any)
Returns
booleantrue on success, false on failure
Link
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::removeFromTreereorder()source public
reorder( Model $Model , array $options array() )
Reorder method.
Reorders the nodes (and child nodes) of the tree according to the field and direction specified in the parameters. This method does not change the parent of any node.
Requires a valid tree, by default it verifies the tree before beginning.
Options:
- 'id' id of record to use as top node for reordering
- 'field' Which field to use in reordering defaults to displayField
- 'order' Direction to order either DESC or ASC (defaults to ASC)
- 'verify' Whether or not to verify the tree before reorder. defaults to true.
Parameters
-
Model
$Model
- Model using this behavior
- array
$options
optional array() - array of options to use in reordering.
Returns
booleantrue on success, false on failure
Link
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::reordersetup()source public
setup( Model $Model , array $config array() )
Initiate Tree behavior
Parameters
-
Model
$Model
- using this behavior of model
- array
$config
optional array() - array of configuration settings.
Overrides
ModelBehavior::setup()
verify()source public
verify( Model $Model )
Check if the current tree is valid.
Returns true if the tree is valid otherwise an array of (type, incorrect left/right index, message)
Parameters
-
Model
$Model
- Model using this behavior
Returns
mixedtrue if the tree is valid or empty, otherwise an array of (error type [index, node], [incorrect left/right index,node id], message)
Link
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::verifyMethods inherited from ModelBehavior
_addToWhitelist()source protected
_addToWhitelist( Model $model , string $field )
If $model's whitelist property is non-empty, $field will be added to it. Note: this method should only be used in beforeValidate or beforeSave to ensure that it only modifies the whitelist for the current save operation. Also make sure you explicitly set the value of the field which you are allowing.
Parameters
-
Model
$model
- Model using this behavior
- string
$field
- Field to be added to $model's whitelist
afterFind()source public
afterFind( Model $model , mixed $results , boolean $primary false )
After find callback. Can be used to modify any results returned by find.
Parameters
-
Model
$model
- Model using this behavior
- mixed
$results
- The results of the find operation
- boolean
$primary
optional false - Whether this model is being queried directly (vs. being queried as an association)
Returns
mixedAn array value will replace the value of $results - any other value will be ignored.
afterValidate()source public
afterValidate( Model $model )
afterValidate is called just after model data was validated, you can use this callback to perform any data cleanup or preparation if needed
Parameters
-
Model
$model
- Model using this behavior
Returns
mixedFalse will stop this event from being passed to other behaviors
beforeValidate()source public
beforeValidate( Model $model , array $options array() )
beforeValidate is called before a model is validated, you can use this callback to add behavior validation rules into a models validate array. Returning false will allow you to make the validation fail.
Parameters
-
Model
$model
- Model using this behavior
- array
$options
optional array() - Options passed from Model::save().
Returns
mixedFalse or null will abort the operation. Any other result will continue.
See
Model::save()cleanup()source public
cleanup( Model $model )
Clean up any initialization this behavior has done on a model. Called when a behavior is dynamically detached from a model using Model::detach().
Parameters
-
Model
$model
- Model using this behavior
See
BehaviorCollection::detach()onError()source public
onError( Model $model , string $error )
DataSource error callback
Parameters
-
Model
$model
- Model using this behavior
- string
$error
- Error generated in DataSource
Methods inherited from Object
_mergeVars()source protected
_mergeVars( array $properties , string $class , boolean $normalize true )
Merges this objects $property with the property in $class' definition. This classes value for the property will be merged on top of $class'
This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine this method as an empty function.
Parameters
- array
$properties
- The name of the properties to merge.
- string
$class
- The class to merge the property with.
- boolean
$normalize
optional true - Set to true to run the properties through Hash::normalize() before merging.
_set()source protected
_set( array $properties array() )
Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.
Parameters
- array
$properties
optional array() - An associative array containing properties and corresponding values.
_stop()source protected
_stop( integer|string $status 0 )
Stop execution of the current script. Wraps exit() making testing easier.
Parameters
- integer|string
$status
optional 0 - see http://php.net/exit for values
dispatchMethod()source public
dispatchMethod( string $method , array $params array() )
Calls a method on this object with the given parameters. Provides an OO wrapper for call_user_func_array
Parameters
- string
$method
- Name of the method to call
- array
$params
optional array() - Parameter list to use when calling $method
Returns
mixedReturns the result of the method call
log()source public
log( string $msg , integer $type LOG_ERR , null|string|array $scope null )
Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.
Parameters
- string
$msg
- Log message
- integer
$type
optional LOG_ERR - Error type constant. Defined in app/Config/core.php.
- null|string|array
$scope
optional null The scope(s) a log message is being created in. See CakeLog::config() for more information on logging scopes.
Returns
booleanSuccess of log write
requestAction()source public
requestAction( string|array $url , array $extra array() )
Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.
Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()
Passing POST and GET data
POST and GET data can be simulated in requestAction. Use $extra['url']
for GET data. The $extra['data']
parameter allows POST data simulation.
Parameters
- string|array
$url
String or array-based URL. Unlike other URL arrays in CakePHP, this URL will not automatically handle passed and named arguments in the $url parameter.
- array
$extra
optional array() if array includes the key "return" it sets the AutoRender to true. Can also be used to submit GET/POST data, and named/passed arguments.
Returns
mixedBoolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.
toString()source public
toString( )
Object-to-string conversion. Each class can override this method as necessary.
Returns
stringThe name of this class
Properties detail
$_defaultssource
protected array
Defaults
array( 'parent' => 'parent_id', 'left' => 'lft', 'right' => 'rght', 'level' => null, 'scope' => '1 = 1', 'type' => 'nested', '__parentChange' => false, 'recursive' => -1 )
© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
http://api.cakephp.org/2.8/class-TreeBehavior.html