问题
I'm trying to override the SonataUser/Admin/Model/UserAdmin
's configureFormFields()
because I need to remove some default fields from the admin form.
So I have copied the file vendor/bundles/Sonata/UserBundle/Admin/Model/UserAdmin.php
in my bundle app/Application/Sonata/UserBundle/Admin/Model/UserAdmin.php
and modified it. Then declared it as a service:
# app/application/Sonata/UserBundle/Resources/config/services.yml
services:
application_user.registration.form.type:
class: Application\Sonata\UserBundle\Admin\Model\UserAdmin
arguments: [%sonata_user.model.user.class%]
tags:
- { name: form.type, alias: application_user_admin }
Now questions: Am I doing right ? How can I tell sonata admin to use it ?
回答1:
The overriding class should be set in config.yml:
# app/config/config.yml
sonata_user:
admin:
user:
class: MyCompany\UserBundle\Admin\Model\UserAdmin
Extend original UserAdmin:
namespace MyCompany\UserBundle\Admin\Model;
use Sonata\AdminBundle\Form\FormMapper;
class UserAdmin extends \Sonata\UserBundle\Admin\Model\UserAdmin
{
protected function configureFormFields(FormMapper $formMapper)
{
// new logic
}
}
Of course change class name MyCompany\UserBundle\Admin\Model\UserAdmin
to reflect your bundle structure.
回答2:
It is a better practice to keep your bundles in the src directory instead: (See Creating a bundle section).
In this case, if you are using easy extends, make sure to use --dest=src
in order to generate the bundle inside an Application namespace in src/.
php app/console sonata:easy-extends:generate SonataUserBundle --dest=src
By creating your overriding bundle in src/Application/Sonata/UserBundle
and registering the vendor bundle as a parent, you won't have to create a new service. This explains you how to override the bundle properly: overriding a bundle and should save you a lot of time.
Don't forget to create the file you want to override in the same location as your parent bundle.
In your case, you would have to copy paste SonataUser/Admin/Model/UserAdmin.php
from the vendor into your bundle src/Application/Sonata/UserBundle/Admin/Model/UserAdmin.php
and modify it as you wish.
That's why overriding bundles can be so useful.
来源:https://stackoverflow.com/questions/11413240/overriding-the-user-admin-form