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

sonata-project/doctrine-mongodb-admin-bundle

Symfony bundle that integrates Doctrine MongoDB ODM with SonataAdminBundle, providing admin services, mappers, and datagrid support to manage MongoDB documents via Sonata’s admin UI. Includes docs, CI, and versioned releases.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sonata-project/doctrine-mongodb-admin-bundle
    

    Ensure SonataDoctrineMongoDBAdminBundle is enabled in config/bundles.php:

    return [
        // ...
        SonataDoctrineMongoDBAdminBundle\SonataDoctrineMongoDBAdminBundle::class => ['all' => true],
    ];
    
  2. Configure MongoDB ODM: Add MongoDB connection to config/packages/doctrine_mongodb.yaml:

    doctrine_mongodb:
        connections:
            default:
                servers: ['mongodb://localhost:27017']
                options: {}
        default_database: app_db
        document_managers:
            default:
                auto_mapping: true
    
  3. Create a Basic Admin Class:

    // src/Admin/PostAdmin.php
    namespace App\Admin;
    
    use Sonata\DoctrineMongoDBAdminBundle\Admin\AbstractAdmin;
    use Sonata\DoctrineMongoDBAdminBundle\Datagrid\DatagridMapper;
    use Sonata\DoctrineMongoDBAdminBundle\Form\FormMapper;
    
    class PostAdmin extends AbstractAdmin
    {
        protected $datagridValues = [
            '_page' => 1,
            '_per_page' => 10,
        ];
    
        protected function configureDatagridFilters(DatagridMapper $datagridMapper)
        {
            $datagridMapper->add('title');
        }
    
        protected function configureFormFields(FormMapper $formMapper)
        {
            $formMapper
                ->tab('General')
                    ->with('Content')
                        ->add('title')
                        ->add('content')
                    ->end()
                ->end();
        }
    }
    
  4. Register Admin in Services:

    # config/services.yaml
    services:
        App\Admin\PostAdmin:
            tags: [sonata.admin]
            arguments: ['App\Entity\Post', App\Admin\PostAdmin, 'SonataDoctrineMongoDBAdminBundle:CRUD', 'Post', 'Post']
    
  5. Access Admin Panel: Visit /admin/app_post_post to see the generated CRUD interface.


First Use Case: Quick CRUD for a MongoDB Document

  • Use the generated admin class to manage Post documents with fields like title and content.
  • Leverage Sonata’s built-in features (list, create, edit, delete) without writing custom controllers.

Implementation Patterns

Common Workflows

1. Field Customization

Override configureFormFields to customize form rendering:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('title', 'text', [
            'label' => 'Post Title',
            'attr' => ['class' => 'form-control'],
        ])
        ->add('publishedAt', 'sonata_type_datetime_picker', [
            'dp_options' => ['format' => 'YYYY-MM-DD HH:mm:ss'],
        ]);
}

2. Datagrid Filtering and Sorting

Customize list views with filters and sorting:

protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper
        ->add('title', null, [
            'label' => 'Title',
            'field_type' => 'string',
        ])
        ->add('publishedAt', 'doctrine_odm_mongodb_date', [
            'field_type' => 'date',
            'label' => 'Published At',
        ]);
}

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        ->add('title', null, [
            'template' => 'SonataDoctrineMongoDBAdminBundle:CRUD:list_field.html.twig',
        ])
        ->add('publishedAt', null, ['template' => 'SonataDoctrineMongoDBAdminBundle:CRUD:list_date.html.twig']);
}

3. Embedded Documents

Handle nested documents (e.g., Author embedded in Post):

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->tab('Author')
            ->with('Details')
                ->add('author.name', 'text')
                ->add('author.bio', 'textarea')
            ->end()
        ->end();
}

4. Batch Actions

Add bulk operations:

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        ->add('_action', 'actions', [
            'actions' => [
                'edit' => [],
                'delete' => [],
                'publish' => ['template' => 'SonataDoctrineMongoDBAdminBundle:CRUD:list__action_publish.html.twig'],
            ],
        ]);
}

public function preBatchAction($action, QueryBuilder $query)
{
    if ('publish' === $action) {
        $query->update(['publishedAt' => new \DateTime()]);
    }
}

5. Custom Templates

Override Sonata’s templates:

{# templates/admin/PostAdmin/edit.html.twig #}
{% extends 'SonataDoctrineMongoDBAdminBundle:CRUD:edit.html.twig' %}

{% block sonata_form_buttons %}
    {{ parent() }}
    <button type="button" class="btn btn-primary">Custom Action</button>
{% endblock %}

Integration Tips

1. Symfony Forms Integration

Use Symfony’s form types directly:

$formMapper->add('tags', 'sonata_type_collection', [
    'by_reference' => false,
    'type_options' => ['delete_empty' => true],
]);

2. Event Listeners

Hook into lifecycle events:

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

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

3. Security

Restrict access to admins:

# config/packages/security.yaml
access_control:
    - { path: ^/admin, roles: ROLE_ADMIN }

4. Translation

Localize labels and placeholders:

# config/packages/sonata_admin.yaml
sonata_admin:
    templates:
        layout: 'SonataAdminBundle::standard_layout.html.twig'
    translations:
        - 'en'
        - 'fr'

5. API Integration

Expose admin actions as API endpoints:

public function generateRouteName()
{
    return 'api_post';
}

public function getRoutePrefix()
{
    return 'api';
}

Gotchas and Tips

Pitfalls

1. Deprecation Warnings

  • The bundle actively deprecates old methods (e.g., ModelManager::getMetadata()). Use updated APIs:
    // Old (deprecated)
    $metadata = $this->getModelManager()->getMetadata();
    
    // New
    $metadata = $this->getModelManager()->getClassMetadata(get_class($this->getSubject()));
    
  • Check the changelog for breaking changes.

2. MongoDB ODM Quirks

  • Embedded Documents: Ensure proper mapping in your document classes:
    use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
    
    /**
     * @MongoDB\EmbedOne(targetDocument="Author")
     */
    private $author;
    
  • Reference Fields: Use ReferenceMany or ReferenceOne for relationships:
    /**
     * @MongoDB\ReferenceMany(targetDocument="Comment")
     */
    private $comments;
    

3. Caching Issues

  • Clear Sonata’s cache after changes:
    php bin/console cache:clear
    php bin/console sonata:admin:cache:clear
    

4. Field Description Confusion

  • Avoid manually instantiating FieldDescription; use the factory:
    // Old (deprecated)
    $fieldDescription = new FieldDescription('title', 'string');
    
    // New
    $fieldDescription = $this->getModelManager()->getFieldDescriptionFactory()->createFieldDescription('title');
    

5. Query Builder Limitations

  • MongoDB’s query syntax differs from SQL. Use Criteria for complex queries:
    $query = $this->getModelManager()->createQueryBuilder('Post')
        ->field('title')->equals('Hello')
        ->field('publishedAt')->gte(new \DateTime('-1 year'));
    

Debugging Tips

1. Enable Debug Mode

# config/packages/dev/sonata_admin.yaml
sonata_admin:
    debug: true

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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor