routing.rst 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. Routing
  2. =======
  3. The default routes used in the CRUD controller are accessible through the
  4. ``Admin`` class.
  5. The ``Admin`` class contains two routing methods:
  6. * ``getRoutes()``: Returns the available routes;
  7. * ``generateUrl($name, $options)``: Generates the related routes.
  8. Routing Definition
  9. ------------------
  10. You can set a ``baseRouteName`` property inside your ``Admin`` class, which
  11. represents the route prefix.
  12. .. code-block:: php
  13. <?php
  14. class PostAdmin extends Admin
  15. {
  16. protected $baseRouteName = 'news_post_admin';
  17. }
  18. If no ``baseRouteName`` is defined then the Admin will pick one for you, built
  19. in the following format: 'admin_vendor_bundlename_entityname_action'. If the
  20. Admin fails to find the best baseRouteName then a ``RuntimeException`` will
  21. be thrown.
  22. The same goes for the ``baseRoutePattern``.
  23. Routing usage
  24. -------------
  25. Inside a CRUD template, a route can be generated by using the ``Admin`` class.
  26. .. code-block:: html
  27. <a href="{{ admin.generateUrl('list') }}">List</a>
  28. <a href="{{ admin.generateUrl('list', params|merge('page': 1) }}">List</a>
  29. Create a route
  30. --------------
  31. You can easily register new routes by defining them in the ``Admin`` class.
  32. Only Admin routes should be registered this way. Of course this requires the
  33. related action to be defined in the controller.
  34. As route is always generated with the ``Admin`` context, it can only be
  35. defined by its name.
  36. .. code-block:: php
  37. <?php
  38. use Sonata\AdminBundle\Route\RouteCollection;
  39. class MediaAdmin extends Admin
  40. {
  41. protected function configureRoutes(RouteCollection $collection)
  42. {
  43. $collection->add('duplicate');
  44. $collection->add('view', $this->getRouterIdParameter().'/view');
  45. }
  46. }
  47. Persistent parameters
  48. ---------------------
  49. In some cases, the interface might be required to pass the same parameters across the different ``Admin``'s actions.
  50. Instead of setting them in the template or doing other weird hacks, you can define a ``getPersistentParameters``
  51. method. This method will be used when a link is being generated.
  52. .. code-block:: php
  53. <?php
  54. class MediaAdmin extends Admin
  55. {
  56. public function getPersistentParameters()
  57. {
  58. if (!$this->getRequest()) {
  59. return array();
  60. }
  61. return array(
  62. 'provider' => $this->getRequest()->get('provider'),
  63. 'context' => $this->getRequest()->get('context', 'default'),
  64. );
  65. }
  66. }
  67. // the result :
  68. // $admin->generateUrl('create') => /admin/module/create?context=default