Class TreeBehavior
Tree Behavior.
Enables a model object to act as a node-based tree. Using Modified Preorder Tree Traversal
- Object
-
ModelBehavior -
TreeBehavior
Copyright: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
License: MIT License
See: http://en.wikipedia.org/wiki/Tree_traversal
Link: http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html
Located at Cake/Model/Behavior/TreeBehavior.php
Method Detail
_getMaxsource 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
$recursiveoptional -1 - Recursive find value.
- boolean
$createdoptional false - Whether it's a new record.
Returns
integerint
_getMinsource 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
$recursiveoptional -1 - Recurursive find value.
Returns
integerint
_getNodesource 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
_getOptionssource 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
_recoverByParentIdsource protected
_recoverByParentId( Model $Model , integer $counter 1 , mixed $parentId null )
_recoverByParentId
Recursive helper function used by recover
Parameters
-
Model$Model - Model instance.
- integer
$counteroptional 1 - Counter
- mixed
$parentIdoptional null - Parent record Id
Returns
integercounter
_setChildrenLevelsource protected
_setChildrenLevel( Model $Model , integer|string $id )
Set level for descendents.
Parameters
-
Model$Model - Model using this behavior.
- integer|string
$id - Record ID
_setParentsource protected
_setParent( Model $Model , integer|string $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
$parentIdoptional null - Parent record Id
- boolean
$createdoptional false - True if newly created record else false.
Returns
booleantrue on success, false on failure
_syncsource 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
$diroptional '+' - Direction.
- array
$conditionsoptional array() - Conditions.
- boolean
$createdoptional false - Whether it's a new record.
- string
$fieldoptional 'both' - Field type.
afterDeletesource 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() afterSavesource 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
$optionsoptional array() - Options passed from Model::save().
Returns
booleantrue on success, false on failure
Overrides
ModelBehavior::afterSave() beforeDeletesource 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
$cascadeoptional true - If true records that depend on this record will also be deleted
Returns
booleanbool
Overrides
ModelBehavior::beforeDelete() beforeFindsource 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
arrayarray
Overrides
ModelBehavior::beforeFind() beforeSavesource 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
$optionsoptional array() - Options passed from Model::save().
Returns
booleantrue to continue, false to abort the save
See
Model::save()Overrides
ModelBehavior::beforeSave() childCountsource 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
$idoptional null - The ID of the record to read or false to read all top level nodes
- boolean
$directoptional 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::childCountchildrensource 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
$idoptional null - The ID of the record to read
- boolean
$directoptional false - whether to return only the direct, or all, children
- string|array
$fieldsoptional null - Either a single string of a field name, or an array of field names
- string
$orderoptional null - SQL ORDER BY conditions (e.g. "price DESC" or "name ASC") defaults to the tree order
- integer
$limitoptional null - SQL LIMIT clause, for calculating items per page.
- integer
$pageoptional 1 - Page number, for accessing paged data
- integer
$recursiveoptional 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::childrenformatTreeListsource 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
$optionsoptional array() - Options
Returns
arrayAn associative array of records, where the id is the key, and the display field is the value
generateTreeListsource 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
$conditionsoptional null - SQL conditions as a string or as an array('field' =>'value',...)
- string
$keyPathoptional null - A string path to the key, i.e. "{n}.Post.id"
- string
$valuePathoptional null - A string path to the value, i.e. "{n}.Post.title"
- string
$spaceroptional '_' - The character or characters which will be repeated
- integer
$recursiveoptional 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::generateTreeListgetLevelsource public
getLevel( Model $Model , integer|string $id null )
Returns the depth level of a node in the tree.
Parameters
-
Model$Model - Model using this behavior
- integer|string
$idoptional 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.
getParentNodesource 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
$idoptional null - The ID of the record to read
- string|array
$fieldsoptional null - Fields to get
- integer
$recursiveoptional 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::getParentNodegetPathsource public
getPath( Model $Model , integer|string $id null , string|array $fields null , integer $recursive null )
Get the path to the given node
Parameters
-
Model$Model - Model using this behavior
- integer|string
$idoptional null - The ID of the record to read
- string|array
$fieldsoptional null - Either a single string of a field name, or an array of field names
- integer
$recursiveoptional 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::getPathmoveDownsource public
moveDown( Model $Model , integer|string $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
$idoptional null - The ID of the record to move
- integer|boolean
$numberoptional 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::moveDownmoveUpsource public
moveUp( Model $Model , integer|string $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
$idoptional null - The ID of the record to move
- integer|boolean
$numberoptional 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::moveUprecoversource public
recover( Model $Model , string $mode 'parent' , string|integer $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
$modeoptional 'parent' - parent or tree
- string|integer
$missingParentActionoptional 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::recoverremoveFromTreesource public
removeFromTree( Model $Model , integer|string $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
$idoptional null - The ID of the record to remove
- boolean
$deleteoptional 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::removeFromTreereordersource 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
$optionsoptional 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::reordersetupsource public
setup( Model $Model , array $config array() )
Initiate Tree behavior
Parameters
-
Model$Model - using this behavior of model
- array
$configoptional array() - array of configuration settings.
Overrides
ModelBehavior::setup() verifysource 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
_addToWhitelistsource 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
afterFindsource 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
$primaryoptional 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.
afterValidatesource 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
beforeValidatesource 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
$optionsoptional array() - Options passed from Model::save().
Returns
mixedFalse or null will abort the operation. Any other result will continue.
See
Model::save()cleanupsource 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()onErrorsource 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
_mergeVarssource 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
$normalizeoptional true - Set to true to run the properties through Hash::normalize() before merging.
_setsource 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
$propertiesoptional array() - An associative array containing properties and corresponding values.
_stopsource protected
_stop( integer|string $status 0 )
Stop execution of the current script. Wraps exit() making testing easier.
Parameters
- integer|string
$statusoptional 0 - see http://php.net/exit for values
dispatchMethodsource 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
$paramsoptional array() - Parameter list to use when calling $method
Returns
mixedReturns the result of the method call
logsource 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
$typeoptional LOG_ERR - Error type constant. Defined in app/Config/core.php.
- null|string|array
$scopeoptional 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
requestActionsource 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
$extraoptional 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.
toStringsource public
toString( )
Object-to-string conversion. Each class can override this method as necessary.
Returns
stringThe name of this class
Properties summary
Properties inherited from ModelBehavior
$mapMethodssource
public array
Allows the mapping of preg-compatible regular expressions to public or private methods in this class, where the array key is a /-delimited regular expression, and the value is a class method. Similar to the functionality of the findBy* / findAllBy* magic methods.
array() $settingssource
public array
Contains configuration settings for use with individual model objects. This is used because if multiple models use this Behavior, each will use the same object instance. Individual model settings should be stored as an associative array, keyed off of the model name.
See
Model::$aliasarray()
© 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.7/class-TreeBehavior.html