routing.rst 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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+jinja
  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
  50. across the different ``Admin``'s actions. Instead of setting them in the
  51. template or doing other weird hacks, you can define a ``getPersistentParameters``
  52. method. This method will be used when a link is being generated.
  53. .. code-block:: php
  54. <?php
  55. class MediaAdmin extends Admin
  56. {
  57. public function getPersistentParameters()
  58. {
  59. if (!$this->getRequest()) {
  60. return array();
  61. }
  62. return array(
  63. 'provider' => $this->getRequest()->get('provider'),
  64. 'context' => $this->getRequest()->get('context', 'default'),
  65. );
  66. }
  67. }
  68. // the result :
  69. // $admin->generateUrl('create') => /admin/module/create?context=default