Hello.
I have a doubt about how i do for handling database errors on YII2.
I have an gii app called Ambientes that interact with the ambientes table.
Ambientes table have child’s on SapAmbientes table (1 to N relationship).
When I delete on Ambientes a record who have child, displays an default error on routed default page. I don’t want this. I need to redirect it to app who’s call, and simple add a flash message (or similar) on this (view or index) views.
I already did research for a few days, has some solutions for yii1 but I did not find anything that works on yii2.
I would like to know of the veterans how do the bank exception handling not to divert to that generic error page in YII2.
I made some changes, but it didn’t look nice.
Table Environments 1 - N Table SapAmbientes
Where I put on a model class called Ambientes
Public function beforeDelete ()
{
$ P = new \ app \ models \ SapPerfis ();
\ Yii :: $ app-> getSession () -> remove ('deleteAmbientes');
$ Return = $ p :: find () -> where (['environment' => $ this-> environment]) -> one ();
If ($ return! == null) {
\ Yii :: $ app-> getSession () -> setFlash ('deleteAmbientes', Yii :: t (' app ',' Can not delete this record. ') There are some dependents records.'));
Return FALSE;
} Else {
Return TRUE;
}
}
on a controller I modified the actionDelete
<font face="Courier New">Public function actionDelete ($ id)
{
If (! Yii :: $ app-> user-> can ('deleteAmbientes'))
Throw new ForbiddenHttpException;
$ Record = $ this-> findModel ($ id);
If ($ record! == null) {
Try {
$ Ret = $ record-> delete ();
If ($ ret === FALSE) {
If (\ Yii :: $ app-> getSession () -> hasFlash ('deleteAmbientes')) {
Return $ this-> render ('view', ['Model' => $ this-> findModel ($ id),
]);
}
}
Return $ this-> redirect (['index']);
} Catch (\ ErrorException $ e) {
Yii :: warning ("The record can not be deleted.");
Return $ this-> redirect (['index']);
}
}
Return $ this-> redirect (['index']);
}
</font>
And on the view I put
<font face="Courier New"><? = (\ Yii :: $ app-> getSession () -> hasFlash ('deleteAmbientes')?
'<Div class = "alert-danger"> <p class = "error-summary">'
. \ Yii :: $ app-> getSession () -> getFlash ('deleteAmbientes')
. ' (<a href="javascript:history.back(-1)" class="backLink"> '
.Yii :: t ('app', 'Return previous page')
. ') </a> </ p> </ div>'
(I.e.
)?></font><div>
For now it works, but I have to make the error code validation, rather than just redirect a database error.
How do you do for such treatment?