Trait kartik\tree\models\TreeTrait

Implemented bykartik\tree\models\Tree

Trait that must be used by the Tree model

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$boolAttribs array The list of boolean value attributes kartik\tree\models\TreeTrait
$falseAttribs array The default list of boolean attributes with initial value = false kartik\tree\models\TreeTrait

Public Methods

Hide inherited methods

MethodDescriptionDefined By
activateNode() Activates a node (for undoing a soft deletion scenario) kartik\tree\models\TreeTrait
attributeLabels() Returns the attribute labels. kartik\tree\models\TreeTrait
behaviors() Returns a list of behaviors that this component should behave as. kartik\tree\models\TreeTrait
createQuery() Creates the query for the kartik\tree\models\Tree active record kartik\tree\models\TreeTrait
find() Creates an kartik\tree\models\TreeQuery instance for query purpose. kartik\tree\models\TreeTrait
getBreadcrumbs() Generate and return the breadcrumbs for the node. kartik\tree\models\TreeTrait
initDefaults() Initialize default values kartik\tree\models\TreeTrait
isActive() Validate if the node is active kartik\tree\models\TreeTrait
isChildAllowed() Validate if the node can have children kartik\tree\models\TreeTrait
isCollapsed() Validate if the node is collapsed kartik\tree\models\TreeTrait
isDisabled() Validate if the node is disabled kartik\tree\models\TreeTrait
isMovable() Validate if the node is movable kartik\tree\models\TreeTrait
isReadonly() Validate if the node is readonly kartik\tree\models\TreeTrait
isRemovable() Validate if the node is removable kartik\tree\models\TreeTrait
isRemovableAll() Validate if the node is removable with descendants kartik\tree\models\TreeTrait
isSelected() Validate if the node is selected kartik\tree\models\TreeTrait
isVisible() Validate if the node is visible kartik\tree\models\TreeTrait
removeNode() Removes a node kartik\tree\models\TreeTrait
rules() Returns the validation rules for attributes. kartik\tree\models\TreeTrait
tableName() Declares the name of the database table associated with this AR class. kartik\tree\models\TreeTrait
transactions() Declares which DB operations should be performed within a transaction in different scenarios. kartik\tree\models\TreeTrait

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
parse() Parses an attribute value if set - else returns the default kartik\tree\models\TreeTrait
setDefault() Sets default value of a model attribute kartik\tree\models\TreeTrait

Property Details

$boolAttribs public static property

The list of boolean value attributes

public static array $boolAttribs = [
    'active''selected''disabled''readonly''visible''collapsed''movable_u''movable_d''movable_r''movable_l''removable''removable_all''child_allowed'
]
$falseAttribs public static property

The default list of boolean attributes with initial value = false

public static array $falseAttribs = [
    'selected''disabled''readonly''collapsed''removable_all'
]

Method Details

activateNode() public method

Activates a node (for undoing a soft deletion scenario)

public boolean activateNode ( $currNode true )
$currNode boolean

Whether to update the current node value also

return boolean

Status of activation

throws yii\base\InvalidConfigException
attributeLabels() public method

Returns the attribute labels.

Attribute labels are mainly used for display purpose. For example, given an attribute firstName, we can declare a label First Name which is more user-friendly and can be displayed to end users.

By default an attribute label is generated using yii\db\ActiveRecord::generateAttributeLabel(). This method allows you to explicitly specify attribute labels.

Note, in order to inherit labels defined in the parent class, a child class needs to merge the parent labels with child labels using functions such as array_merge().

See also yii\db\ActiveRecord::generateAttributeLabel().

public array attributeLabels ( )
return array

Attribute labels (name => label)

throws yii\base\InvalidConfigException
behaviors() public method

Returns a list of behaviors that this component should behave as.

Child classes may override this method to specify the behaviors they want to behave as.

The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

Note that a behavior class must extend from yii\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using kartik\tree\models\Tree::getBehavior() or be detached using kartik\tree\models\Tree::detachBehavior(). Anonymous behaviors can not be retrieved or detached.

