Symfony2 how to redirect to an action without a routing coding name?

I have abstract CRUDController extending Controller. In my newActionos success, I would like to redirect to showAction($slug)using the method redirect:

return $this->redirect($this->generateUrl($route, $params));

But newAction it is actually called in a subclass UserController , so I cannot specify the route name $routein CRUDController.

class UserController extends CRUDController { }

abstract class CRUDController extends Controller
{
    /** @Template */
    public function showAction($slug) { }

    /** @Template */
    public function newAction(Request $request)
    {

        $model = $this->createModel();
        $form  = $this->createForm($this->createType(), $model);

        if('GET' == $request->getMethod())
            return array('form' => $form->createView());

        $form->bindRequest($request);

        if(!$form->isValid()) return array(
            'errors' => $this->get('validator')->validate($model),
            'form'   => $form->createView()
        );

        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($model);
        $em->flush();

        // Success, redirect to showAction($slug)
    }

}

Route example:

users_show:
  pattern: /users/show/{slug}
  defaults: { _controller: AcmeSecurityBundle:User:show }
  requirements:
    _method:  GET

users_new:
  pattern: /users/new
  defaults: { _controller: AcmeSecurityBundle:User:new }
  requirements:
    _method:  GET

users_create:
  pattern: /users/new
  defaults: { _controller: AcmeSecurityBundle:User:new }
  requirements:
    _method:  POST
+4
source share
2 answers

You can work with the whole concept of OO and have an interface method getRouteName()in your abstract class:

abstract public function getRoute();

And then, in your specific class or subclass of UserController, you simply override and implement this:

public function getRoute()
{
    return 'whatever:Route:YouWant';
}

, , OO , , magic:

public function newAction(Request $request)
{
    ...
    return $this->redirect($this->generateUrl($this->getRouteName(), $params));
}

, , .

+11

-, sf:

interface specialRedirect
{
    public function specialRedirect($slug);
}

, - :

public function newAction(Request $request)
{
    // ...
    $this->specialRedirect('user', $slug);
}

public function specialRedirect($slug)
{
    // If you don't want to do anything special, just act like normal
    // Success, redirect to showAction($slug)
}

UserController / :

public function specialRedirect($slug)
{
    //here is where you can specify your route name.
    $route = 'Foo_Bar';
    return $this->redirect($this->generateUrl($route, $params));

}
0

All Articles