Chisskarzz
Chisskarzz

Reputation: 171

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;
}

Upvotes: 1

Views: 469

Answers (1)

Insane Skull
Insane Skull

Reputation: 9358

Use owner property of behavior :

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

Upvotes: 2

Related Questions