How To Use Beforesave()

I have auction and when someone bid on something, before that bid is saved into database I need to check if that bid is lower from last bid. Could someone explain me how to use beforeSave() to check it. Where tu put beforeSave(), in controller or model

Firstly beforeSave function override goes into the model.

I think you need to check not in beforeSave but in afterValidate, so

if your fields are all validates, you also check that your bid is lower from last.

thank you. but still not sure how ti implement afterValidate

Create a method in the model and use name of that method as a validator in rules. This is called an inline validator.

An example:

public function isHighestBid($attribute, $params) {

   if (/*some condition*/){

       $this->addError($attribute, Yii::t('app','error message'));

       return false;


   return true;


There is however a possibility of a race condition when after the model gets validates and before it is saved to the database (the transaction will be commited) another model will be saved and the condition for highest bid won’t be true anymore. You may not care for this, because the probability is very low. But if you would, the best way is to use transactions and define a constraint right in the database. Then add proper error checking when save() will throw an exception because of this. PostgreSQL can do it, don’t know about other databases.

Oh I just noticed that it’s not the highest bid condition but that doesn’t change the meaning of my post.

thank you, I will try that