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

Comment Bundle Laravel Package

sonata-project/comment-bundle

SonataCommentBundle integrates FOSCommentBundle into the Sonata ecosystem, providing comment management features for Sonata-based Symfony apps. Note: this repository is abandoned and not actively maintained; community help is welcome.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sonata-project/comment-bundle
    

    Ensure you have sonata-project/doctrine-orm-admin-bundle installed (required for admin integration).

  2. Enable Bundle: Add to config/bundles.php:

    SonataProject\CommentBundle\SonataCommentBundle::class => ['all' => true],
    
  3. Database Migration: Run migrations to create the Comment and CommentThread tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  4. Basic Configuration: Update config/packages/sonata_comment.yaml (auto-generated):

    sonata_comment:
        class:
            model_comment: App\Entity\Comment
            model_thread: App\Entity\CommentThread
            form_type_comment: App\Form\CommentType
        admin:
            comment:
                template: SonataCommentBundle:Comment:admin_list.html.twig
    
  5. First Use Case: Enable comments on a Sonata Admin entity (e.g., Post):

    // src/Admin/PostAdmin.php
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper->add('comments', 'sonata_type_collection', [
            'by_reference' => false,
        ]);
    }
    

Implementation Patterns

Core Workflows

1. Integrating Comments with Sonata Admin

  • Entity Setup: Add CommentableInterface to your entity (e.g., Post):
    use Sonata\CommentBundle\Model\CommentableInterface;
    
    class Post implements CommentableInterface
    {
        // ...
        public function getCommentableSubject(): string
        {
            return $this->title;
        }
    }
    
  • Admin Configuration: Extend SonataAdminBundle\Admin\AbstractAdmin and override configureFormFields:
    $formMapper->add('comments', 'sonata_type_collection', [
        'label' => 'Comments',
        'required' => false,
        'cascade_validation' => true,
    ]);
    

2. Customizing Comment Forms

  • Extend the default CommentType:
    // src/Form/CommentType.php
    use Sonata\CommentBundle\Form\Type\CommentType as BaseCommentType;
    
    class CommentType extends BaseCommentType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            parent::buildForm($builder, $options);
            $builder->add('custom_field', TextType::class);
        }
    }
    
  • Update sonata_comment.yaml:
    sonata_comment:
        class:
            form_type_comment: App\Form\CommentType
    

3. Displaying Comments in Templates

  • Use Twig functions in your entity show template:
    {% for comment in sonata_comment_get_thread(entity).comments %}
        <div class="comment">
            {{ comment.body }}
            <small>{{ comment.createdAt|date('M d, Y') }}</small>
        </div>
    {% endfor %}
    

4. Thread Management

  • Manually create/update threads:
    $thread = $commentManager->createThread($entity);
    $comment = $commentManager->createComment($thread, $author, $body);
    $commentManager->saveComment($comment);
    

5. API/REST Integration

  • Use Symfony’s Serializer to expose comments as JSON:
    $comments = $commentManager->getThread($entity)->getComments();
    return $this->json($comments);
    

Integration Tips

Sonata Admin Integration

  • Lazy-Loading Comments: Override configureListFields to avoid N+1 queries:
    $formMapper->add('comments', 'sonata_type_collection', [
        'by_reference' => false,
        'label' => false,
        'sonata_type_collection_allow_add' => false,
        'sonata_type_collection_allow_delete' => false,
    ]);
    

Frontend Customization

  • Twig Extensions: Use sonata_comment_get_thread and sonata_comment_get_comments in templates:
    {% set thread = sonata_comment_get_thread(app.user.post) %}
    {% for comment in sonata_comment_get_comments(thread) %}
        {{ comment.body }}
    {% endfor %}
    

Security

  • Restrict comment creation to authenticated users:
    # config/packages/security.yaml
    access_control:
        - { path: ^/comment/new, roles: ROLE_USER }
    

Performance

  • Caching Threads: Cache thread data in AppCache:
    $cache = $this->get('sonata.cache');
    $thread = $cache->get('thread_' . $entity->getId(), function() use ($entity) {
        return $commentManager->getThread($entity);
    });
    

Gotchas and Tips

Pitfalls

  1. Deprecated Dependencies:

    • Avoid SonataEasyExtendsBundle (deprecated in v3.3.0). Use SonataDoctrineBundle instead.
    • Fix: Remove SonataEasyExtendsBundle and update Doctrine mappings manually.
  2. Symfony Version Mismatch:

    • Bundle drops support for Symfony < 4.4 (v3.3.0+). Ensure compatibility:
      composer require symfony/*:^4.4|^5.0
      
  3. Template Paths:

    • Hardcoded template paths in older versions may break. Use Twig’s namespaced syntax:
      {# Old (deprecated) #}
      SonataCommentBundle:Comment:list.html.twig
      
      {# New #}
      @SonataComment/Comment/list.html.twig
      
  4. Command Failures:

    • Commands may fail in Symfony 4+ due to service container changes. Rebuild cache:
      php bin/console cache:clear
      
  5. Translation Issues:

    • Missing translations (e.g., Russian) may appear if not explicitly added. Extend translations:
      # config/packages/translation.yaml
      frameworks:
          translator:
              paths:
                  - '%kernel.project_dir%/vendor/sonata-project/comment-bundle/Resources/translations'
      

Debugging Tips

  1. Enable Debug Mode:

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

    Logs SQL queries and template rendering issues.

  2. Check Event Listeners:

    • Override comment events (e.g., sonata.comment.post_create):
      // src/EventListener/CommentListener.php
      public function onPostCreate(PostCreateEvent $event)
      {
          $comment = $event->getComment();
          // Custom logic
      }
      
    • Register in services.yaml:
      services:
          App\EventListener\CommentListener:
              tags:
                  - { name: kernel.event_listener, event: sonata.comment.post_create, method: onPostCreate }
      
  3. Database Schema:

    • Verify migrations:
      php bin/console doctrine:schema:validate
      

Extension Points

  1. Custom Comment Models: Extend Sonata\CommentBundle\Model\Comment and CommentThread:

    class AppComment extends Comment
    {
        private $customField;
    
        // Add getters/setters
    }
    

    Update sonata_comment.yaml:

    sonata_comment:
        class:
            model_comment: App\Entity\AppComment
    
  2. Dynamic Threads: Override getCommentableSubject() for dynamic thread subjects:

    public function getCommentableSubject(): string
    {
        return "Post #{$this->id}";
    }
    
  3. API Endpoints: Create a custom controller for comment CRUD:

    #[Route('/api/comments', name: 'api_comment_')]
    class CommentController extends AbstractController
    {
        #[Route('/{id}', name: 'read', methods: ['GET'])]
        public function read(Comment $comment): JsonResponse
        {
            return $this->json($comment);
        }
    }
    
  4. Notification System: Trigger events on comment creation:

    $dispatcher->dispatch(new CommentEvent($comment), 'sonata.comment.post_create');
    

Configuration Quirks

  1. Parameter Overrides: Override default parameters in config/packages/sonata_comment.yaml:

    sonata_comment:
        admin:
            comment:
                template: custom/path.html.twig
                list:
                    actions:
                        _delete: { 'attr' => { 'class' => 'btn-danger' } }
    
  2. Form Theme: Customize form themes by extending the default:

    {
    
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