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

bbit/admin-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bbit/admin-bundle
    

    Register the bundle in AppKernel.php:

    new BBIT\AdminBundle\BBITAdminBundle(),
    new BBIT\DataGridBundle\BBITDataGridBundle(),
    new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(),
    new Knp\Bundle\MenuBundle\KnpMenuBundle(),
    new Symfony\Bundle\AsseticBundle\AsseticBundle()
    
  2. First Admin Class Create a basic ItemAdmin extending BaseAdmin in src/AppBundle/Admin/ItemAdmin.php:

    namespace AppBundle\Admin;
    
    use BBIT\AdminBundle\Admin\BaseAdmin;
    use BBIT\DataGridBundle\Service\DataGridService;
    use Symfony\Component\Form\FormBuilder;
    
    class ItemAdmin extends BaseAdmin
    {
        protected function mapListFields(DataGridService $grid) {
            $grid->addField('id', 'string');
            $grid->addField('name', 'string');
        }
    
        protected function mapFormFields(FormBuilder $formBuilder) {
            $formBuilder->add('name');
        }
    }
    
  3. Register Admin Service Define the admin service in app/config/services.yml:

    services:
        item_admin:
            class: AppBundle\Admin\ItemAdmin
            arguments: ['AppBundle\Entity\Item']
            tags:
                - { name: bbit.admin, label: 'Items', icon: 'fa fa-tag' }
    
  4. Access Admin Panel Visit /admin (or your configured route_prefix) to see the auto-generated CRUD interface for Item.


Implementation Patterns

Core Workflows

  1. CRUD Operations Extend BaseAdmin and override:

    • mapListFields() → Configure DataGrid columns.
    • mapFormFields() → Define form fields.
    • listQueryBuilder() → Customize list queries (e.g., joins, where clauses).
    • prePersist()/preUpdate() → Modify entities before save.

    Example: Filtering and sorting

    protected function listQueryBuilder() {
        $qb = parent::listQueryBuilder();
        $qb->andWhere('e.active = :active')->setParameter('active', true);
        return $qb;
    }
    
  2. Form Customization Use Symfony’s FormBuilder methods:

    protected function mapFormFields(FormBuilder $formBuilder) {
        $formBuilder
            ->add('name', TextType::class, ['label' => 'Item Name'])
            ->add('price', MoneyType::class)
            ->add('tags', EntityType::class, ['class' => 'AppBundle:Tag']);
    }
    
  3. DataGrid Enhancements Leverage DataGridService for advanced features:

    protected function mapListFields(DataGridService $grid) {
        $grid->addField('createdAt', 'datetime', [
            'label' => 'Created',
            'format' => 'Y-m-d H:i',
        ]);
        $grid->addAction('edit', 'Edit', 'fa fa-edit');
        $grid->addAction('delete', 'Delete', 'fa fa-trash', ['confirm' => true]);
    }
    
  4. Bulk Actions Add bulk operations via mapBulkActions():

    protected function mapBulkActions() {
        return [
            'delete' => [
                'label' => 'Delete Selected',
                'icon' => 'fa fa-trash',
                'route' => 'admin_item_bulk_delete',
                'method' => 'POST',
            ],
        ];
    }
    
  5. Integration with Other Bundles

    • KnpMenu: Auto-generates admin menu items via the bbit.admin tag.
    • Assetic: Bundle includes Twig templates with embedded assets (CSS/JS). Override templates in templates/BBITAdminBundle/ to customize.
    • Doctrine: Works seamlessly with Doctrine ORM. For non-Doctrine entities, implement getEntityManager() in your admin class.

Advanced Patterns

  1. Dynamic Admin Classes Use dependency injection to load admin classes dynamically:

    # services.yml
    app.admin.item:
        class: AppBundle\Admin\DynamicItemAdmin
        arguments: ['%app.dynamic_entity_class%']
        tags: [{ name: bbit.admin, label: 'Dynamic Items' }]
    
  2. Role-Based Access Control (RBAC) Override isGranted() to restrict actions:

    public function isGranted($attribute, $object = null) {
        if ($attribute === 'edit' && !$this->getUser()->hasRole('ROLE_ADMIN')) {
            return false;
        }
        return parent::isGranted($attribute, $object);
    }
    
  3. Custom Routes Define custom routes in routing.yml:

    admin_item_export:
        path: /items/export
        defaults: { _controller: 'AppBundle:Admin/ItemAdmin::exportAction' }
    

    Then implement exportAction() in your admin class.

  4. Event Listeners Attach listeners to admin events (e.g., prePersist, postDelete):

    $dispatcher->addListener('bbit.admin.pre_persist', function ($event) {
        $entity = $event->getEntity();
        $entity->setUpdatedBy($event->getUser());
    });
    

Gotchas and Tips

Common Pitfalls

  1. Entity Manager Injection

    • Issue: Forgetting to inject EntityManager can cause listQueryBuilder() to fail.
    • Fix: Extend BaseAdmin and call parent::listQueryBuilder() to ensure proper EM injection.
    • Tip: Use $this->getEntityManager() in custom queries.
  2. Routing Conflicts

    • Issue: Custom routes may clash with auto-generated ones.
    • Fix: Prefix custom routes explicitly (e.g., _admin_item_custom).
  3. DataGrid Caching

    • Issue: Large datasets may slow down the admin panel.
    • Fix: Configure KnpPaginator’s cache in config.yml:
      knp_paginator:
          page_range: 5
          default_options:
              page_name: page
              sort_field_name: sort
              sort_direction_name: direction
              distinct: true
      
  4. Form Type Overrides

    • Issue: Custom form types may not render correctly.
    • Fix: Ensure your form types extend Symfony’s base types and are properly registered as services.
  5. Asset Loading

    • Issue: Custom CSS/JS not loading.
    • Fix: Override the base template (BBITAdminBundle:Admin:layout.html.twig) and add assets via {% block stylesheets %} or {% block javascripts %}.

Debugging Tips

  1. Enable Debug Mode Set APP_DEBUG=true in .env to see detailed errors and template inheritance.

  2. Log Admin Events Enable monolog for bbit.admin events:

    # config.yml
    monolog:
        handlers:
            admin:
                type: stream
                path: "%kernel.logs_dir%/admin.log"
                level: debug
                channels: ["bbit.admin"]
    
  3. Check DataGrid Queries Use Doctrine’s query logging to debug slow queries:

    // config.yml
    doctrine:
        dbal:
            logging: true
            profiling: true
    
  4. Template Debugging Use Twig’s dump() or var_export() to inspect variables:

    {{ dump(grid) }}
    

Extension Points

  1. Custom Templates Override any template in templates/BBITAdminBundle/Admin/ (e.g., list.html.twig, form.html.twig).

  2. Admin Events Listen to built-in events:

    • bbit.admin.pre_list (modify list query)
    • bbit.admin.post_persist (post-save logic)
    • bbit.admin.pre_delete (pre-delete validation)

    Example listener:

    $dispatcher->addListener('bbit.admin.pre_delete', function ($event) {
        if (!$event->getUser()->hasRole('ROLE_SUPER_ADMIN')) {
            throw new \RuntimeException('Unauthorized');
        }
    });
    
  3. Dynamic Field Mapping Use closures for dynamic field mapping:

    protected function mapListFields(DataGridService $grid) {
        $grid->addField('price', 'currency', function ($field) {
            $field->setCurrency('USD');
        });
    }
    
  4. API Integration Extend the bundle to support API responses by overriding getResponse() in your admin class.


Configuration Quirks

  1. route_prefix
    • Defaults to /admin. Change it in config.yml:
      bbit_admin:
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware