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 Form Bundle Laravel Package

deadkash/translation-form-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require a2lix/translation-form-bundle
    

    Add to config/bundles.php:

    A2lix\TranslationFormBundle\A2lixTranslationFormBundle::class => ['all' => true],
    
  2. Enable Translations Configure config/packages/a2lix_translation_form.yaml:

    a2lix_translation_form:
        default_locale: en
        supported_locales: [en, fr, es]
        translation_class: App\Entity\Translation
    
  3. First Use Case: Translatable Entity Annotate your entity with Translation:

    use A2lix\TranslationFormBundle\Model\TranslationInterface;
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity]
    class Product implements TranslationInterface
    {
        #[ORM\Id]
        private ?int $id = null;
    
        #[ORM\Column(type: 'string')]
        private string $name;
    
        #[ORM\Column(type: 'string')]
        private string $description;
    
        // Getters/setters...
    }
    
  4. Form Integration Use the TranslationType in your form:

    use A2lix\TranslationFormBundle\Form\Type\TranslationType;
    
    $builder->add('product', TranslationType::class, [
        'class' => Product::class,
        'translation_class' => ProductTranslation::class,
        'translatable_fields' => ['name', 'description'],
    ]);
    

Implementation Patterns

Common Workflows

1. Basic Translation Handling

  • Form Submission: The bundle automatically handles locale-specific fields (e.g., name_en, name_fr).
  • Locale Switching: Use translation_locale form field to switch between locales dynamically:
    $builder->add('translation_locale', LocaleType::class, [
        'choices' => ['en' => 'English', 'fr' => 'French'],
    ]);
    

2. Nested Translations

  • For nested entities (e.g., ProductCategory), configure the translation_class and translatable_fields hierarchically:
    # config/packages/a2lix_translation_form.yaml
    a2lix_translation_form:
        translation_classes:
            App\Entity\Product: App\Entity\ProductTranslation
            App\Entity\Category: App\Entity\CategoryTranslation
    

3. Dynamic Field Mapping

  • Use translatable_fields to dynamically include/exclude fields:
    $builder->add('product', TranslationType::class, [
        'translatable_fields' => $this->getTranslatableFields($userRole),
    ]);
    

4. Custom Validation

  • Add validation constraints to translated fields:
    use Symfony\Component\Validator\Constraints as Assert;
    
    #[ORM\Entity]
    class ProductTranslation
    {
        #[ORM\Column(type: 'string')]
        #[Assert\NotBlank(groups: ['fr'])]
        private string $name;
    }
    

5. API Integration

  • Use SerializerNormalizer to expose translations in API responses:
    # config/packages/serializer.yaml
    framework:
        serializer:
            normalizers:
                A2lix\TranslationFormBundle\Serializer\TranslationNormalizer: ~
    

Integration Tips

Symfony Forms

  • Locale-Aware Forms: Pass the current locale to the form factory:
    $form = $this->createForm(TranslationType::class, $product, [
        'translation_locale' => $request->getLocale(),
    ]);
    

Doctrine Events

  • Pre-Persist/Update: Handle translation creation/updates:
    use A2lix\TranslationFormBundle\Event\TranslationEvents;
    use A2lix\TranslationFormBundle\Event\TranslationEvent;
    
    $dispatcher->addListener(TranslationEvents::PRE_TRANSLATION_CREATE, function (TranslationEvent $event) {
        $event->getTranslation()->setCreatedBy($this->getUser());
    });
    

Twig Templates

  • Access translated fields in templates:
    {{ product.name|trans({ locale: app.request.locale }) }}
    

Command-Line Tools

  • Use the a2lix:translation:dump command to generate translation entities:
    php bin/console a2lix:translation:dump
    

Gotchas and Tips

Pitfalls

1. Locale Mismatch

  • Issue: Translated fields may not render if the translation_locale is missing or invalid.
  • Fix: Ensure translation_locale is always set in the form:
    $builder->add('translation_locale', HiddenType::class, [
        'data' => $request->getLocale(),
    ]);
    

2. Circular References

  • Issue: Nested translations with circular references (e.g., ProductCategoryProduct) cause infinite loops.
  • Fix: Exclude circular fields from translatable_fields or use ignore_circular_references: true in config.

3. Doctrine Proxy Issues

  • Issue: Lazy-loaded translations may fail if the proxy is not initialized.
  • Fix: Use fetch: EAGER for translation associations or initialize proxies manually:
    $product->getTranslation($locale)->initialize();
    

4. Default Locale Fallback

  • Issue: Missing translations for a locale may break rendering.
  • Fix: Configure a fallback locale in a2lix_translation_form.yaml:
    a2lix_translation_form:
        fallback_locale: en
    

5. Form Theme Overrides

  • Issue: Custom form themes may not render translation fields correctly.
  • Fix: Extend the default theme block:
    {# templates/translation_form.html.twig #}
    {% block a2lix_translation_form_row %}
        {{ form_row(form) }}
        {% if form.vars.data.translation_locale %}
            <small>Locale: {{ form.vars.data.translation_locale }}</small>
        {% endif %}
    {% endblock %}
    

Debugging Tips

1. Enable Debug Mode

  • Enable debug: true in config to log translation operations:
    a2lix_translation_form:
        debug: true
    

2. Check Database Schema

  • Verify translation tables exist and are properly linked:
    php bin/console doctrine:schema:validate
    

3. Dump Form Data

  • Debug form submission data:
    $data = $form->getData();
    dump($data);
    

4. Validate Entities

  • Use Symfony’s validator to catch issues early:
    $errors = $validator->validate($product);
    if (count($errors) > 0) {
        dump($errors);
    }
    

Extension Points

1. Custom Translation Classes

  • Override the default Translation class:
    a2lix_translation_form:
        translation_classes:
            App\Entity\Product: App\Entity\CustomProductTranslation
    

2. Event Subscribers

  • Extend translation behavior via events:
    use A2lix\TranslationFormBundle\Event\TranslationEvents;
    use A2lix\TranslationFormBundle\Event\TranslationEvent;
    
    class CustomTranslationSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                TranslationEvents::POST_TRANSLATION_UPDATE => 'onTranslationUpdate',
            ];
        }
    
        public function onTranslationUpdate(TranslationEvent $event)
        {
            // Custom logic here
        }
    }
    

3. Custom Field Types

  • Create a custom field type for translations:
    use A2lix\TranslationFormBundle\Form\Type\TranslationType;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    
    class CustomTranslationType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('custom_field', TranslationType::class, [
                'translatable_fields' => ['title', 'content'],
            ]);
        }
    }
    

4. Serializer Normalizers

  • Extend the default normalizer for custom serialization:
    use A2lix\TranslationFormBundle\Serializer\TranslationNormalizer;
    use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
    
    class CustomTranslationNormalizer extends TranslationNormalizer implements ContextAwareNormalizerInterface
    {
        public function normalize($object, string $format = null, array $context = [])
        {
            // Custom logic
            return parent::normalize($object, $format, $context);
        }
    }
    

5. Twig Extensions

  • Add custom filters/functions for translations:
    use Twig\TwigFunction;
    use Twig\Extension\AbstractExtension;
    
    class TranslationTwigExtension extends AbstractExtension
    {
        public function getFunctions()
    
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