Behaviors declared in this method will be attached to the component automatically (on demand).

public array behaviors ( )
return array

The behavior configurations.

throws yii\base\InvalidConfigException
createQuery() public static method

Creates the query for the kartik\tree\models\Tree active record

public static kartik\tree\models\TreeQuery createQuery ( )
return kartik\tree\models\TreeQuery

The newly created kartik\tree\models\TreeQuery instance.

find() public static method

Creates an kartik\tree\models\TreeQuery instance for query purpose.

The returned kartik\tree\models\TreeQuery instance can be further customized by calling methods defined in yii\db\ActiveQueryInterface before one() or all() is called to return populated ActiveRecord instances. For example,

// find the node whose ID is 1
$node = CustomTree::find()->where(['id' => 1])->one();

// find all active nodes and order them by their price:
$nodes = CustomTree::find()
    ->where(['status' => 1])
    ->orderBy('price')
    ->all();

This method is also called by yii\db\ActiveRecord::hasOne() and yii\db\ActiveRecord::hasMany() to create a relational query.

You may override this method to return a customized query. For example,

use kartik\tree\models\Tree;

class CustomTree extends Tree
{
    public static function find()
    {
        // use CustomTreeQuery instead of the default ActiveQuery
        return new CustomTreeQuery(get_called_class());
    }
}

The following code shows how to apply a default condition for all queries:

use kartik\tree\models\Tree;

class CustomTree extends Tree
{
    public static function find()
    {
        return parent::find()->where(['deleted' => false]);
    }
}

// Use andWhere()/orWhere() to apply the default condition
// SELECT FROM custom_tree WHERE `deleted`=:deleted AND price > 30
$nodes = CustomTree::find()->andWhere('price > 30')->all();

// Use where() to ignore the default condition
// SELECT FROM custom_tree WHERE price > 30
$nodes = CustomTree::find()->where('price > 30')->all();
public static kartik\tree\models\TreeQuery find ( )
return kartik\tree\models\TreeQuery

The newly created kartik\tree\models\TreeQuery instance.

getBreadcrumbs() public method

Generate and return the breadcrumbs for the node.

public string getBreadcrumbs ( $depth 1, $glue ' » ', $currCss 'kv-crumb-active', $new 'Untitled' )
$depth integer

The breadcrumbs parent depth

$glue string

The pattern to separate the breadcrumbs

$currCss string

The CSS class to be set for current node

$new string

The name to be displayed for a new node

return string

The parsed breadcrumbs

throws yii\base\InvalidConfigException
initDefaults() public method

Initialize default values

public void initDefaults ( )
isActive() public method

Validate if the node is active

public boolean isActive ( )
isChildAllowed() public method

Validate if the node can have children

public boolean isChildAllowed ( )
isCollapsed() public method

Validate if the node is collapsed

public boolean isCollapsed ( )
isDisabled() public method

Validate if the node is disabled

public boolean isDisabled ( )
isMovable() public method

Validate if the node is movable

public boolean isMovable ( $dir )
$dir string

The direction, one of 'u', 'd', 'l', or 'r'

isReadonly() public method

Validate if the node is readonly

public boolean isReadonly ( )
isRemovable() public method

Validate if the node is removable

public boolean isRemovable ( )
isRemovableAll() public method

Validate if the node is removable with descendants

public boolean isRemovableAll ( )
isSelected() public method

Validate if the node is selected

public boolean isSelected ( )
isVisible() public method

Validate if the node is visible

public boolean isVisible ( )
parse() protected method

Parses an attribute value if set - else returns the default

protected mixed parse ( $attr, $default true )
$attr string

The attribute name

$default mixed

The attribute default value

removeNode() public method

Removes a node

public boolean removeNode ( $softDelete true, $currNode true )
$softDelete boolean

Whether to soft delete or hard delete

$currNode boolean

Whether to update the current node value also

return boolean

Status of activation/inactivation

