Search code examples
symfonyoverridingsonata-admin

Sonata admin : specific batch_confirmation template per batch action


Today at work, I have to create a custom batch action in a Sonata project.

It's ok for that, the problem is :

I want set a specific batch_confirmation template for my new batch action, and I need it have no impact on other.

If no solution exists, I will override the default batch_confirmation template, change it in my sonata config, and make many 'if' statements to keep the basic confirmation for my other admin classes, but I think it's not the cleaner alternative.

Somebody have already has this kind of issues ?


Solution

  • When you add a custom batch action you'll need a custom action in your controller which exends the normal CRUD controller, see: https://sonata-project.org/bundles/admin/master/doc/reference/batch_actions.html.

    Instead of returning a redirect response, like you see in the documentation: you can return any template, e.g.:

    return $this->render(
         'YourBundle:Batch:confirmation.html.twig',
          $templateParams
    );
    

    In this confirmation template you can add your custom html. When you want to confirm the batch method, you'll need a form that posts back to your custom action with the data you'll need.

    From the batch_confirmation.html.twig copy the form to your own confirmation template. In the original batch_confirmation template, a hidden field is set to check if the user confirms: <input type="hidden" name="confirmation" value="ok">

    Check in your custom action if the user did confirm (check the request object). Then do the batch action. (You also can return a second step template, to build a wizard).

    Finally throw in some flash message

    $this->addFlash('sonata_flash_success', 'everything is ok!'); 
    

    and return to the list url:

    return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));