batch_actions.rst 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. Batch actions
  2. =============
  3. Batch actions are actions triggered on a set of selected objects. By default,
  4. Admins have a ``delete`` action which allows you to remove several entries at once.
  5. Defining new actions
  6. --------------------
  7. To create a new custom batch action which appears in the list view follow these steps:
  8. Override ``getBatchActions()`` in your ``Admin`` class to define the new batch actions
  9. by adding them to the ``$actions`` array. Each entry has two settings:
  10. - **label**: The name to use when offering this option to users, should be passed through the translator
  11. - **ask_confirmation**: defaults to true and means that the user will be asked
  12. for confirmation before the batch action is processed
  13. For example, lets define a new ``merge`` action which takes a number of source items and
  14. merges them onto a single target item. It should only be available when two conditions are met:
  15. - the EDIT and DELETE routes exist for this Admin (have not been disabled)
  16. - the logged in administrator has EDIT and DELETE permissions
  17. .. code-block:: php
  18. <?php
  19. // In your Admin class
  20. public function getBatchActions()
  21. {
  22. // retrieve the default batch actions (currently only delete)
  23. $actions = parent::getBatchActions();
  24. if (
  25. $this->hasRoute('edit') && $this->isGranted('EDIT') &&
  26. $this->hasRoute('delete') && $this->isGranted('DELETE')
  27. ) {
  28. $actions['merge'] = array(
  29. 'label' => $this->trans('action_merge', array(), 'SonataAdminBundle'),
  30. 'ask_confirmation' => true
  31. );
  32. }
  33. return $actions;
  34. }
  35. Define the core action logic
  36. ----------------------------
  37. The method ``batchAction<MyAction>`` will be executed to process your batch in your ``CRUDController`` class. The selected
  38. objects are passed to this method through a query argument which can be used to retrieve them.
  39. If for some reason it makes sense to perform your batch action without the default selection
  40. method (for example you defined another way, at template level, to select model at a lower
  41. granularity), the passed query is ``null``.
  42. .. note::
  43. You can check how to declare your own ``CRUDController`` class in the Architecture section.
  44. .. code-block:: php
  45. <?php
  46. // In Acme/ProjectBundle/Controller/CRUDController.php
  47. public function batchActionMerge(ProxyQueryInterface $selectedModelQuery)
  48. {
  49. if (!$this->admin->isGranted('EDIT') || !$this->admin->isGranted('DELETE')) {
  50. throw new AccessDeniedException();
  51. }
  52. $request = $this->get('request');
  53. $modelManager = $this->admin->getModelManager();
  54. $target = $modelManager->find($this->admin->getClass(), $request->get('targetId'));
  55. if( $target === null){
  56. $this->addFlash('sonata_flash_info', 'flash_batch_merge_no_target');
  57. return new RedirectResponse(
  58. $this->admin->generateUrl('list', $this->admin->getFilterParameters())
  59. );
  60. }
  61. $selectedModels = $selectedModelQuery->execute();
  62. // do the merge work here
  63. try {
  64. foreach ($selectedModels as $selectedModel) {
  65. $modelManager->delete($selectedModel);
  66. }
  67. $modelManager->update($selectedModel);
  68. } catch (\Exception $e) {
  69. $this->addFlash('sonata_flash_error', 'flash_batch_merge_error');
  70. return new RedirectResponse(
  71. $this->admin->generateUrl('list', $this->admin->getFilterParameters())
  72. );
  73. }
  74. $this->addFlash('sonata_flash_success', 'flash_batch_merge_success');
  75. return new RedirectResponse(
  76. $this->admin->generateUrl('list', $this->admin->getFilterParameters())
  77. );
  78. }
  79. (Optional) Overriding the batch selection template
  80. --------------------------------------------------
  81. A merge action requires two kinds of selection: a set of source objects to merge from
  82. and a target object to merge into. By default, batch_actions only let you select one set
  83. of objects to manipulate. We can override this behavior by changing our list template
  84. (``list__batch.html.twig``) and adding a radio button to choose the target object.
  85. .. code-block:: html+jinja
  86. {# in Acme/ProjectBundle/Resources/views/CRUD/list__batch.html.twig #}
  87. {# See SonataAdminBundle:CRUD:list__batch.html.twig for the current default template #}
  88. {% extends admin.getTemplate('base_list_field') %}
  89. {% block field %}
  90. <input type="checkbox" name="idx[]" value="{{ admin.id(object) }}" />
  91. {# the new radio #}
  92. <input type="radio" name="targetId" value="{{ admin.id(object) }}" />
  93. {% endblock %}
  94. And add this:
  95. .. code-block:: php
  96. <?php
  97. // Acme/ProjectBundle/AcmeProjectBundle.php
  98. public function getParent()
  99. {
  100. return 'SonataAdminBundle';
  101. }
  102. See the `Symfony bundle overriding mechanism`_
  103. for further explanation of overriding bundle templates.
  104. (Optional) Overriding the default relevancy check function
  105. ----------------------------------------------------------
  106. By default, batch actions are not executed if no object was selected, and the user is notified of
  107. this lack of selection. If your custom batch action needs more complex logic to determine if
  108. an action can be performed or not, just define a ``batchAction<MyAction>IsRelevant`` method
  109. (e.g. ``batchActionMergeIsRelevant``) in your ``CRUDController`` class. This check is performed
  110. before the user is asked for confirmation, to make sure there is actually something to confirm.
  111. This method may return three different values:
  112. - ``true``: The batch action is relevant and can be applied.
  113. - ``false``: Same as above, with the default "action aborted, no model selected" notification message.
  114. - a string: The batch action is not relevant given the current request parameters
  115. (for example the ``target`` is missing for a ``merge`` action).
  116. The returned string is a message displayed to the user.
  117. .. code-block:: php
  118. <?php
  119. // In Acme/ProjectBundle/Controller/CRUDController.php
  120. public function batchActionMergeIsRelevant(array $selectedIds, $allEntitiesSelected)
  121. {
  122. // here you have access to all POST parameters, if you use some custom ones
  123. // POST parameters are kept even after the confirmation page.
  124. $parameterBag = $this->get('request')->request;
  125. // check that a target has been chosen
  126. if (!$parameterBag->has('targetId')) {
  127. return 'flash_batch_merge_no_target';
  128. }
  129. $targetId = $parameterBag->get('targetId');
  130. // if all entities are selected, a merge can be done
  131. if ($allEntitiesSelected) {
  132. return true;
  133. }
  134. // filter out the target from the selected models
  135. $selectedIds = array_filter($selectedIds,
  136. function($selectedId) use($targetId){
  137. return $selectedId !== $targetId;
  138. }
  139. );
  140. // if at least one but not the target model is selected, a merge can be done.
  141. return count($selectedIds) > 0;
  142. }
  143. (Optional) Executing a pre batch hook
  144. -------------------------------------
  145. In your admin class you can create a ``preBatchAction`` method to execute something before doing the batch action.
  146. The main purpose of this method is to alter the query or the list of selected ids.
  147. .. code-block:: php
  148. <?php
  149. // In your Admin class
  150. public function preBatchAction($actionName, ProxyQueryInterface $query, array & $idx, $allElements)
  151. {
  152. // altering the query or the idx array
  153. $foo = $query->getParameter('foo')->getValue();
  154. // Doing something with the foo object
  155. // ...
  156. $query->setParameter('foo', $bar);
  157. }
  158. .. _Symfony bundle overriding mechanism: http://symfony.com/doc/current/cookbook/bundles/inheritance.html