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

Translation Base Bundle Laravel Package

braune-digital/translation-base-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies Run:

    composer require braune-digital/translation-base-bundle knp/doctrine-behaviors a2lix/translation-form-bundle
    

    For SonataAdmin integration:

    composer require sonata-project/admin-bundle sonata-project/doctrine-orm-admin-bundle ivory/ckeditor-bundle
    
  2. Enable Bundles Add to config/bundles.php (or AppKernel.php for Symfony <5.0):

    BrauneDigital\TranslationBaseBundle\BrauneDigitalTranslationBaseBundle::class => ['all' => true],
    Knp\DoctrineBehaviors\KnpDoctrineBehaviorsBundle::class => ['all' => true],
    A2lix\TranslationFormBundle\A2lixTranslationFormBundle::class => ['all' => true],
    
  3. Configure Translatable Entities Use Translatable behavior on your entity:

    use Knp\DoctrineBehaviors\Model\Translatable\Translatable;
    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * @ORM\Entity
     * @ORM\HasLifecycleCallbacks
     */
    class YourEntity
    {
        use Translatable;
    
        // ...
    }
    
  4. First Use Case Create a translatable field in your entity (e.g., title):

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $title;
    

    The bundle automatically generates YourEntityTranslation with title as translatable.


Implementation Patterns

Workflow for Translatable Entities

  1. Define Translatable Fields Mark fields with Translatable behavior. The bundle splits them into a separate translation entity.

  2. Admin Integration (SonataAdmin) Extend SonataAdmin services to use the bundle’s templates:

    # config/packages/sonata_admin.yaml
    sonata_admin:
        templates:
            layout: BrauneDigitalTranslationBaseBundle:admin/translation_layout.html.twig
    
  3. Form Handling Use A2lixTranslationFormBundle for translation-aware forms:

    use A2lix\TranslationFormBundle\Form\Type\TranslationType;
    
    $builder->add('translations', TranslationType::class, [
        'fields' => ['title', 'description'],
    ]);
    
  4. Custom Translation Logic Override default behavior by extending the bundle’s services or creating custom listeners:

    // src/EventSubscriber/TranslationSubscriber.php
    class TranslationSubscriber implements EventSubscriberInterface
    {
        public function getSubscribedEvents()
        {
            return [
                KernelEvents::VIEW => ['onKernelView', 20],
            ];
        }
    
        public function onKernelView(ViewEvent $event)
        {
            // Custom logic for translations
        }
    }
    
  5. CKEditor Integration (Optional) Configure IvoryCKEditorBundle for rich-text translatable fields:

    ivory_ck_editor:
        default_config: default
        configs:
            default:
                filebrowserImageUploadRoute: sonata_media_provider_image_media_upload_media
                filebrowserBrowseRoute: sonata_media_provider_image_media_browse_media
    

Integration Tips

  • Localization Context Use Translatable with Locale to manage language-specific data:

    use Knp\DoctrineBehaviors\Model\Translatable\TranslationInterface;
    
    class YourEntityTranslation implements TranslationInterface
    {
        // ...
    }
    
  • Fallback Logic Implement fallback locales in config/packages/a2lix_translation_form.yaml:

    a2lix_translation_form:
        fallback_locale: en
        fallback_method: default
    
  • Performance Use DQL to fetch translations efficiently:

    $query = $entityManager->createQuery(
        'SELECT t FROM YourBundle:YourEntityTranslation t WHERE t.translatable = :entity'
    )->setParameter('entity', $entity);
    

Gotchas and Tips

Pitfalls

  1. Missing Dependencies

    • Forgetting KnpDoctrineBehaviors or A2lixTranslationFormBundle will break translation functionality.
    • Fix: Ensure all dependencies are installed and enabled.
  2. Template Overrides

    • Custom templates (e.g., translation_layout.html.twig) may not render if paths are incorrect.
    • Fix: Verify template paths in config.yml and clear cache:
      php bin/console cache:clear
      
  3. Locale Mismatches

    • Translations may not appear if the locale is not set in the request.
    • Fix: Configure default locale in config/packages/framework.yaml:
      framework:
          default_locale: en
      
  4. SonataAdmin Conflicts

    • The bundle’s translation_layout.html.twig may conflict with existing SonataAdmin templates.
    • Fix: Copy the template to your theme and customize it.
  5. Outdated Bundle

    • Last release was in 2016; some Symfony/Doctrine features may not work.
    • Fix: Fork the repository and update dependencies (e.g., knp/doctrine-behaviors to v2+).

Debugging

  1. Check Generated Entities Verify YourEntityTranslation is created with correct fields:

    php bin/console doctrine:schema:update --dump-sql
    
  2. Enable Debugging for Translations Add to config/packages/dev/doctrine.yaml:

    doctrine:
        orm:
            filters:
                translatable:
                    class: Knp\DoctrineBehaviors\Model\Translatable\Query\TranslatableFilter
                    enabled: true
    
  3. Log Translation Events Enable Symfony’s profiler to inspect translation-related events:

    php bin/console debug:event-dispatcher
    

Extension Points

  1. Custom Translation Entities Extend the default TranslationInterface to add metadata:

    class CustomTranslation implements TranslationInterface
    {
        /**
         * @ORM\Column(type="string", length=50)
         */
        private $customField;
    }
    
  2. Dynamic Translation Fields Use callbacks to dynamically add translatable fields:

    use Knp\DoctrineBehaviors\Model\Translatable\Translatable;
    
    class DynamicEntity
    {
        use Translatable;
    
        public function getTranslatableFields()
        {
            return ['title', 'description', 'dynamic_field_' . uniqid()];
        }
    }
    
  3. Override Bundle Services Replace the bundle’s services (e.g., translation.listener) in config/services.yaml:

    services:
        App\EventListener\CustomTranslationListener:
            tags:
                - { name: kernel.event_listener, event: your.event, method: onYourEvent }
    
  4. Add Validation Use Symfony’s validator constraints on translatable fields:

    use Symfony\Component\Validator\Constraints as Assert;
    
    /**
     * @Assert\Length(max=100)
     */
    protected $title;
    
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