2017-10-24 20 views
1

symfonyでデータベース内の要素が見つからないときにコントローラからカスタム404エラーページにリダイレクトする方法はありますか?例えばsymfony、404ステータスリターンコードを持つ404カスタムエラーページにリダイレクト(またはレンダリング)

:ルートは独自の価値を提供(多くの場合、IDを、それがユーザ名または単純なテキストことができる)場合

if (empty($db_result)) { 
    /* DO REDIRECT */ 
} else { 
    return $this->render('default/correct.html.twig'); 
} 

答えて

2

、その後、SensioFrameworkExtraBundle ParamConverterは自動的にエンティティ(データベースレコード)を取得することができます。

独自にメソッドのシグネチャを用いることで、より簡単かつ迅速な方法があるので、一般的である
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; 
/** 
* @Route("/blog/{id}") 
* @ParamConverter("post", class="SensioBlogBundle:Post") 
*/ 
public function showAction(Post $post) 
{ 
} 

:「PRODの環境(ライブサーバー)で

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
/** 
* @Route("/blog/{id}") 
*/ 
public function showAction(Post $post) 
{ 
    // $post will be the database record - if it exists 
} 

、もしそこにあなたが/blog/1にアクセスしたとき、id:1(例えば) 'post'テーブルにレコードがないと、フレームワークは404エラーを生成します。

自分自身(またはそのより複雑な)で検索をしたい場合は、「NotFoundHttpException」を作る、またはそうするように、コントローラのショートカットを使用することができます。

public function indexAction(/* parameters, like Request, or maybe $id */) 
{ 
    // retrieve the object from database 
    $product = ...; 
    if (!$product) { 
     throw $this->createNotFoundException('The product does not exist'); 
    } 

    return $this->render(...); 
} 
0

は、この方法を試してみてください。

if (is_null($db_result)) { 
    throw $this->createNotFoundException(); 
} else { 
    return $this->render('default/correct.html.twig'); 
} 
関連する問題