yiimodelyii-events

When should I call parent::beforeDelete() in my Yii model


Up until now I was always calling / checking result of parent::beforeDelete() before I my own code:

public function beforeDelete()
{
    if(parent::beforeValidate())
    {
        $this->short = strtolower(preg_replace("/[^a-zA-Z0-9_-]+/", "", (string)$this->short));

        return TRUE;
    }

    return FALSE;
}

(an example of stripping incorrect characters from one of model's properties)

But now, I found this answer:

public function beforeDelete()
{
    foreach($this->qualifications as $q)
        $q->delete();
    return parent::beforeDelete();
}

(an example of deleting record with related models)

and I'm confused? When should I call parent::beforeDelete()? Always before my code is executed, always after execution of my code or depending on context / what I'm doing?


Solution

  • Some methods have event listeners attached, in this case the onBeforeDelete event. You have to call parent implementation so that the event is raised properly.

    Always in the last is safer because if you call it before your code , and your code modifies something which would have caused the code in beforeDelete to fail,that won't happen now as beforeDelete was triggered earlier .

    In your first example you are calling beforeValidate in your beforeDelete function that is completely different.