3

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?

Community
  • 1
  • 1
trejder
  • 17,148
  • 27
  • 124
  • 216

1 Answers1

1

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.

Manquer
  • 7,390
  • 8
  • 42
  • 69
  • I'm accepting your answer, though in my opinion, isn't full. While, I agree with your point of view, you seem to forgot about situations, where calling `beforeDelete` _after_ your code is a must. For example, when you're [using transactions in Yii event](http://stackoverflow.com/a/24511751/1469208), you have to call `parent::beforeDelete()` _after_ your code and only, when transaction succeeds without errors. You don't have other way to inform Yii, that deletion of relational records is fine and Yii can proceed with deletion of master record. – trejder Jul 01 '14 at 13:43
  • 1
    agreed, there are cases where you should **never** call before, i merely wished to illustrate that calling before is never a good idea, therefore always call later. – Manquer Jul 01 '14 at 13:59