We use the SonataAdminBundle with our Symfony2 application. When editing an entity I want to add an own action to the dropdown menu which is located in the top right corner, but I have no idea how this works.
I know I can add own routes via configureRoutes(RouteCollection $collection)
and how to add batch actions or add own actions behind entities in the list view, but how can I add an own link in the actions dropdown in the edit view?
It is basically just a link like "Show me this entity in the frontend", so no big logic is needed.
One way would be to override the template that is used when editing. Now, what you need to do is:
Create new directory (if you already haven't) in
app/Resources
calledSonataAdminBundle
. Inside, create another one calledviews
. This would create a path likeapp/Resources/SonataAdminBundle/views
. This is Symfony basic template overriding. You can read more on that subject here.Now, you should copy the original template following the same path as it is, inside the original bundle. The template file we are interested here is located in
sonata-project/admin-bundle/Resources/views/CRUD/base_edit.html.twig
. This means that you have to create another folder insideviews
(the one we just created inapp
, calledCRUD
. So, now we have to following pathapp/Resources/SonataAdminBundle/views/CRUD
. Paste the template (base_edit.html.twig
) inside and we can start editing.Keep in mind that the following template is used in every edit action you have. So it's up to you whether you want to display that link in every edit_action or not. I will show you 1 way to limit that for specific action.
The block you gonna edit is
{% block actions %}
which is responsible for rendering the dropdown. This is how it should look now:Now all that's left to do is insert your link after last
<li>
tag.admin.id(object)
will return the current ID of the item you edit.app.request.get('_route')
will return the route of your edit action. You can remove that if you want your link to be displayed in all edit actions. Change<a href="/generate/path/with/your/route">View in Frontend</a>
with your route name usingadmin.id(object)
and you should be good to go.