Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 how to redirect to an action without hardcoding route name?

Tags:

symfony

I've an abstract CRUDController extending Controller. In my newAction, os success, i'd like to redirect to showAction($slug) using redirect method:

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

But newAction is actually called in the subclass UserController, so i can't specify route name $route in my 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)
    }

}

An example of routes:

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
like image 495
gremo Avatar asked Dec 21 '22 00:12

gremo


1 Answers

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

abstract public function getRoute();

And then, on your concrete class, or subclass, UserController, you just override and implement that:

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

So when, on your abstract class, call the actual interface method, the OO will handle everything like magic:

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

Maybe try that and let us know if does the job right.

like image 79
Daniel Ribeiro Avatar answered Dec 26 '22 16:12

Daniel Ribeiro