batch_actions.rst 7.6 KB

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