Validate model with related


I’m trying to save model A together with it’s related models B using only A->save() method in my controller. Relation between A & B is 1:N.

I’m saving B using link() in A->afterSave() method. However, I need to validate models B, which link() does not provide. Should I just manually set foreign keys in models B and use B->save() methods or is there some better solution?

Moreover, I’d like to validate models B together with model A and prevent model A from saving in case of errors in models B. How can I achieve this? Is there some way to prevent model from saving in afterValidate() or beforeSave() methods?

Thanks for help!


I can share you a solution following:

  • You should use Json to validate on client

  • In action, you should using Yii->transaction by using try{}catch(){}

  • If B is not saved, B should use transaction->rollback, and validate by Json to client.

  • If B is not saved, A should use transaction->rollback , and validate by Json to client.

Good luck.