action_list.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. The List View
  2. =============
  3. .. note::
  4. This document is a stub representing a new work in progress. If you're reading
  5. this you can help contribute, **no matter what your experience level with Sonata
  6. is**. Check out the `issues on GitHub`_ for more information about how to get involved.
  7. This document will cover the List view which you use to browse the objects in your
  8. system. It will cover configuration of the list itself and the filters you can use
  9. to control what's visible.
  10. Basic configuration
  11. -------------------
  12. SonataAdmin Options that may affect the list view:
  13. .. code-block:: yaml
  14. sonata_admin:
  15. templates:
  16. list: SonataAdminBundle:CRUD:list.html.twig
  17. action: SonataAdminBundle:CRUD:action.html.twig
  18. select: SonataAdminBundle:CRUD:list__select.html.twig
  19. list_block: SonataAdminBundle:Block:block_admin_list.html.twig
  20. short_object_description: SonataAdminBundle:Helper:short-object-description.html.twig
  21. batch: SonataAdminBundle:CRUD:list__batch.html.twig
  22. inner_list_row: SonataAdminBundle:CRUD:list_inner_row.html.twig
  23. base_list_field: SonataAdminBundle:CRUD:base_list_field.html.twig
  24. pager_links: SonataAdminBundle:Pager:links.html.twig
  25. pager_results: SonataAdminBundle:Pager:results.html.twig
  26. To do:
  27. - a note about Routes and how disabling them disables the related action
  28. - adding custom columns
  29. Customizing the fields displayed on the list page
  30. -------------------------------------------------
  31. You can customize the columns displayed on the list through the ``configureListFields`` method.
  32. Here is an example:
  33. .. code-block:: php
  34. <?php
  35. // ...
  36. public function configureListFields(ListMapper $listMapper)
  37. {
  38. $listMapper
  39. // addIdentifier allows to specify that this column
  40. // will provide a link to the entity
  41. // (edit or show route, depends on your access rights)
  42. ->addIdentifier('name')
  43. // you may specify the field type directly as the
  44. // second argument instead of in the options
  45. ->add('isVariation', 'boolean')
  46. // if null, the type will be guessed
  47. ->add('enabled', null, array(
  48. 'editable' => true
  49. ))
  50. // we can add options to the field depending on the type
  51. ->add('price', 'currency', array(
  52. 'currency' => $this->currencyDetector->getCurrency()->getLabel()
  53. ))
  54. // Here we specify which property is used to render the label of each entity in the list
  55. ->add('productCategories', null, array(
  56. 'associated_property' => 'name')
  57. )
  58. // you may also use dotted-notation to access
  59. // specific properties of a relation to the entity
  60. ->add('image.name')
  61. // You may also specify the actions you want to be displayed in the list
  62. ->add('_action', 'actions', array(
  63. 'actions' => array(
  64. 'show' => array(),
  65. 'edit' => array(),
  66. 'delete' => array(),
  67. )
  68. ))
  69. ;
  70. }
  71. Options
  72. ^^^^^^^
  73. .. note::
  74. * ``(m)`` stands for mandatory
  75. * ``(o)`` stands for optional
  76. - ``type`` (m): defines the field type - mandatory for the field description itself but will try to detect the type automatically if not specified
  77. - ``template`` (o): the template used to render the field
  78. - ``label`` (o): the name used for the column's title
  79. - ``link_parameters`` (o): add link parameter to the related Admin class when the ``Admin::generateUrl`` is called
  80. - ``code`` (o): the method name to retrieve the related value
  81. - ``associated_property`` (o): property path to retrieve the "string" representation of the collection element, or a closure with the element as argument and return a string.
  82. - ``identifier`` (o): if set to true a link appears on the value to edit the element
  83. Available types and associated options
  84. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  85. .. note::
  86. ``(m)`` means that option is mandatory
  87. +-----------+----------------+-----------------------------------------------------------------------+
  88. | Type | Options | Description |
  89. +===========+================+=======================================================================+
  90. | actions | actions | List of available actions |
  91. +-----------+----------------+-----------------------------------------------------------------------+
  92. | batch | | Renders a checkbox |
  93. +-----------+----------------+-----------------------------------------------------------------------+
  94. | select | | Renders a select box |
  95. +-----------+----------------+-----------------------------------------------------------------------+
  96. | array | | Displays an array |
  97. +-----------+----------------+-----------------------------------------------------------------------+
  98. | boolean | ajax_hidden | Yes/No; ajax_hidden allows to hide list field during an AJAX context. |
  99. +-----------+----------------+-----------------------------------------------------------------------+
  100. | boolean | editable | Yes/No; editable allows to edit directly from the list if authorized. |
  101. +-----------+----------------+-----------------------------------------------------------------------+
  102. | choice | choices | Possible choices |
  103. + +----------------+-----------------------------------------------------------------------+
  104. | | multiple | Is it a multiple choice option? Defaults to false. |
  105. + +----------------+-----------------------------------------------------------------------+
  106. | | delimiter | Separator of values if multiple. |
  107. + +----------------+-----------------------------------------------------------------------+
  108. | | catalogue | Translation catalogue. |
  109. +-----------+----------------+-----------------------------------------------------------------------+
  110. | currency | currency (m) | A currency string (EUR or USD for instance). |
  111. +-----------+----------------+-----------------------------------------------------------------------+
  112. | date | format | A format understandable by Twig's ``date`` function. |
  113. +-----------+----------------+-----------------------------------------------------------------------+
  114. | datetime | format | A format understandable by Twig's ``date`` function. |
  115. +-----------+----------------+-----------------------------------------------------------------------+
  116. | percent | | Renders value as a percentage. |
  117. +-----------+----------------+-----------------------------------------------------------------------+
  118. | string | | Renders a simple string. |
  119. +-----------+----------------+-----------------------------------------------------------------------+
  120. | time | | Renders a datetime's time with format ``H:i:s``. |
  121. +-----------+----------------+-----------------------------------------------------------------------+
  122. | trans | catalogue | Translates the value with catalogue ``catalogue`` if defined. |
  123. +-----------+----------------+-----------------------------------------------------------------------+
  124. | url | url | Adds a link with url ``url`` to the displayed value |
  125. + +----------------+-----------------------------------------------------------------------+
  126. | | route | Give a route to generate the url |
  127. + + + +
  128. | | name | Route name |
  129. + + + +
  130. | | parameters | Route parameters |
  131. + +----------------+-----------------------------------------------------------------------+
  132. | | hide_protocol | Hide http:// or https:// (default: false) |
  133. +-----------+----------------+-----------------------------------------------------------------------+
  134. If you have the SonataDoctrineORMAdminBundle installed, you have access to more field types, see `SonataDoctrineORMAdminBundle Documentation <https://sonata-project.org/bundles/doctrine-orm-admin/master/doc/reference/list_field_definition.html>`_.
  135. Customizing the query used to generate the list
  136. -----------------------------------------------
  137. You can customize the list query thanks to the ``createQuery`` method.
  138. .. code-block:: php
  139. <?php
  140. public function createQuery($context = 'list')
  141. {
  142. $query = parent::createQuery($context);
  143. $query->andWhere(
  144. $query->expr()->eq($query->getRootAliases()[0] . '.my_field', ':my_param')
  145. );
  146. $query->setParameter('my_param', 'my_value');
  147. return $query;
  148. }
  149. Customizing the sort order
  150. --------------------------
  151. Configure the default ordering in the list view
  152. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  153. Configuring the default ordering column can simply be achieved by overriding
  154. the ``datagridValues`` array property. All three keys ``_page``, ``_sort_order`` and
  155. ``_sort_by`` can be omitted.
  156. .. code-block:: php
  157. <?php
  158. // src/AppBundle/Admin/PostAdmin.php
  159. use Sonata\AdminBundle\Admin\Admin;
  160. class PostAdmin extends Admin
  161. {
  162. // ...
  163. protected $datagridValues = array(
  164. // display the first page (default = 1)
  165. '_page' => 1,
  166. // reverse order (default = 'ASC')
  167. '_sort_order' => 'DESC',
  168. // name of the ordered field (default = the model's id field, if any)
  169. '_sort_by' => 'updatedAt',
  170. );
  171. // ...
  172. }
  173. .. note::
  174. The '_sort_by' key can be of the form ``mySubModel.mySubSubModel.myField``.
  175. To do:
  176. - how to sort by multiple fields (this might be a separate recipe?)
  177. Filters
  178. -------
  179. You can add filters to let user control which data will be displayed.
  180. .. code-block:: php
  181. <?php
  182. // src/AppBundle/Admin/PostAdmin.php
  183. use Sonata\AdminBundle\Datagrid\DatagridMapper;
  184. class ClientAdmin extends Admin
  185. {
  186. protected function configureDatagridFilters(DatagridMapper $datagridMapper)
  187. {
  188. $datagridMapper
  189. ->add('phone')
  190. ->add('email')
  191. ;
  192. }
  193. // ...
  194. }
  195. All filters are hidden by default for space-saving. User has to check which filter he wants to use.
  196. To make the filter always visible (even when it is inactive), set the parameter
  197. ``show_filter`` to ``true``.
  198. .. code-block:: php
  199. <?php
  200. protected function configureDatagridFilters(DatagridMapper $datagridMapper)
  201. {
  202. $datagridMapper
  203. ->add('phone')
  204. ->add('email', null, array(
  205. 'show_filter' => true
  206. ))
  207. // ...
  208. ;
  209. }
  210. By default the template generates an ``operator`` for a filter which defaults to ``sonata_type_equal``.
  211. Though this ``operator_type`` is automatically detected it can be changed or even be hidden:
  212. .. code-block:: php
  213. protected function configureDatagridFilters(DatagridMapper $datagridMapper)
  214. {
  215. $datagridMapper
  216. ->add('foo', null, array(
  217. 'operator_type' => 'sonata_type_boolean'
  218. ))
  219. ->add('bar', null, array(
  220. 'operator_type' => 'hidden'
  221. ))
  222. // ...
  223. ;
  224. }
  225. If you don't need the advanced filters, or all your ``operator_type`` are hidden, you can disable them by setting
  226. ``advanced_filter`` to ``false``. You need to disable all advanced filters to make the button disappear.
  227. .. code-block:: php
  228. protected function configureDatagridFilters(DatagridMapper $datagridMapper)
  229. {
  230. $datagridMapper
  231. ->add('bar', null, array(
  232. 'operator_type' => 'hidden',
  233. 'advanced_filter' => false
  234. ))
  235. // ...
  236. ;
  237. }
  238. Default filters
  239. ^^^^^^^^^^^^^^^
  240. Default filters can be added to the datagrid values by overriding the ``$datagridValues`` property which is also used for default sorting.
  241. A filter has a ``value`` and an optional ``type``. If no ``type`` is given the default type ``is equal`` is used.
  242. .. code-block:: php
  243. protected $datagridValues = array(
  244. '_page' => 1,
  245. '_sort_order' => 'ASC',
  246. '_sort_by' => 'id',
  247. 'foo' => array(
  248. 'value' => 'bar'
  249. )
  250. );
  251. Available types are represented through classes which can be found here:
  252. https://github.com/sonata-project/SonataCoreBundle/tree/master/Form/Type
  253. Types like ``equal`` and ``boolean`` use constants to assign a choice of ``type`` to an ``integer`` for its ``value``:
  254. .. code-block:: php
  255. <?php
  256. // SonataCoreBundle/Form/Type/EqualType.php
  257. namespace Sonata\CoreBundle\Form\Type;
  258. class EqualType extends AbstractType
  259. {
  260. const TYPE_IS_EQUAL = 1;
  261. const TYPE_IS_NOT_EQUAL = 2;
  262. }
  263. The integers are then passed in the URL of the list action e.g.:
  264. **/admin/user/user/list?filter[enabled][type]=1&filter[enabled][value]=1**
  265. This is an example using these constants for an ``boolean`` type:
  266. .. code-block:: php
  267. use Sonata\UserBundle\Admin\Model\UserAdmin as SonataUserAdmin;
  268. use Sonata\CoreBundle\Form\Type\EqualType;
  269. use Sonata\CoreBundle\Form\Type\BooleanType;
  270. class UserAdmin extends SonataUserAdmin
  271. {
  272. protected $datagridValues = array(
  273. 'enabled' => array(
  274. 'type' => EqualType::TYPE_IS_EQUAL, // => 1
  275. 'value' => BooleanType::TYPE_YES // => 1
  276. )
  277. );
  278. }
  279. Please note that setting a ``false`` value on a the ``boolean`` type will not work since the type expects an integer of ``2`` as ``value`` as defined in the class constants:
  280. .. code-block:: php
  281. <?php
  282. // SonataCoreBundle/Form/Type/BooleanType.php
  283. namespace Sonata\CoreBundle\Form\Type;
  284. class BooleanType extends AbstractType
  285. {
  286. const TYPE_YES = 1;
  287. const TYPE_NO = 2;
  288. }
  289. Default filters can also be added to the datagrid values by overriding the ``getFilterParameters`` method.
  290. .. code-block:: php
  291. use Sonata\CoreBundle\Form\Type\EqualType;
  292. use Sonata\CoreBundle\Form\Type\BooleanType;
  293. class UserAdmin extends SonataUserAdmin
  294. {
  295. public function getFilterParameters()
  296. {
  297. $this->datagridValues = array_merge(array(
  298. 'enabled' => array (
  299. 'type' => EqualType::TYPE_IS_EQUAL,
  300. 'value' => BooleanType::TYPE_YES
  301. )
  302. ), $this->datagridValues);
  303. return parent::getFilterParameters();
  304. }
  305. }
  306. This approach is useful when you need to create dynamic filters.
  307. .. code-block:: php
  308. class PostAdmin extends SonataUserAdmin
  309. {
  310. public function getFilterParameters()
  311. {
  312. // Assuming security context injected
  313. if (!$this->securityContext->isGranted('ROLE_ADMIN')) {
  314. $user = $this->securityContext->getToken()->getUser();
  315. $this->datagridValues = array_merge(array(
  316. 'author' => array (
  317. 'type' => EqualType::TYPE_IS_EQUAL,
  318. 'value' => $user->getId()
  319. )
  320. ), $this->datagridValues);
  321. }
  322. return parent::getFilterParameters();
  323. }
  324. }
  325. Please note that this is not a secure approach to hide posts from others. It's just an example for setting filters on demand.
  326. Callback filter
  327. ^^^^^^^^^^^^^^^
  328. If you have the **SonataDoctrineORMAdminBundle** installed you can use the ``doctrine_orm_callback`` filter type e.g. for creating a full text filter:
  329. .. code-block:: php
  330. use Sonata\UserBundle\Admin\Model\UserAdmin as SonataUserAdmin;
  331. use Sonata\AdminBundle\Datagrid\DatagridMapper;
  332. class UserAdmin extends SonataUserAdmin
  333. {
  334. protected function configureDatagridFilters(DatagridMapper $datagridMapper)
  335. {
  336. $datagridMapper
  337. ->add('full_text', 'doctrine_orm_callback', array(
  338. 'callback' => array($this, 'getFullTextFilter'),
  339. 'field_type' => 'text'
  340. ))
  341. // ...
  342. ;
  343. }
  344. public function getFullTextFilter($queryBuilder, $alias, $field, $value)
  345. {
  346. if (!$value['value']) {
  347. return;
  348. }
  349. // Use `andWhere` instead of `where` to prevent overriding existing `where` conditions
  350. $queryBuilder->andWhere($queryBuilder->expr()->orX(
  351. $queryBuilder->expr()->like($alias.'.username', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
  352. $queryBuilder->expr()->like($alias.'.firstName', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
  353. $queryBuilder->expr()->like($alias.'.lastName', $queryBuilder->expr()->literal('%' . $value['value'] . '%'))
  354. ));
  355. return true;
  356. }
  357. }
  358. You can also get the filter type which can be helpful to change the operator type of your condition(s):
  359. .. code-block:: php
  360. use Sonata\CoreBundle\Form\Type\EqualType;
  361. class UserAdmin extends SonataUserAdmin
  362. {
  363. public function getFullTextFilter($queryBuilder, $alias, $field, $value)
  364. {
  365. if (!$value['value']) {
  366. return;
  367. }
  368. $operator = $value['type'] == EqualType::TYPE_IS_EQUAL ? '=' : '!=';
  369. $queryBuilder
  370. ->andWhere($alias.'.username '.$operator.' :username')
  371. ->setParameter('username', $value['value'])
  372. ;
  373. return true;
  374. }
  375. }
  376. To do:
  377. - basic filter configuration and options
  378. - targeting submodel fields using dot-separated notation
  379. - advanced filter options (global_search)
  380. Visual configuration
  381. --------------------
  382. You have the possibility to configure your List View to customize the render without overriding to whole template.
  383. You can :
  384. - `header_style`: Customize the style of header (width, color, background, align...)
  385. - `header_class`: Customize the class of the header
  386. - `row_align`: Customize the alignment of the rendered inner cells
  387. .. code-block:: php
  388. <?php
  389. public function configureListFields(ListMapper $list)
  390. {
  391. $list
  392. ->add('id', null, array(
  393. 'header_style' => 'width: 5%; text-align: center',
  394. 'row_align' => 'center'
  395. ))
  396. ->add('name', 'text', array(
  397. 'header_style' => 'width: 35%'
  398. )
  399. ->add('actions', null, array(
  400. 'header_class' => 'customActions',
  401. 'row_align' => 'right'
  402. )
  403. // ...
  404. ;
  405. }
  406. .. _`issues on GitHub`: https://github.com/sonata-project/SonataAdminBundle/issues/1519