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

Easyadmin Bundle Laravel Package

easycorp/easyadmin-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require easycorp/easyadmin-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        EasyCorp\Bundle\EasyAdminBundle\EasyAdminBundle::class => ['all' => true],
    ];
    
  2. First Admin Class: Create a CRUD controller for an entity (e.g., Post):

    php bin/console make:easyadmin:crud --entity=App\Entity\Post
    

    This generates a PostCrudController in src/Controller/Admin/.

  3. Route & Access: Define a route in config/routes.yaml:

    easy_admin:
        resource: '@EasyAdminBundle/Controller/AdminController.php'
        type: 'annotation'
        prefix: '/admin'
    

    Secure with Symfony’s security system (e.g., ROLE_ADMIN).

  4. First Use Case: Visit /admin to see the auto-generated dashboard. Click on Post to manage records via a pre-built UI (list, create, edit, delete).


Where to Look First

  • Official Documentation: Start with the "Getting Started" section.
  • Generated Code: Inspect src/Controller/Admin/PostCrudController.php to understand the CRUD structure.
  • Templates: Override defaults in templates/admin/ (see customization docs).
  • Configuration: Check config/packages/easy_admin.yaml for global settings (e.g., site name, theme).

Implementation Patterns

Core Workflows

1. CRUD Generation

  • Auto-Generated CRUD: Use the CLI command to scaffold controllers for entities:

    php bin/console make:easyadmin:crud --entity=App\Entity\User --fields="name,email,roles"
    
    • Fields are auto-detected via Doctrine annotations/attributes.
    • Customize with --per-page=20 or --format=list (override defaults).
  • Manual CRUD: Extend AbstractCrudController and define configureFields():

    public function configureFields(string $pageName): iterable {
        return [
            'id' => 'id',
            'title' => 'text',
            'content' => 'richtext',
            'publishedAt' => 'datetime',
        ];
    }
    

2. Field Customization

  • Field Types: Use built-in types (text, boolean, association, collection, etc.) or create custom ones.
    'author' => 'association',
    'tags' => 'collection' => ['entry_type' => TagCrudController::class],
    
  • Validation: Add validation rules via configureValidationGroups().
  • Templates: Override field rendering in templates/admin/crud/fields/.

3. Dashboard & Navigation

  • Custom Dashboard: Extend AbstractDashboardController and override configureMenuItems():
    public function configureMenuItems(iterable $menuItems): iterable {
        yield MenuItem::linkToCrud('Posts', 'fas fa-newspaper', PostCrudController::class);
        yield MenuItem::linkToDashboard('Dashboard', 'fas fa-tachometer-alt');
    }
    
  • Grouping: Use MenuItem::section() to organize items.

4. Integration with Symfony

  • Forms: Extend existing forms or create custom form types for fields.
  • Events: Listen to EasyAdmin events (e.g., Crud::ENTITY_CREATED) via Symfony’s event dispatcher.
    // src/EventListener/CrudListener.php
    public function onEntityCreated(CrudEvent $event) {
        $entity = $event->getEntityInstance();
        // Custom logic (e.g., send welcome email)
    }
    
    Register in services.yaml:
    services:
        App\EventListener\CrudListener:
            tags:
                - { name: kernel.event_listener, event: easyadmin.crud.entity.created, method: onEntityCreated }
    

5. API & Export

  • CSV/Excel Export: Enable via configureActions():
    public function configureActions(Actions $actions): Actions {
        return $actions
            ->add(CsvAction::new())
            ->add(ExcelAction::new());
    }
    
  • API Endpoints: Use JsonAction for REST-like exports or integrate with Symfony’s Serializer.

6. Theming & Assets

  • Override Templates: Copy templates/admin/ from the bundle to your project.
  • Custom CSS/JS: Add to assets/admin/ and include via configurePageTitle() or configureAssets().
    public function configureAssets(): Assets {
        return Assets::new()
            ->addCssFile('admin/css/custom.css')
            ->addJsFile('admin/js/custom.js');
    }
    

Advanced Patterns

1. Dynamic CRUD

  • Entity Auto-Discovery: Use EasyAdminBundle\Context\AdminContext to dynamically load CRUD controllers based on user roles or runtime conditions.
  • Example: Route to a controller that checks permissions and returns the appropriate CRUD class.

2. Multi-Tenancy

  • Filter by Tenant: Use configureQueryBuilder() to scope queries:
    public function configureQueryBuilder(QueryBuilder $qb): QueryBuilder {
        return $qb
            ->andWhere('e.tenantId = :tenantId')
            ->setParameter('tenantId', $this->getTenantId());
    }
    
  • Tenant-Aware Fields: Add tenant-specific fields to forms.

3. Bulk Actions

  • Custom Bulk Actions:
    public function configureActions(Actions $actions): Actions {
        $actions->add(CustomBulkAction::new()
            ->setLabel('Publish')
            ->setIcon('fas fa-bullhorn')
            ->setCssClass('btn btn-success')
        );
    }
    
  • Handle Bulk Logic:
    public function handleBulkAction(BulkActionEvent $event): void {
        $entities = $event->getEntities();
        foreach ($entities as $entity) {
            $entity->setPublished(true);
            $this->entityManager->flush();
        }
    }
    

4. Soft Deletes

  • Toggle Soft Delete:
    public function configureFields(string $pageName): iterable {
        return [
            'isDeleted' => 'boolean',
            // ...
        ];
    }
    
  • Query Filtering:
    public function configureQueryBuilder(QueryBuilder $qb): QueryBuilder {
        return $qb->andWhere('e.isDeleted = false');
    }
    

Gotchas and Tips

Pitfalls

  1. Caching Issues:

    • Problem: Changes to CRUD controllers or templates may not reflect immediately due to Symfony’s cache.
    • Fix: Clear the cache:
      php bin/console cache:clear
      
    • Tip: Use debug:config easy_admin to verify configuration.
  2. Field Ordering:

    • Problem: Fields may not appear in the expected order in forms or lists.
    • Fix: Explicitly define the order in configureFields():
      return [
          'title' => 'text',
          'content' => 'richtext',
          // ...
      ];
      
  3. Association Loading:

    • Problem: Lazy-loaded associations (e.g., OneToMany) can cause N+1 queries.
    • Fix: Use ->addSelect() in configureQueryBuilder() or enable DQL JOIN:
      public function configureQueryBuilder(QueryBuilder $qb): QueryBuilder {
          return $qb->addSelect('p.author');
      }
      
  4. Permission Denied:

    • Problem: Users see a "403 Forbidden" error even with ROLE_ADMIN.
    • Fix: Ensure:
      • The route is secured in security.yaml:
        access_control:
            - { path: ^/admin, roles: ROLE_ADMIN }
        
      • The user has the role in the database (e.g., User entity).
  5. Translation Issues:

    • Problem: Field labels or buttons appear in English despite translations.
    • Fix:
      • Ensure translations are loaded in config/packages/easy_admin.yaml:
        easy_admin:
            design:
                assets:
                    js:
                        - 'bundles/easyadmin/js/easyadmin.js'
                    css:
                        - 'bundles/easyadmin/css/easyadmin.css'
        
      • Add translations to translations/messages.en.yaml or your locale.
  6. Rich Text Fields:

    • Problem: richtext fields don’t render or save properly
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager