alevit
alevit

Reputation: 21

Symfony, redirect to (or render) 404 custom error page with 404 status return code

In symfony how can I redirect to a custom 404 error page from a controller when I don't find an element in the database?

For example:

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

Upvotes: 2

Views: 7124

Answers (2)

Alister Bulman
Alister Bulman

Reputation: 35149

If the route provides a unique value (often an ID, but it could be a username or simple text), then the SensioFrameworkExtraBundle ParamConverter can fetch an entity (a database record) automatically.

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)
{
}

That is so common there is an even easier and quicker way, by using the method signature on its own:

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

In a 'prod' environment (the live server), if there is no record in the 'post' table, id:1 (for example) when you visit /blog/1, then the framework will make a 404 error for you.

If you want to do the search by yourself (or its more complex), you can make a 'NotFoundHttpException', or use the controller shortcut to do so:

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(...);
}

Upvotes: 3

Cesur APAYDIN
Cesur APAYDIN

Reputation: 836

Try this way:

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

Upvotes: 4

Related Questions