action_list.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. .. code-block:: php
  33. <?php
  34. // Example taken from Sonata E-Commerce Product Admin
  35. public function configureListFields(ListMapper $list)
  36. {
  37. $list
  38. // addIdentifier allows to specify that this column will provide a link to the entity's edition
  39. ->addIdentifier('name')
  40. // You may specify the field type directly as the second argument instead of in the options
  41. ->add('isVariation', 'boolean')
  42. // The type can be guessed as well
  43. ->add('enabled', null, array('editable' => true))
  44. // We can add options to the field depending on the type
  45. ->add('price', 'currency', array('currency' => $this->currencyDetector->getCurrency()->getLabel()))
  46. // Here we specify which method is used to render the label
  47. ->add('productCategories', null, array('associated_tostring' => 'getCategory'))
  48. ->add('productCollections', null, array('associated_tostring' => 'getCollection'))
  49. // You may also use dotted-notation to access specific properties of a relation to the entity
  50. ->add('image.name')
  51. // You may also specify the actions you want to be displayed in the list
  52. ->add('_action', 'actions', array(
  53. 'actions' => array(
  54. 'show' => array(),
  55. 'edit' => array(),
  56. 'delete' => array(),
  57. )
  58. ))
  59. ;
  60. }
  61. Options
  62. ^^^^^^^
  63. .. note::
  64. * ``(m)`` stands for mandatory
  65. * ``(o)`` stands for optional
  66. - ``type`` (m): defines the field type - mandatory for the field description itself but will try to detect the type automatically if not specified
  67. - ``template`` (o): the template used to render the field
  68. - ``label`` (o): the name used for the column's title
  69. - ``link_parameters`` (o): add link parameter to the related Admin class when the ``Admin::generateUrl`` is called
  70. - ``code`` (o): the method name to retrieve the related value
  71. - ``associated_tostring`` (o): (deprecated, use associated_property option) the method to retrieve the "string" representation of the collection element.
  72. - ``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.
  73. - ``identifier`` (o): if set to true a link appears on the value to edit the element
  74. Available types and associated options
  75. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  76. .. note::
  77. ``(m)`` means that option is mandatory
  78. +-----------+----------------+-----------------------------------------------------------------------+
  79. | Type | Options | Description |
  80. +===========+================+=======================================================================+
  81. | actions | actions | List of available actions |
  82. +-----------+----------------+-----------------------------------------------------------------------+
  83. | batch | | Renders a checkbox |
  84. +-----------+----------------+-----------------------------------------------------------------------+
  85. | select | | Renders a select box |
  86. +-----------+----------------+-----------------------------------------------------------------------+
  87. | array | | Displays an array |
  88. +-----------+----------------+-----------------------------------------------------------------------+
  89. | boolean | ajax_hidden | Yes/No; ajax_hidden allows to hide list field during an AJAX context. |
  90. +-----------+----------------+-----------------------------------------------------------------------+
  91. | boolean | editable | Yes/No; editable allows to edit directly from the list if authorized. |
  92. +-----------+----------------+-----------------------------------------------------------------------+
  93. | choice | choices | Possible choices |
  94. + +----------------+-----------------------------------------------------------------------+
  95. | | multiple | Is it a multiple choice option? Defaults to false. |
  96. + +----------------+-----------------------------------------------------------------------+
  97. | | delimiter | Separator of values if multiple. |
  98. + +----------------+-----------------------------------------------------------------------+
  99. | | catalogue | Translation catalogue. |
  100. +-----------+----------------+-----------------------------------------------------------------------+
  101. | currency | currency (m) | A currency string (EUR or USD for instance). |
  102. +-----------+----------------+-----------------------------------------------------------------------+
  103. | date | format | A format understandable by Twig's ``date`` function. |
  104. +-----------+----------------+-----------------------------------------------------------------------+
  105. | datetime | format | A format understandable by Twig's ``date`` function. |
  106. +-----------+----------------+-----------------------------------------------------------------------+
  107. | percent | | Renders value as a percentage. |
  108. +-----------+----------------+-----------------------------------------------------------------------+
  109. | string | | Renders a simple string. |
  110. +-----------+----------------+-----------------------------------------------------------------------+
  111. | time | | Renders a datetime's time with format ``H:i:s``. |
  112. +-----------+----------------+-----------------------------------------------------------------------+
  113. | trans | catalogue | Translates the value with catalogue ``catalogue`` if defined. |
  114. +-----------+----------------+-----------------------------------------------------------------------+
  115. | url | url | Adds a link with url ``url`` to the displayed value |
  116. + +----------------+-----------------------------------------------------------------------+
  117. | | route | Give a route to generate the url |
  118. + + + +
  119. | | name | Route name |
  120. + + + +
  121. | | parameters | Route parameters |
  122. + +----------------+-----------------------------------------------------------------------+
  123. | | hide_protocol | Hide http:// or https:// (default false) |
  124. +-----------+----------------+-----------------------------------------------------------------------+
  125. 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>`_.
  126. Customizing the query used to generate the list
  127. -----------------------------------------------
  128. You can customize the list query thanks to the ``createQuery`` method.
  129. .. code-block:: php
  130. <?php
  131. public function createQuery($context = 'list')
  132. {
  133. $query = parent::createQuery($context);
  134. $query->andWhere(
  135. $query->expr()->eq($query->getRootAliases()[0] . '.my_field', ':my_param')
  136. );
  137. $query->setParameter('my_param', 'my_value');
  138. return $query;
  139. }
  140. Customizing the sort order
  141. --------------------------
  142. Configure the default ordering in the list view
  143. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  144. Configuring the default ordering column can simply be achieved by overriding
  145. the ``datagridValues`` array property. All three keys ``_page``, ``_sort_order`` and
  146. ``_sort_by`` can be omitted.
  147. .. code-block:: php
  148. <?php
  149. use Sonata\AdminBundle\Admin\Admin;
  150. class PageAdmin extends Admin
  151. {
  152. // ...
  153. /**
  154. * Default Datagrid values
  155. *
  156. * @var array
  157. */
  158. protected $datagridValues = array(
  159. '_page' => 1, // display the first page (default = 1)
  160. '_sort_order' => 'DESC', // reverse order (default = 'ASC')
  161. '_sort_by' => 'updated' // name of the ordered field
  162. // (default = the model's id field, if any)
  163. // the '_sort_by' key can be of the form 'mySubModel.mySubSubModel.myField'.
  164. );
  165. // ...
  166. }
  167. To do:
  168. - how to sort by multiple fields (this might be a separate recipe?)
  169. Filters
  170. -------
  171. You can add filters to let user control which data will be displayed.
  172. .. code-block:: php
  173. <?php
  174. // src/Acme/DemoBundle/Admin/PostAdmin.php
  175. use Sonata\AdminBundle\Datagrid\DatagridMapper;
  176. class ClientAdmin extends Admin
  177. {
  178. protected function configureDatagridFilters(DatagridMapper $datagridMapper)
  179. {
  180. $datagridMapper
  181. ->add('phone')
  182. ->add('email')
  183. ;
  184. }
  185. }
  186. All filters are hidden by default for space-saving. User has to check which filter he wants to use.
  187. To make the filter always visible (even when it is inactive), set the parameter
  188. ``show_filter`` to ``true``.
  189. .. code-block:: php
  190. <?php
  191. protected function configureDatagridFilters(DatagridMapper $datagridMapper)
  192. {
  193. $datagridMapper
  194. ->add('phone')
  195. ->add('email', null, array('show_filter'=>true))
  196. ;
  197. }
  198. By default the template generates an ``operator`` for a filter which defaults to ``sonata_type_equal``.
  199. Though this ``operator_type`` is automatically detected it can be changed or even be hidden:
  200. .. code-block:: php
  201. protected function configureDatagridFilters(DatagridMapper $datagridMapper)
  202. {
  203. $datagridMapper
  204. ->add('foo', null, array('operator_type' => 'sonata_type_boolean'))
  205. ->add('bar', null, array('operator_type' => 'hidden'))
  206. ;
  207. }
  208. If you don't need the advanced filters, or all your ``operator_type`` are hidden, you can disable them by setting
  209. ``advanced_filter`` to ``false``. You need to disable all advanced filters to make the button disappear.
  210. .. code-block:: php
  211. protected function configureDatagridFilters(DatagridMapper $datagridMapper)
  212. {
  213. $datagridMapper
  214. ->add('bar', null, array('operator_type' => 'hidden', 'advanced_filter' => false))
  215. ;
  216. }
  217. Default filters
  218. ^^^^^^^^^^^^^^^
  219. Default filters can be added to the datagrid values by overriding the ``$datagridValues`` property which is also used for default sorting.
  220. A filter has a ``value`` and an optional ``type``. If no ``type`` is given the default type ``is equal`` is used.
  221. .. code-block:: php
  222. protected $datagridValues = array(
  223. '_page' => 1,
  224. '_sort_order' => 'ASC',
  225. '_sort_by' => 'id',
  226. 'foo' => array('value' => 'bar')
  227. );
  228. Available types are represented through classes which can be found here:
  229. https://github.com/sonata-project/SonataCoreBundle/tree/master/Form/Type
  230. Types like ``equal`` and ``boolean`` use constants to assign a choice of ``type`` to an ``integer`` for its ``value``:
  231. .. code-block:: php
  232. class EqualType extends AbstractType
  233. {
  234. const TYPE_IS_EQUAL = 1;
  235. const TYPE_IS_NOT_EQUAL = 2;
  236. }
  237. The integers are then passed in the URL of the list action e.g.:
  238. **/admin/user/user/list?filter[enabled][type]=1&filter[enabled][value]=1**
  239. This is an example using these constants for an ``boolean`` type:
  240. .. code-block:: php
  241. use Sonata\UserBundle\Admin\Model\UserAdmin as SonataUserAdmin;
  242. use SonataCoreBundle/blob/master/Form/Type/EqualType.php;
  243. use SonataCoreBundle/blob/master/Form/Type/BooleanType;
  244. class UserAdmin extends SonataUserAdmin
  245. {
  246. protected $datagridValues = array(
  247. 'enabled' => array(
  248. 'type' => EqualType::TYPE_IS_EQUAL, // => 1
  249. 'value' => BooleanType::TYPE_YES // => 1
  250. )
  251. );
  252. }
  253. 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:
  254. .. code-block:: php
  255. class BooleanType extends AbstractType
  256. {
  257. const TYPE_YES = 1;
  258. const TYPE_NO = 2;
  259. }
  260. Default filters can also be added to the datagrid values by overriding the ``getFilterParameters`` method.
  261. .. code-block:: php
  262. use SonataCoreBundle/blob/master/Form/Type/EqualType.php;
  263. use SonataCoreBundle/blob/master/Form/Type/BooleanType;
  264. class UserAdmin extends SonataUserAdmin
  265. {
  266. public function getFilterParameters()
  267. {
  268. $this->datagridValues = array_merge(array(
  269. 'enabled' => array (
  270. 'type' => EqualType::TYPE_IS_EQUAL,
  271. 'value' => BooleanType::TYPE_YES
  272. )
  273. ), $this->datagridValues);
  274. return parent::getFilterParameters();
  275. }
  276. }
  277. This approach is useful when you need to create dynamic filters.
  278. .. code-block:: php
  279. class PostAdmin extends SonataUserAdmin
  280. {
  281. public function getFilterParameters()
  282. {
  283. // Assuming security context injected
  284. if (!$this->securityContext->isGranted('ROLE_ADMIN')) {
  285. $user = $this->securityContext->getToken()->getUser();
  286. $this->datagridValues = array_merge(array(
  287. 'author' => array (
  288. 'type' => EqualType::TYPE_IS_EQUAL,
  289. 'value' => $user->getId()
  290. )
  291. ), $this->datagridValues);
  292. }
  293. return parent::getFilterParameters();
  294. }
  295. }
  296. Please note that this is not a secure approach to hide posts from others. It's just an example for setting filters on demand.
  297. Callback filter
  298. ^^^^^^^^^^^^^^^
  299. If you have the **SonataDoctrineORMAdminBundle** installed you can use the ``doctrine_orm_callback`` filter type e.g. for creating a full text filter:
  300. .. code-block:: php
  301. use Sonata\UserBundle\Admin\Model\UserAdmin as SonataUserAdmin;
  302. use Sonata\AdminBundle\Datagrid\DatagridMapper;
  303. class UserAdmin extends SonataUserAdmin
  304. {
  305. protected function configureDatagridFilters(DatagridMapper $datagridMapper)
  306. {
  307. $datagridMapper
  308. ->add('full_text', 'doctrine_orm_callback', array(
  309. 'callback' => array($this, 'getFullTextFilter'),
  310. 'field_type' => 'text'
  311. ));
  312. }
  313. public function getFullTextFilter($queryBuilder, $alias, $field, $value)
  314. {
  315. if (!$value['value']) {
  316. return;
  317. }
  318. // Use `andWhere` instead of `where` to prevent overriding existing `where` conditions
  319. $queryBuilder->andWhere($queryBuilder->expr()->orX(
  320. $queryBuilder->expr()->like($alias.'.username', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
  321. $queryBuilder->expr()->like($alias.'.firstName', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
  322. $queryBuilder->expr()->like($alias.'.lastName', $queryBuilder->expr()->literal('%' . $value['value'] . '%'))
  323. ));
  324. return true;
  325. }
  326. }
  327. You can also get the filter type which can be helpful to change the operator type of your condition(s):
  328. .. code-block:: php
  329. use Sonata\CoreBundle\Form\Type\EqualType;
  330. class UserAdmin extends SonataUserAdmin
  331. {
  332. public function getFullTextFilter($queryBuilder, $alias, $field, $value)
  333. {
  334. if (!$value['value']) {
  335. return;
  336. }
  337. $operator = $value['type'] == EqualType::TYPE_IS_EQUAL ? '=' : '!=';
  338. $queryBuilder->andWhere($alias.'.username ' . $operator . ' :username')
  339. ->setParameter('username', $value['value']);
  340. return true;
  341. }
  342. }
  343. To do:
  344. - basic filter configuration and options
  345. - targeting submodel fields using dot-separated notation
  346. - advanced filter options (global_search)
  347. .. _`issues on GitHub`: https://github.com/sonata-project/SonataAdminBundle/issues/1519