问题
I am using SonataAdminBundle
and I'd like to know how to add a custom form action in the edit
(Something similar to the Save, Update and Close
)
There doesn't seem to anything documented about it.
I'm trying to add a custom input field that will call a controller or something to update a value and send an email
Is there any docs or examples on how to do this?
Thanks
回答1:
You can add custom form actions by adding new routes. Because when you add new route you need also add action to handle this route.
Create Route
You can register new routes by defining them in your Admin class. Only Admin routes should be registered this way.
The routes you define in this way are generated within your Admin’s context, and the only required parameter to add() is the action name. The second parameter can be used to define the URL format to append to baseRoutePattern, if not set explicitly this defaults to the action name.
<?php
use Sonata\AdminBundle\Route\RouteCollection;
class MediaAdmin extends Admin
{
protected function configureRoutes(RouteCollection $collection)
{
$collection->add('myCustomAction');
$collection->add('view', $this->getRouterIdParameter().'/view');
}
}
Other steps needed to create your new action
In addition to defining the route for your new action you also need to create a handler for it in your Controller. By default Admin classes use SonataAdminBundle:CRUD as their controller, but this can be changed by altering the third argument when defining your Admin service (in your admin.yml file).
For example, lets change the Controller for our MediaAdmin class to AcmeDemoBundle:MediaCRUD:
# src/Acme/DemoBundle/Resources/config/admin.yml
sonata.admin.media:
class: Acme\DemoBundle\Admin\MediaAdmin
tags:
- { name: sonata.admin, manager_type: orm, label: "Media" }
arguments:
- ~
- Acme\DemoBundle\Entity\Page
- 'AcmeDemoBundle:MediaCRUD' # define the new controller via the third argument
calls:
- [ setTranslationDomain, [Acme\DemoBundle]]
We now need to create our Controller, the easiest way is to extend the basic Sonata CRUD controller:
use Sonata\AdminBundle\Controller\CRUDController;
class MediaCRUDController extends CRUDController
{
public function myCustomAction()
{
// your code here ...
}
}
Inside a CRUD template, a route for the current Admin class can be generated via the admin variable’s generateUrl() command:
<a href="{{ admin.generateUrl('list') }}">List</a>
<a href="{{ admin.generateUrl('list', params|merge('page': 1)) }}">List</a>
Just override the template you need and add this custom action.
来源:https://stackoverflow.com/questions/20271883/sonataadmin-custom-form-action