How to redirect user to the same page in actionDelete()

I have extended the default UserController:actionDelete() to make it check, if the user isn’t trying to delete themselves from the user table / model. If such situation is detected, I want to display some nice info screen:

Yii::$app->session->setFlash('error', You cannot delete yourself.');

return $this->refresh();

Doing so causes app to throw Method Not Allowed (#405) error:

Method Not Allowed. This URL can only handle the following request methods: POST.

How can I avoid the above or how to handle such request correctly?

Your action is about to delete record right now so when you try to refresh the page you actually try to do the same over and over again.

It doesnt work anyway because clearly you have some ‘post’ verb filter in your controller engaged and when you refresh (http 302 code) you are initializing new ‘get’ request:

So you can e.g. redirect user to another view (back, where the user made decision of delete) with flash message set as above ( that’s the better way) or disable the ‘verb’ filter then distinct behavior of ‘actionDelete’ depending of ‘get’ / ‘post’ request (but this introduces some mess).

Yes, I have figured out the same. But thanks for confirming the idea.

Since I don’t know where to redirect user (as actionDelete can be triggered from many places), I have ended up with setting:


In all places which can trigger delete (in my case user/index and user/view routes / views / actions).

And then redirecting back to that remembered address whenever I need to display a flash:

return $this->goBack();

This seems to be working so far. Thanks.

1 Like

Do you have behavior that limtis that method to post only?
If Yes then you cannot do that.

But why would you want to refresh a delete method? Isn’t that going to cause 404 for deleted model?

Yes. This is added automatically by Gii and this is good. I do want to allow my user to perform delete operation only in POST and never in GET.

I don’t want to refresh delete method. I was looking for a way to redirect user back to the page where they was when clicking delete (either “view” or “index” views).

Original implementation (generated by Gii) is as simple as:

public function actionDelete($id)

    return $this->redirect(['index']);

As you can see, no checking at all. Therefore it always assumes that delete is successful and always redirects user to the “index” view. I.e. if you trigger delete operation from “view” view and that delete won’t be successful for any reason, you will land back to “index” not back to “view”.

I want to redirect it back (where they was) in any situation that prevents actual delete from happening.

As you see my answer to Bart’s answer, I have managed to resolve this issue.

1 Like