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

Doctrine Mongodb Admin Bundle Laravel Package

danidelalin/doctrine-mongodb-admin-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require danidelalin/doctrine-mongodb-admin-bundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        Danidelalin\DoctrineMongoDBAdminBundle\DanidelalinDoctrineMongoDBAdminBundle::class => ['all' => true],
    ];
    
  2. Configure Doctrine MongoDB ODM Ensure your config/packages/doctrine_mongodb.yaml is properly set up:

    doctrine_mongodb:
        connections:
            default:
                server: '%env(MONGODB_URL)%'
                options: {}
        document_managers:
            default:
                auto_mapping: true
                mappings:
                    App:
                        is_bundle: false
                        type: attribute
                        dir: '%kernel.project_dir%/src/Document'
                        prefix: 'App\Document'
                        alias: App
    
  3. Create a Basic Admin Class Extend Sonata\AdminBundle\Admin\AbstractAdmin and annotate your document:

    use Danidelalin\DoctrineMongoDBAdminBundle\Admin\AbstractMongoDBAdmin;
    use App\Document\User;
    
    class UserAdmin extends AbstractMongoDBAdmin
    {
        protected $documentClass = User::class;
        protected $translationDomain = 'App';
    
        protected function configureListFields(ListMapper $listMapper)
        {
            $listMapper
                ->add('username')
                ->add('email');
        }
    }
    
  4. Register the Admin Add the admin to config/packages/sonata_admin.yaml:

    sonata_admin:
        options:
            document_class: App\Document\User
        managers:
            app:
                list: [App\Admin\UserAdmin]
    
  5. Route the Admin Ensure routing is enabled in config/routes.yaml:

    sonata_admin:
        resource: '@SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
        prefix: /admin
    
  6. First Use Case Clear cache and visit /admin/app/user to see your MongoDB-backed CRUD interface.


Implementation Patterns

Common Workflows

  1. Customizing List Views Override configureListFields to tailor the admin panel:

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('id')
            ->add('createdAt', null, [
                'template' => 'SonataAdminBundle:CRUD:base_date_field.html.twig',
            ]);
    }
    
  2. Form Customization Use configureFormFields to modify the edit/create forms:

    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->tab('General')
                ->with('Basic Info')
                    ->add('username', 'text')
                    ->add('email', 'email')
                ->end()
            ->end();
    }
    
  3. Filtering and Sorting Extend configureDatagridFilters and configureDatagridValues:

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('username')
            ->add('email');
    }
    
  4. Batch Actions Enable batch operations in configureBatchActions:

    protected function configureBatchActions(BatchActionMapper $batchActionMapper)
    {
        $batchActionMapper
            ->add('delete', null, [
                'label' => 'Delete',
                'ask_confirmation' => true,
            ]);
    }
    
  5. Integration with Sonata Blocks Use the sonata.block service to embed admin content in blocks:

    {{ render(controller('SonataAdminBundle:Block:block', {
        'type': 'sonata.admin.block.admin_list',
        'code': 'app_user',
        'mode': 'list'
    })) }}
    
  6. Handling Embedded Documents For nested documents, use SonataAdminBundle's sonata_type_model:

    $formMapper->add('address', 'sonata_type_model', [
        'btn_add' => 'Add Address',
        'btn_edit' => 'Edit Address',
        'btn_delete' => 'Delete Address',
    ]);
    

Gotchas and Tips

Pitfalls

  1. Documentation Quirks

    • The README warns about broken reStructuredText in GitHub. Always refer to raw files or the Sonata Project docs.
    • Key classes like AbstractMongoDBAdmin may differ slightly from SonataAdminBundle's AbstractAdmin. Check inheritance chains carefully.
  2. Caching Issues

    • Clear both Symfony and Doctrine caches after changes:
      php bin/console cache:clear
      php bin/console doctrine:mongodb:cache:clear-metadata
      
    • Use --no-debug in production to avoid cache inconsistencies.
  3. MongoDB Schema Mismatches

    • Ensure your document annotations (@Document, @Field) align with the admin's expectations. Test with a fresh DB if fields disappear or errors occur.
  4. Translation Problems

    • The translationDomain must match your translation files (e.g., messages.en.yml). Verify domain names in configureTitleField and configureListFields.
  5. Route Conflicts

    • SonataAdmin routes may clash with other bundles. Prefix routes in sonata_admin.yaml if needed:
      sonata_admin:
          options:
              base_route_pattern: 'custom_admin'
              base_route: 'custom_admin'
      
  6. Performance with Large Datasets

    • MongoDB queries in the admin can be slow. Limit results in configureDatagridValues:
      $datagridMapper->add('id', null, [], 'string', 1); // Sort by ID
      $datagridMapper->add('username', null, [], 'string', 2); // Secondary sort
      

Debugging Tips

  1. Enable Debug Mode Set debug: true in config/packages/dev/sonata_admin.yaml to see SQL-like MongoDB queries.

  2. Log Queries Add this to config/packages/dev/doctrine_mongodb.yaml:

    doctrine_mongodb:
        logging: true
    

    Check logs in var/log/dev.log.

  3. Check Admin Registration If the admin doesn’t appear, verify:

    • The admin class is autoloaded (check composer dump-autoload).
    • The manager is listed in sonata_admin.yaml under the correct key (app in the example).
  4. Override Templates Copy templates from vendor/sonata-project/doctrine-mongodb-admin-bundle/Resources/views/ to templates/SonataAdminBundle/ to customize without overriding core files.

Extension Points

  1. Custom Field Types Extend Sonata\AdminBundle\Form\Type\ModelType for custom MongoDB field rendering.

  2. Event Listeners Use Symfony events (e.g., sonata.admin.pre_persist) to modify documents before save:

    $event->getSubject()->setUpdatedAt(new \DateTime());
    
  3. Dynamic Admins Generate admin classes dynamically using Sonata\AdminBundle\Generator\Generator:

    $generator = $this->get('sonata.admin.generator.admin');
    $generator->generate('App\Document\User', 'App\Admin\UserAdmin');
    
  4. MongoDB-Specific Features Leverage ODM features like @Index or @ReferenceMany in your documents and reflect them in the admin:

    // In your document
    use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
    
    /**
     * @MongoDB\Index(name="username_idx", keys={"username"="text"})
     */
    private $username;
    
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