Search code examples
symfonymodal-dialogsonata-admin

Modal window for edit model in Sonata Admin


How can I set-up the an Admin class in SonataAdminBundle, to display the form for adding/editing an entity in a modal window? Like below:

enter image description here


Solution

  • Manually you can do it yourself.

    1. Add in your config service

      calls:
      - [ setTemplate, [list, AcmeYourBundle:Your:base_list.html.twig]]
      - [ setTemplate, [edit, AcmeYourBundle:Your:base_edit.html.twig]]
      
    2. In your admin bundle add custom templete in configureListFields

      protected function configureListFields(ListMapper $listMapper) {
        $listMapper
          ->add('_action', 'actions', array(
            'actions' => array(
              'edit' => array('template' => 'AcmeYourBundle:Your:_action_edit.html.twig'),
            )
          ));
      }
      
    3. _action_edit.html.twig

      {% if admin.hasRoute('edit') and admin.id(object) and admin.isGranted('EDIT', object)%}
        <a class="edit sonata-action-element" href="{{ admin.generateObjectUrl('edit', object) }}">
          <i class="fa fa-edit"></i>
          {{ 'link_action_edit'|trans({}, 'SonataAdminBundle') }}
        </a>
      {% endif %}
      
    4. Add javascript code in base_list.html.twig

      <script type="text/javascript">
        $(document).ready(function() {
          $('a.edit').click(function() {   //bind handlers
              var url = $(this).attr('href');
              showDialog(url);
              return false;
          });
      
          $("#targetDiv").dialog({
            autoOpen: false,
            height: 700,
            width: 950,
            modal: true
          });
      
          function showDialog(url) {  
            $("#targetDiv").load(url);
            $("#targetDiv").dialog("open");
          }
        });
      
      </script>
      
    5. Done ! Enjoy it.