CakePHP 2.x 系 遷移前の情報を取得してリダイレクトを行う
1つのControllerのfunctionを使いまわしたとき、リダイレクト先が固定されてしまったていたので、refererを使って少々強引に解決した。
postsというコントローラにaddファンクションがあり、topsというコントローラでも同じaddファンクションを使用している
// AppController <?php public function rfr() { // 適当なfunction名をつけて if ($this->request->referer('/') == '/posts') { // 遷移前のcontroller名を取得 // 以下リダイレクト処理 $this->redirect(array('controller' => 'posts', 'action' => 'index')); } else { $this->redirect(array('controller' => 'tops', 'action' => 'index')); } }
$this->request->refererで遷移前の情報を取得することができる
また、('/')をつけることでURLではなく、コントローラ名のみ取得できる
最後に、このfunctionを使いたいコントローラで呼び出す
// PostsController <?php // ...... public function add() { // add処理....... if ($this->Post->save($this->request->data)) { $this->rfr(); // AppControllerのfunctionを呼び出す } }
多分これでうまくいくと思う。もっとクールな方法があるぜって方はコメント書いていただけたらありがたいです。
インターン受かるといいなぁ…関係ないけど
以上