E
E
EVOSandru62017-09-21 08:48:43
Yii
EVOSandru6, 2017-09-21 08:48:43

How in Yii2 in behavior can't get into onBeforeSave?

Good afternoon,
There is a behavior that I connect in the model:

...
public function behaviors()
    {
        return [
            [
                'class'=>LogBehavior::classname()
            ]
        ];
    }
...
public function beforeSave($insert)
    {

        echo 'Сюда тоже не поапдаю(';
        die;

        if($insert) {
            $this->user_id = Yii::$app->user->id;
        }
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

Log Behavior :
...
public function attach($owner)
    {
        parent::attach($owner);

        $owner->on(ActiveRecord::EVENT_BEFORE_INSERT,[$this,'onBeforeSave']);
        $owner->on(ActiveRecord::EVENT_BEFORE_UPDATE,[$this,'onBeforeSave']);
        $owner->on(ActiveRecord::EVENT_AFTER_INSERT,[$this,'onAfterSave']);
        $owner->on(ActiveRecord::EVENT_AFTER_UPDATE,[$this,'onAfterSave']);
        $owner->on(ActiveRecord::EVENT_AFTER_DELETE,[$this,'onAfterDelete']);

...
}

public function onBeforeSave()
    {
        echo 'Сюда не попадаю, При сохранении модели эта запись не отображается';
        die;
 }
...

Only if I explicitly set parameters for the model, then I get into beforeSave of the model:
$model = new Results();
        $model->option_id = $this->option_id;

        $time = time();
        $model->date_create = date('Y-m-d H:i:s',$time);
        $model->date_update = date('Y-m-d H:i:s',$time);
        $model->date_update_stamp = $time;
        $model->date_create_stamp = $time;
        $model->author_id = Yii::$app->user->id;
        $model->exist = 1;
        $model->sort = 1;
       if(!$model->save()) {
            echo $model->printErrors();
        } else {
            echo 'ok';
        }
        die();

How so? I should get into beforeSave ( further in onBeforeSave ) before saving modedi before validation.
It is learned that if I do not explicitly specify additional. attributes from the listing above, then $model->printErrors() complains that the attributes are not integers. Although these attributes are not mandatory.
What could be the problem? In attach ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Agafonov, 2017-09-21
@Tairesh

It is not worth attaching to events in attach, it is better to do this:

public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_INSERT => 'onBeforeSave',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'onBeforeSave',
        ];
    }

But in essence, my crystal ball says that you simply don’t save anything, for example, validation fails, or you incorrectly overridden the ActiveRecord::save method or something else. Use a debugger!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question