throws yii\base\InvalidConfigException
rules() public method

Returns the validation rules for attributes.

Validation rules are used by kartik\tree\models\Tree::validate() to check if attribute values are valid. Child classes may override this method to declare different validation rules.

Each rule is an array with the following structure:

[
    ['attribute1', 'attribute2'],
    'validator type',
    'on' => ['scenario1', 'scenario2'],
    //...other parameters...
]

where

  • attribute list: required, specifies the attributes array to be validated, for single attribute you can pass a string;
  • validator type: required, specifies the validator to be used. It can be a built-in validator name, a method name of the model class, an anonymous function, or a validator class name.
  • on: optional, specifies the kartik\tree\models\Tree::scenarios() array in which the validation rule can be applied. If this option is not set, the rule will apply to all scenarios.
  • additional name-value pairs can be specified to initialize the corresponding validator properties. Please refer to individual validator class API for possible properties.

A validator can be either an object of a class extending yii\validators\Validator, or a model class method (called inline validator) that has the following signature:

// $params refers to validation parameters given in the rule
function validatorName($attribute, $params)

In the above $attribute refers to the attribute currently being validated while $params contains an array of validator configuration options such as max in case of string validator. The value of the attribute currently being validated can be accessed as $this->$attribute. Note the $ before attribute; this is taking the value of the variable $attribute and using it as the name of the property to access.

Yii also provides a set of built-in validators. Each one has an alias name which can be used when specifying a validation rule.

Below are some examples:

[
    // built-in "required" validator
    [['username', 'password'], 'required'],
    // built-in "string" validator customized with "min" and "max" properties
    ['username', 'string', 'min' => 3, 'max' => 12],
    // built-in "compare" validator that is used in "register" scenario only
    ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],
    // an inline validator defined via the "authenticate()" method in the model class
    ['password', 'authenticate', 'on' => 'login'],
    // a validator of class "DateRangeValidator"
    ['dateRange', 'DateRangeValidator'],
];

Note, in order to inherit rules defined in the parent class, a child class needs to merge the parent rules with child rules using functions such as array_merge().

See also kartik\tree\models\Tree::scenarios().

public array rules ( )
return array

Validation rules

throws yii\base\InvalidConfigException
setDefault() protected method

Sets default value of a model attribute

protected void setDefault ( $attr, $val )
$attr string

The attribute name

$val mixed

The default value

tableName() public static method

Declares the name of the database table associated with this AR class.

By default this method returns the class name as the table name by calling yii\helpers\Inflector::camel2id() with prefix yii\db\Connection::$tablePrefix. For example if yii\db\Connection::$tablePrefix is tbl_, Customer becomes tbl_customer, and OrderItem becomes tbl_order_item. You may override this method if the table is not named after this convention.

public static string tableName ( )
return string

The table name

transactions() public method

Declares which DB operations should be performed within a transaction in different scenarios.

The supported DB operations are: kartik\tree\models\Tree::OP_INSERT, kartik\tree\models\Tree::OP_UPDATE and kartik\tree\models\Tree::OP_DELETE, which correspond to the kartik\tree\models\Tree::insert(), kartik\tree\models\Tree::update() and kartik\tree\models\Tree::delete() methods, respectively. By default, these methods are NOT enclosed in a DB transaction.

In some scenarios, to ensure data consistency, you may want to enclose some or all of them in transactions. You can do so by overriding this method and returning the operations that need to be transactional. For example,

return [
    'admin' => Tree::OP_INSERT,
    'api' => Tree::OP_INSERT | Tree::OP_UPDATE | Tree::OP_DELETE,
    // the above is equivalent to the following:
    // 'api' => Tree::OP_ALL,

];

The above declaration specifies that in the "admin" scenario, the insert operation kartik\tree\models\Tree::insert()) should be done in a transaction; and in the "api" scenario, all the operations should be done in a transaction.

public array transactions ( )
return array

The declarations of transactional operations. The array keys are scenarios names, and the array values are the corresponding transaction operations.