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

News Bundle Laravel Package

sonata-project/news-bundle

SonataNewsBundle adds news/blog features to Symfony with Sonata integration. Includes admin management, posts, categories, comments, and RSS support. Note: the repository is abandoned and currently has no active maintenance or support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sonata-project/news-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Sonata\NewsBundle\SonataNewsBundle::class => ['all' => true],
    ];
    
  2. Database Migration: Run the SonataNewsBundle’s migrations (or manually create tables based on schema):

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Use Case: Create a news item via the admin interface (auto-generated by SonataAdminBundle):

    php bin/console sonata:admin:generate
    

    Access /admin/news to create/edit news entries.


Where to Look First

  • Admin Configuration: config/packages/sonata_admin.yaml (or config/packages/sonata_news.yaml if using standalone).
  • Templates: Override Sonata’s default templates in templates/SonataNewsBundle/ (e.g., default/index.html.twig).
  • Services: Extend or override services via config/services.yaml (e.g., sonata.news.manager.news).

Implementation Patterns

Core Workflows

1. Admin Integration

  • CRUD Operations: SonataAdminBundle handles news creation, editing, and deletion out-of-the-box.
  • Custom Fields: Extend the NewsAdmin class to add custom fields:
    // src/Admin/NewsAdmin.php
    use Sonata\AdminBundle\Admin\AbstractAdmin;
    use Sonata\NewsBundle\Admin\NewsAdmin as BaseNewsAdmin;
    
    class NewsAdmin extends BaseNewsAdmin {
        protected function configureFormFields(FormMapper $formMapper) {
            parent::configureFormFields($formMapper);
            $formMapper->add('custom_field', TextType::class);
        }
    }
    
  • Reordering: Enable drag-and-drop reordering in config/packages/sonata_admin.yaml:
    sonata_admin:
        options:
            delete:
                confirmation: true
            list:
                actions:
                    - { name: 'Reorder', label: 'sonata_news.admin.reorder', icon: '<i class="fa fa-sort"></i>' }
    

2. Frontend Display

  • List News: Use the sonata_news_list Twig function in templates:
    {{ sonata_news_list({
        'where': {'o.enabled': 1},
        'orderBy': {'o.createdAt': 'DESC'},
        'limit': 5
    }) }}
    
  • Single News: Access via route sonata_news_show with slug:
    {{ path('sonata_news_show', {'slug': news.slug}) }}
    
  • Pagination: Integrate with KnpPaginatorBundle for custom pagination:
    {% paginate newsItems %}
        {% for item in newsItems %}
            {{ item.title }}
        {% endfor %}
    {% endpaginate %}
    

3. API Exposure

  • REST API: Use SonataApiBundle to expose news as an API:
    # config/packages/sonata_api.yaml
    sonata_api:
        resources:
            - { resource: 'Sonata\NewsBundle\Entity\News', group_name: 'news', formats: [json] }
    
  • GraphQL: Integrate with API Platform for GraphQL support.

4. Event Handling

  • Pre/Post Save: Listen to sonata.news.pre_persist or sonata.news.post_persist events:
    // src/EventListener/NewsListener.php
    use Sonata\NewsBundle\Event\NewsEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class NewsListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                NewsEvent::PRE_PERSIST => 'onPrePersist',
            ];
        }
    
        public function onPrePersist(NewsEvent $event) {
            $news = $event->getSubject();
            $news->setSeoTitle('Default SEO Title');
        }
    }
    

Integration Tips

  • Symfony Flex: Use config/packages/sonata_news.yaml for bundle configuration (e.g., enable/disable features):
    sonata_news:
        class:
            news: App\Entity\News
            media: Sonata\MediaBundle\Entity\Media
        db_driver: doctrine_orm # or doctrine_mongodb
        persist_media: true
    
  • Media Integration: Pair with SonataMediaBundle for rich media support:
    sonata_media:
        db_driver: doctrine_orm
        context:
            default:
                providers:
                    - sonata.media.provider.dailymotion
                    - sonata.media.provider.youtube
                    - sonata.media.provider.image
    
  • Translation: Override translations in translations/messages.en.yaml:
    sonata_news:
        admin:
            label_news: "Blog Post"
            label_news_plural: "Blog Posts"
    

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle:

    • The bundle is archived (last release in 2021). Use at your own risk or fork for maintenance.
    • Workaround: Pin to a specific version in composer.json:
      "sonata-project/news-bundle": "3.11"
      
  2. Doctrine Migrations:

    • Manual schema updates may be needed if extending the News entity. Always back up your database before migrations.
  3. Admin Route Conflicts:

    • SonataAdminBundle routes may clash with custom routes. Use _sonata_admin prefix or override routing:
      # config/routes.yaml
      sonata_news:
          resource: '@SonataNewsBundle/Resources/config/routing/admin.xml'
          prefix: /admin/news
      
  4. Media Handling:

    • If persist_media: false, media files won’t be saved to the database. Ensure proper file storage (e.g., AWS S3) is configured in sonata_media.
  5. Caching Issues:

    • Clear cache after extending templates or services:
      php bin/console cache:clear
      

Debugging Tips

  1. Admin Panel Not Showing:

    • Ensure SonataAdminBundle is installed and configured:
      composer require sonata-project/admin-bundle
      
    • Check sonata_admin configuration in config/packages/sonata_admin.yaml:
      sonata_admin:
          security:
              handler: sonata.admin.security.handler.acl
          templates:
              layout: 'SonataAdminBundle::standard_layout.html.twig'
      
  2. News Not Displaying:

    • Verify the News entity is properly mapped and the enabled field is set to true:
      // src/Entity/News.php
      /** @ORM\Column(type="boolean") */
      private $enabled = true;
      
    • Check Twig errors for missing variables (e.g., newsItems not passed to the template).
  3. Database Errors:

    • Run php bin/console doctrine:schema:validate to check schema compatibility.
    • For MongoDB, ensure doctrine_mongodb_odm is installed and configured.

Extension Points

  1. Custom News Entity:

    • Extend the default News entity to add fields:
      // src/Entity/News.php
      use Sonata\NewsBundle\Entity\BaseNews;
      
      class News extends BaseNews {
          /** @ORM\Column(type="string", length=255) */
          private $customField;
      }
      
    • Update sonata_news.class.news in config to point to your entity.
  2. Custom Repository:

    • Override the default repository for custom queries:
      // src/Repository/NewsRepository.php
      use Sonata\NewsBundle\Repository\NewsRepository as BaseNewsRepository;
      
      class NewsRepository extends BaseNewsRepository {
          public function findPublished() {
              return $this->createQueryBuilder('o')
                  ->where('o.enabled = :enabled')
                  ->setParameter('enabled', true)
                  ->orderBy('o.createdAt', 'DESC')
                  ->getQuery()
                  ->getResult();
          }
      }
      
    • Bind the repository in services.yaml:
      services:
          App\Repository\NewsRepository:
              parent: sonata.news.repository.news
              tags: ['doctrine.repository_service']
      
  3. Custom Templates:

    • Override Sonata’s templates in templates/SonataNewsBundle/:
      templates
      
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.
terminal42/code-quality-tools
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