Search code examples
yii2yii2-basic-appyii-behaviour

Access the current instance of the model in behavior Yii2


is it possible to access the current instance of the model within the behavior method of an active record? What I'm planning, is to use the attribute value of the current instance to help in configuring the return value. Please see example below:

public function behaviors()
{
    $behaviors = parent::behaviors();

    $behaviors[] = [
        'class' => AttributeBehavior::className(),
        'attributes' => [
             ActiveRecord::EVENT_BEFORE_INSERT => 'line_number',
        ],
        'value' => function ($event) {
            $maxLineNum = $this->getQuestion()->max('line_number'); // Is this possible?

            return ++$maxLineNum;
        },
    ];

    return $behaviors;
}

Solution

  • Use owner property of behavior :

    $maxLineNum = $this->owner->getQuestion()->max('line_number');