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

Sonata Translation Bundle Laravel Package

awaresoft/sonata-translation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation via Composer (if not symlinked):

    composer require awaresoft/sonata-translation-bundle
    

    Note: Follow the README’s symlink instructions if modifying locally.

  2. Enable the Bundle in config/bundles.php:

    return [
        // ...
        Awaresoft\SonataTranslationBundle\SonataTranslationBundle::class => ['all' => true],
    ];
    
  3. Basic Configuration in config/packages/sonata_translation.yaml:

    sonata_translation:
        default_locale: en
        locales: [en, fr, es]
        driver: doctrine # or 'orm'/'mongodb'
    
  4. First Use Case:

    • Translate a Doctrine entity field:
      use Awaresoft\SonataTranslationBundle\Model\TranslationInterface;
      
      class Product implements TranslationInterface
      {
          // ...
          private $translations;
      }
      
    • Add translations via a form or admin panel (SonataAdmin integration assumed).

Implementation Patterns

Workflow: Translatable Entities

  1. Mark Entities as Translatable: Implement TranslationInterface and define getTranslations()/setTranslations().

    class Article implements TranslationInterface
    {
        public function getTranslations()
        {
            return $this->translations;
        }
    }
    
  2. Database Schema: Use the bundle’s Doctrine event listeners to auto-generate translation tables (e.g., article_translation).

    # config/packages/doctrine.yaml
    doctrine:
        orm:
            mappings:
                sonata_translation:
                    type: attribute
                    dir: "%kernel.project_dir%/vendor/awaresoft/sonata-translation-bundle/Resources/config/doctrine"
                    prefix: 'Awaresoft\SonataTranslationBundle\Model'
    
  3. Form Integration: Extend AbstractType to handle translations:

    use Awaresoft\SonataTranslationBundle\Form\Type\TranslationType;
    
    $builder->add('translations', TranslationType::class, [
        'locales' => ['en', 'fr'],
        'entry_type' => ArticleTranslationType::class,
    ]);
    
  4. Admin Panel (SonataAdmin): Enable translations in your admin class:

    protected function configureFields(FieldMap $fields)
    {
        $fields->add('translations', 'sonata_type_translatable', [
            'locales' => ['en', 'fr'],
        ]);
    }
    

Common Patterns

  • Fallback Logic: Configure default locale fallbacks in sonata_translation.yaml:
    sonata_translation:
        fallback_locale: en
    
  • Dynamic Locale Switching: Use the LocaleListener to switch locales mid-request:
    $this->get('sonata_translation.locale_listener')->setLocale('fr');
    
  • Translation Validation: Add constraints to translation fields:
    use Symfony\Component\Validator\Constraints as Assert;
    
    $builder->add('translations', TranslationType::class, [
        'entry_options' => [
            'constraints' => [
                new Assert\NotBlank(),
            ],
        ],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Doctrine Event Conflicts:

    • If using other translation bundles (e.g., Gedmo), disable Sonata’s listeners in services.yaml:
      services:
          Awaresoft\SonataTranslationBundle\EventListener\Doctrine\TranslationLifecycleListener: ~
      
    • Symptom: Duplicate translation tables or errors on entity save.
  2. Locale-Specific Queries:

    • The bundle does not auto-fetch translations for missing locales. Always check:
      if (!$entity->getTranslation($locale)) {
          return $entity->getTranslation($fallbackLocale);
      }
      
  3. Symlink Breakage:

    • After modifying the vendor, clear cache and rebuild autoloader:
      php bin/console cache:clear
      composer dump-autoload
      
  4. Symfony 4+ Compatibility:

    • The bundle targets Symfony 2.x. For Symfony 4/5/6:
      • Override SonataTranslationBundle to extend Bundle (not ContainerAwareBundle).
      • Manually register services in resources/config/services.yaml.

Debugging Tips

  • Missing Translations:

    • Verify the translations association is mapped in Doctrine:
      /**
       * @ORM\OneToMany(targetEntity="Translation", mappedBy="translatable")
       */
      private $translations;
      
    • Check for SQL errors in var/log/dev.log (e.g., missing foreign keys).
  • Locale Not Switching:

    • Ensure the LocaleListener is enabled in kernel.event_subscribers:
      public static $subscribedEvents = [
          KernelEvents::REQUEST => ['onKernelRequest', 16],
      ];
      

Extension Points

  1. Custom Translation Storage: Override the TranslationManager to use a custom driver (e.g., Redis):

    class CustomTranslationManager extends TranslationManager
    {
        public function findTranslation($id, $locale)
        {
            // Custom logic
        }
    }
    

    Register it in services.yaml:

    services:
        sonata_translation.manager:
            class: App\Service\CustomTranslationManager
            arguments: ['@doctrine.orm.entity_manager']
    
  2. Translation Events: Listen for sonata_translation.pre_save/post_save:

    use Awaresoft\SonataTranslationBundle\Event\TranslationEvent;
    
    $dispatcher->addListener(TranslationEvent::PRE_SAVE, function (TranslationEvent $event) {
        // Pre-save logic (e.g., sanitize content)
    });
    
  3. Admin Customization: Extend the TranslationAdmin class to add fields or actions:

    class CustomTranslationAdmin extends TranslationAdmin
    {
        protected function configureFormFields(FormMapper $formMapper)
        {
            $formMapper->add('custom_field');
        }
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
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