architecture.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. Architecture
  2. ============
  3. The architecture of the ``SonataAdminBundle`` is primarily inspired by the Django Admin
  4. Project, which is truly a great project. More information can be found at the
  5. `Django Project Website`_.
  6. If you followed the instructions on the :doc:`getting_started` page, you should by
  7. now have an ``Admin`` class and an ``Admin`` service. In this chapter, we'll discuss more in
  8. depth how it works.
  9. The Admin Class
  10. ---------------
  11. The ``Admin`` class maps a specific model to the rich CRUD interface provided by
  12. ``SonataAdminBundle``. In other words, using your ``Admin`` classes, you can configure
  13. what is shown by ``SonataAdminBundle`` in each CRUD action for the associated model.
  14. By now you've seen 3 of those actions in the ``getting started`` page: list,
  15. filter and form (for creation/editing). However, a fully configured ``Admin`` class
  16. can define more actions:
  17. * ``list``: The fields displayed in the list table
  18. * ``filter``: The fields available for filtering the list
  19. * ``form``: The fields used to create/edit the entity
  20. * ``show``: The fields used to show the entity
  21. * Batch actions: Actions that can be performed on a group of entities
  22. (e.g. bulk delete)
  23. The ``Sonata\AdminBundle\Admin\Admin`` class is provided as an easy way to
  24. map your models, by extending it. However, any implementation of the
  25. ``Sonata\AdminBundle\Admin\AdminInterface`` can be used to define an ``Admin``
  26. service. For each ``Admin`` service, the following required dependencies are
  27. automatically injected by the bundle:
  28. * ``ConfigurationPool``: configuration pool where all Admin class instances are stored
  29. * ``ModelManager``: service which handles specific code relating to your persistence layer (e.g. Doctrine ORM)
  30. * ``FormContractor``: builds the forms for the edit/create views using the Symfony ``FormBuilder``
  31. * ``ShowBuilder``: builds the show fields
  32. * ``ListBuilder``: builds the list fields
  33. * ``DatagridBuilder``: builds the filter fields
  34. * ``Request``: the received http request
  35. * ``RouteBuilder``: allows you to add routes for new actions and remove routes for default actions
  36. * ``RouterGenerator``: generates the different urls
  37. * ``SecurityHandler``: handles permissions for model instances and actions
  38. * ``Validator``: handles model validation
  39. * ``Translator``: generates translations
  40. * ``LabelTranslatorStrategy``: a strategy to use when generating labels
  41. * ``MenuFactory``: generates the side menu, depending on the current action
  42. .. note::
  43. Each of these dependencies is used for a specific task, briefly described above.
  44. If you wish to learn more about how they are used, check the respective documentation
  45. chapter. In most cases, you won't need to worry about their underlying implementation.
  46. All of these dependencies have default values that you can override when declaring any of
  47. your ``Admin`` services. This is done using a ``call`` to the matching "setter":
  48. .. configuration-block::
  49. .. code-block:: xml
  50. <service id="sonata.admin.post" class="Acme\DemoBundle\Admin\PostAdmin">
  51. <tag name="sonata.admin" manager_type="orm" group="Content" label="Post"/>
  52. <argument />
  53. <argument>Acme\DemoBundle\Entity\Post</argument>
  54. <argument />
  55. <call method="setLabelTranslatorStrategy">
  56. <argument>sonata.admin.label.strategy.underscore</argument>
  57. </call>
  58. </service>
  59. .. code-block:: yaml
  60. services:
  61. sonata.admin.post:
  62. class: Acme\DemoBundle\Admin\PostAdmin
  63. tags:
  64. - { name: sonata.admin, manager_type: orm, group: "Content", label: "Post" }
  65. arguments:
  66. - ~
  67. - Acme\DemoBundle\Entity\Post
  68. - ~
  69. calls:
  70. - [ setLabelTranslatorStrategy, ["@sonata.admin.label.strategy.underscore"]]
  71. Here, we declare the same ``Admin`` service as in the :doc:`getting_started` chapter, but using a
  72. different label translator strategy, replacing the default one. Notice that
  73. ``sonata.admin.label.strategy.underscore`` is a service provided by ``SonataAdminBundle``,
  74. but you could just as easily use a service of your own.
  75. CRUDController
  76. --------------
  77. The ``CRUDController`` contains the actions you have available to manipulate
  78. your model instances, like create, list, edit or delete. It uses the ``Admin``
  79. class to determine its behavior, like which fields to display in the edit form,
  80. or how to build the list view. Inside the ``CRUDController``, you can access the
  81. ``Admin`` class instance via the ``$admin`` variable.
  82. .. note::
  83. `CRUD is an acronym`_ for "Create, Read, Update and Delete"
  84. The ``CRUDController`` is no different from any other Symfony2 controller, meaning
  85. that you have all the usual options available to you, like getting services from
  86. the Dependency Injection Container (DIC).
  87. This is particularly useful if you decide to extend the ``CRUDController`` to
  88. add new actions or change the behavior of existing ones. You can specify which controller
  89. to use when declaring the ``Admin`` service by passing it as the 3rd argument. For example
  90. to set the controller to ``AcmeDemoBundle:PostAdmin``:
  91. .. configuration-block::
  92. .. code-block:: xml
  93. <services>
  94. <service id="sonata.admin.post" class="Acme\DemoBundle\Admin\PostAdmin">
  95. <tag name="sonata.admin" manager_type="orm" group="Content" label="Post"/>
  96. <argument />
  97. <argument>Acme\DemoBundle\Entity\Post</argument>
  98. <argument>AcmeDemoBundle:PostAdmin</argument>
  99. <call method="setTranslationDomain">
  100. <argument>AcmeDemoBundle</argument>
  101. </call>
  102. </service>
  103. </services>
  104. .. code-block:: yaml
  105. services:
  106. sonata.admin.post:
  107. class: Acme\DemoBundle\Admin\PostAdmin
  108. tags:
  109. - { name: sonata.admin, manager_type: orm, group: "Content", label: "Post" }
  110. arguments:
  111. - ~
  112. - Acme\DemoBundle\Entity\Post
  113. - AcmeDemoBundle:PostAdmin
  114. calls:
  115. - [ setTranslationDomain, [AcmeDemoBundle]]
  116. When extending ``CRUDController``, remember that the ``Admin`` class already has
  117. a set of automatically injected dependencies that are useful when implementing several
  118. scenarios. Refer to the existing ``CRUDController`` actions for examples of how to get
  119. the best out of them.
  120. In your overloaded CRUDController you can overload also these methods to limit
  121. the number of duplicated code from SonataAdmin:
  122. * ``preCreate``: called from ``createAction``
  123. * ``preEdit``: called from ``editAction``
  124. * ``preDelete``: called from ``deleteAction``
  125. * ``preShow``: called from ``showAction``
  126. * ``preList``: called from ``listAction``
  127. These methods are called after checking the access rights and after retrieving the object
  128. from database. You can use them if you need to redirect user to some other page under certain conditions.
  129. Fields Definition
  130. -----------------
  131. Your ``Admin`` class defines which of your model's fields will be available in each
  132. action defined in your ``CRUDController``. So, for each action, a list of field mappings
  133. is generated. These lists are implemented using the ``FieldDescriptionCollection`` class
  134. which stores instances of ``FieldDescriptionInterface``. Picking up on our previous
  135. ``PostAdmin`` class example:
  136. .. code-block:: php
  137. <?php
  138. namespace Acme\DemoBundle\Admin;
  139. use Sonata\AdminBundle\Admin\Admin;
  140. use Sonata\AdminBundle\Datagrid\ListMapper;
  141. use Sonata\AdminBundle\Datagrid\DatagridMapper;
  142. use Sonata\AdminBundle\Form\FormMapper;
  143. class PostAdmin extends Admin
  144. {
  145. // Fields to be shown on create/edit forms
  146. protected function configureFormFields(FormMapper $formMapper)
  147. {
  148. $formMapper
  149. ->add('title', 'text', array('label' => 'Post Title'))
  150. ->add('author', 'entity', array('class' => 'Acme\DemoBundle\Entity\User'))
  151. ->add('body') //if no type is specified, SonataAdminBundle tries to guess it
  152. ;
  153. }
  154. // Fields to be shown on filter forms
  155. protected function configureDatagridFilters(DatagridMapper $datagridMapper)
  156. {
  157. $datagridMapper
  158. ->add('title')
  159. ->add('author')
  160. ;
  161. }
  162. // Fields to be shown on lists
  163. protected function configureListFields(ListMapper $listMapper)
  164. {
  165. $listMapper
  166. ->addIdentifier('title')
  167. ->add('slug')
  168. ->add('author')
  169. ;
  170. }
  171. }
  172. Internally, the provided ``Admin`` class will use these three functions to create three
  173. ``FieldDescriptionCollection`` instances:
  174. * ``$formFieldDescriptions``, containing three ``FieldDescriptionInterface`` instances
  175. for title, author and body
  176. * ``$filterFieldDescriptions``, containing two ``FieldDescriptionInterface`` instances
  177. for title and author
  178. * ``$listFieldDescriptions``, containing three ``FieldDescriptionInterface`` instances
  179. for title, slug and author
  180. The actual ``FieldDescription`` implementation is provided by the storage abstraction
  181. bundle that you choose during the installation process, based on the
  182. ``BaseFieldDescription`` abstract class provided by ``SonataAdminBundle``.
  183. Each ``FieldDescription`` contains various details about a field mapping. Some of
  184. them are independent of the action in which they are used, like ``name`` or ``type``,
  185. while others are used only in specific actions. More information can be found in the
  186. ``BaseFieldDescription`` class file.
  187. In most scenarios, you will not actually need to handle the ``FieldDescription`` yourself.
  188. However, it is important that you know it exists and how it is used, as it sits at the
  189. core of ``SonataAdminBundle``.
  190. Templates
  191. ---------
  192. Like most actions, ``CRUDController`` actions use view files to render their output.
  193. ``SonataAdminBundle`` provides ready to use views as well as ways to easily customize them.
  194. The current implementation uses ``Twig`` as the template engine. All templates
  195. are located in the ``Resources/views`` directory of the bundle.
  196. There are two base templates, one of these is ultimately used in every action:
  197. * ``SonataAdminBundle::standard_layout.html.twig``
  198. * ``SonataAdminBundle::ajax_layout.html.twig``
  199. Like the names say, one if for standard calls, the other one for AJAX.
  200. The subfolders include Twig files for specific sections of ``SonataAdminBundle``:
  201. Block:
  202. ``SonataBlockBundle`` block views. By default there is only one, which
  203. displays all the mapped classes on the dashboard
  204. Button:
  205. Buttons such as ``Add new`` or ``Delete`` that you can see across several
  206. CRUD actions
  207. CRUD:
  208. Base views for every CRUD action, plus several field views for each field type
  209. Core:
  210. Dashboard view, together with deprecated and stub twig files.
  211. Form:
  212. Views related to form rendering
  213. Helper:
  214. A view providing a short object description, as part of a specific form field
  215. type provided by ``SonataAdminBundle``
  216. Pager:
  217. Pagination related view files
  218. These will be discussed in greater detail in the specific :doc:`templates` section, where
  219. you will also find instructions on how to configure ``SonataAdminBundle`` to use your templates
  220. instead of the default ones.
  221. Managing ``Admin`` Service
  222. --------------------------
  223. Your ``Admin`` service definitions are parsed when Symfony2 is loaded, and handled by
  224. the ``Pool`` class. This class, available as the ``sonata.admin.pool`` service from the
  225. DIC, handles the ``Admin`` classes, lazy-loading them on demand (to reduce overhead)
  226. and matching each of them to a group. It is also responsible for handling the top level
  227. template files, administration panel title and logo.
  228. Create child admins
  229. -------------------
  230. Let us say you have a ``PostAdmin`` and a ``CommentAdmin``. You can optionally declare the ``CommentAdmin``
  231. to be a child of the ``PostAdmin``. This will create new routes like, for example, ``/post/{id}/comment/list``,
  232. where the comments will automatically be filtered by post.
  233. To do this, you first need to call the ``addChild`` method in your PostAdmin service configuration :
  234. .. code-block:: xml
  235. <!-- app/config/config.xml -->
  236. <service id="sonata.news.admin.post" class="Sonata\NewsBundle\Admin\PostAdmin">
  237. ...
  238. <call method="addChild">
  239. <argument type="service" id="sonata.news.admin.comment" />
  240. </call>
  241. </service>
  242. Then, you have to set the CommentAdmin ``parentAssociationMapping`` attribute to ``post`` :
  243. .. code-block:: php
  244. <?php
  245. namespace Sonata\NewsBundle\Admin;
  246. ...
  247. class CommentAdmin extends Admin
  248. {
  249. protected $parentAssociationMapping = 'post';
  250. // OR
  251. public function getParentAssociationMapping()
  252. {
  253. return 'post';
  254. }
  255. }
  256. It also possible to set a dot-separated value, like ``post.author``, if your parent and child admins are not directly related.
  257. .. _`Django Project Website`: http://www.djangoproject.com/
  258. .. _`CRUD is an acronym`: http://en.wikipedia.org/wiki/CRUD