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

Translator Bundle Laravel Package

domis86/translator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require domis86/translator-bundle
    

    Add to config/bundles.php:

    Domis86\TranslatorBundle\Domis86TranslatorBundle::class => ['all' => true],
    
  2. Database Configuration: Run migrations to create the translations table:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. Enable WebDebugToolbar Integration: Ensure WebProfilerBundle is enabled (default in Symfony Flex). The toolbar will now show translation counts and missing translations.

  4. First Use Case:

    • Visit any page with translations (e.g., {{ 'homepage.title'|trans }}).
    • Open the WebDebugToolbar"Translations" tab.
    • Edit translations directly in the browser via the inline editor.

Implementation Patterns

Workflow: Inline Translation Editing

  1. Debugging Translations:

    • Use the WebDebugToolbar to inspect translations used in the current request.
    • Click the translation count to open the editor for quick fixes.
  2. Admin Interface Integration:

    • Extend the bundle’s admin controller (Domis86\TranslatorBundle\Controller\TranslationController) to add a dedicated admin panel:
      <!-- templates/translator/admin.html.twig -->
      {% extends 'translator:admin:index.html.twig' %}
      {% block body %}
          {{ parent() }}
          <!-- Custom filters or bulk actions -->
      {% endblock %}
      
    • Override routes in config/routes.yaml:
      translator_admin:
          resource: "@Domis86TranslatorBundle/Resources/config/routing/admin.yaml"
          prefix: /admin/translations
      
  3. Fallback Logic:

    • Configure fallback chains in config/packages/translator.yaml:
      framework:
          translator:
              fallbacks:
                  - "%locale%"
                  - en
      
    • The bundle prioritizes DB translations over files. Use translator.use_db to toggle:
      domis86_translator:
          use_db: true  # Default: true
      
  4. Caching:

    • Leverage Symfony’s cache system for performance:
      domis86_translator:
          cache:
              enabled: true
              pool: cache.app
      

Gotchas and Tips

Pitfalls

  1. Database Locking:

    • Concurrent edits may cause race conditions. Use transactions for bulk operations:
      $entityManager->beginTransaction();
      try {
          $translation = $entityManager->getRepository(Translation::class)->findOneBy(['id' => $id]);
          $translation->setContent($newContent);
          $entityManager->flush();
          $entityManager->commit();
      } catch (\Exception $e) {
          $entityManager->rollback();
          throw $e;
      }
      
  2. Missing Translations:

    • The toolbar highlights missing translations in red. Clicking them creates a new DB entry. Ensure your Translation entity has allowMissing: true in the repository:
      // src/Repository/TranslationRepository.php
      public function findMissing($domain, $id, $locale)
      {
          return null; // Forces creation of new entry
      }
      
  3. Locale-Specific Quirks:

    • Right-to-left (RTL) languages may require CSS adjustments for the inline editor. Override the Twig template:
      {% extends 'translator:edit_dialog.html.twig' %}
      {% block styles %}
          {{ parent() }}
          <style>
              .translator-editor { direction: rtl; }
          </style>
      {% endblock %}
      

Debugging

  • Log Missing Translations: Enable logging in config/packages/monolog.yaml:
    monolog:
        handlers:
            translator:
                type: stream
                path: "%kernel.logs_dir%/translator.log"
                level: debug
                channels: ["translator"]
    
    Then, in your TranslationListener, log missing keys:
    public function onKernelRequest(GetResponseEvent $event)
    {
        $translator = $this->container->get('translator');
        $translator->addMissingTranslationListener(function ($missing) {
            $this->logger->debug('Missing translation', ['missing' => $missing]);
        });
    }
    

Extension Points

  1. Custom Validation: Extend the Translation entity to add validation rules:

    // src/Entity/Translation.php
    use Symfony\Component\Validator\Constraints as Assert;
    
    /**
     * @Assert\Length(max=255)
     * @Assert\NotBlank
     */
    private $content;
    
  2. Event Listeners: Subscribe to translation events (e.g., translator.pre_save):

    // src/EventListener/TranslationListener.php
    use Domis86\TranslatorBundle\Event\TranslationEvents;
    
    public function onPreSave(TranslationEvent $event)
    {
        $translation = $event->getTranslation();
        $translation->setCreatedAt(new \DateTime());
    }
    

    Register in services.yaml:

    services:
        App\EventListener\TranslationListener:
            tags:
                - { name: kernel.event_listener, event: translator.pre_save, method: onPreSave }
    
  3. Override Templates: Copy templates from vendor/domis86/translator-bundle/Resources/views/ to templates/translator/ to customize:

    • edit_dialog.html.twig (inline editor UI).
    • admin/index.html.twig (admin panel layout).
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