Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Admin Bundle Laravel Package

sonata-project/admin-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require sonata-project/admin-bundle

Add to config/bundles.php:

return [
    // ...
    SonataAdminBundle::class => ['all' => true],
];
  1. Basic Admin Class: Create a service for your entity admin (e.g., src/Admin/ProductAdmin.php):

    use Sonata\AdminBundle\Admin\AbstractAdmin;
    use Sonata\AdminBundle\Datagrid\ListMapper;
    use Sonata\AdminBundle\Datagrid\DatagridMapper;
    use Sonata\AdminBundle\Form\FormMapper;
    
    class ProductAdmin extends AbstractAdmin
    {
        protected $datagridValues = [
            '_page' => 1,
            '_per_page' => 10,
        ];
    
        protected function configureDatagridFilters(DatagridMapper $datagridMapper)
        {
            $datagridMapper->add('name');
        }
    
        protected function configureListFields(ListMapper $listMapper)
        {
            $listMapper
                ->add('id')
                ->add('name')
                ->add('price');
        }
    
        protected function configureFormFields(FormMapper $formMapper)
        {
            $formMapper
                ->with('General')
                    ->add('name')
                    ->add('price')
                ->end();
        }
    }
    
  2. Register Admin: Add to config/services.yaml:

    services:
        App\Admin\ProductAdmin:
            tags: ['sonata.admin']
            arguments: ['App\Entity\Product', App\Admin\ProductController::class, 'main', '@doctrine.orm.entity_manager', null, null]
    
  3. Access Admin: Visit /admin/app_product (route auto-generated from App\Entity\Product).


First Use Case: CRUD for an Entity

  1. Generate Admin Skeleton: Use the sonata:admin command:

    php bin/console make:sonata-admin Product
    

    This creates a basic admin class with pre-configured fields.

  2. Customize Fields: Override configureFormFields() and configureListFields() to tailor the UI to your needs.

  3. Enable Permissions: Configure security in config/packages/security.yaml:

    access_control:
        - { path: ^/admin/, roles: ROLE_ADMIN }
    

Key First Steps Summary

  • Install bundle and dependencies.
  • Create an AbstractAdmin subclass for your entity.
  • Configure fields for list, form, and filters.
  • Register the admin as a service.
  • Secure the admin routes.

Implementation Patterns

Common Workflows

1. Field Configuration

  • List Fields: Use ListMapper to define columns in the list view.

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('id', 'id', ['label' => 'ID'])
            ->add('name', null, ['label' => 'Product Name'])
            ->add('price', 'currency', ['label' => 'Price', 'currency' => 'USD']);
    }
    
    • Use built-in types (id, text, currency, date, etc.) or custom templates.
  • Form Fields: Use FormMapper to define editable fields.

    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->with('Details')
                ->add('name', 'text', ['label' => 'Product Name'])
                ->add('price', 'money', ['label' => 'Price', 'currency' => 'USD'])
            ->end();
    }
    
    • Group fields with with()/end() for tabbed interfaces.
  • Filtering: Use DatagridMapper to add filters.

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('name')
            ->add('price', null, ['label' => 'Price', 'type' => 'range']);
    }
    

2. Batch Actions

Enable batch actions in the admin class:

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        ->add('name')
        ->add('_action', 'actions', [
            'actions' => [
                'edit' => [],
                'delete' => [],
            ],
        ]);
}

protected function configureSideMenu(SideMenuMapper $sideMenuMapper, $action = 'list')
{
    $sideMenuMapper
        ->addChild('Batch Actions', 'batch')
        ->addChild('Export', 'export', ['icon' => 'fa fa-download']);
}

protected function configureBatchActions(BatchMapper $batchMapper)
{
    $batchMapper
        ->add('delete', null, ['label' => 'Delete']);
}

3. Custom Templates

Override default templates by creating a templates directory in your admin bundle:

src/
  Resources/
    views/
      Admin/
        Product/
          list.html.twig       # Override list view
          edit.html.twig       # Override edit form

4. Relationships

Handle relationships with sonata_type_model:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('categories', 'sonata_type_model', [
            'btn_add' => 'Add',
            'btn_delete' => 'Remove',
            'btn_edit' => 'Edit',
            'link_parameters' => ['context' => 'list'],
        ], [
            'edit' => 'inline',
            'inline' => 'table',
        ]);
}

5. Permissions

Use ACL or voter-based permissions:

protected function configurePermissions()
{
    return [
        'edit' => 'ROLE_ADMIN',
        'delete' => 'ROLE_SUPER_ADMIN',
        'list' => 'IS_AUTHENTICATED_REMEMBERED',
    ];
}

6. Custom Controllers

Extend functionality by overriding controller methods:

public function prePersist($object)
{
    $object->setCreatedAt(new \DateTime());
}

public function preUpdate($object)
{
    $object->setUpdatedAt(new \DateTime());
}

Integration Tips

1. Doctrine Integration

  • Use sonata_type_model for entity relationships.
  • Leverage Doctrine filters for soft-deleted entities:
    $filterRepository = $this->getModelManager()->getFilterPool();
    $filterRepository->addFilter('softdeleteable', \App\Filter\SoftDeleteFilter::class);
    

2. Symfony Forms

Extend Sonata's form types:

use Sonata\AdminBundle\Form\Type\CollectionType;

$formMapper->add('tags', CollectionType::class, [
    'by_reference' => false,
], [
    'edit' => 'inline',
    'inline' => 'table',
]);

3. Translation

Use translation keys for labels:

$listMapper->add('name', null, ['label' => 'admin.product.name']);

Define translations in translations/messages.en.yaml:

admin:
    product:
        name: 'Product Name'

4. Assets

Customize CSS/JS:

public function getTemplateDirs()
{
    return [__DIR__.'/../Resources/views'];
}

public function getBundle()
{
    return new \App\AdminBundle\AdminBundle();
}

5. Event Listeners

Listen to admin events:

use Sonata\AdminBundle\Event\ConfigureDatagridEvent;

$eventDispatcher->addListener(ConfigureDatagridEvent::class, function (ConfigureDatagridEvent $event) {
    $event->getDatagridMapper()->add('custom_field');
});

Gotchas and Tips

Pitfalls

1. Deprecated Methods

  • Avoid setup_sticky_elements() and setup_readmore_elements() (deprecated in v4.37+).
  • Replace jQuery dependencies with Stimulus controllers (e.g., readmore-js → Stimulus).

2. Routing Conflicts

  • Ensure sonata_admin.php routing config is used (importing sonata_admin.xml is deprecated).
  • Custom routes may conflict with Sonata's auto-generated ones. Use _sonata_admin prefix for clarity.

3. Permission Issues

  • ACL (symfony/security-acl) is optional but required for advanced permissions. Explicitly add it:
    composer require symfony/security-acl
    
  • Always define permissions in configurePermissions() to avoid access errors.

4. Template Overrides

  • Template paths must match Sonata's structure. For example, to override ProductAdmin:
    src/
      Resources/
        views/
          Admin/
            Product/
              list.html.twig
    
  • Use getTemplate() in the admin class to specify custom paths:
    public function getTemplate($name)
    {
        return 'AppAdminBundle:Product:'.$name.'.html.twig';
    }
    

5.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
capell-app/block-library
capell-app/frontend
capell-app/admin
capell-app/core
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/privacy-filter-classifier
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php