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

Form Translation Bundle Laravel Package

elao/form-translation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require elao/form-translation-bundle
    

    Register it in config/bundles.php:

    return [
        // ...
        Elao\FormTranslationBundle\ElaoFormTranslationBundle::class => ['all' => true],
    ];
    
  2. Enable in Forms Extend your form type with Elao\FormTranslationBundle\Form\TranslationAwareInterface and implement getTranslationKey():

    use Elao\FormTranslationBundle\Form\TranslationAwareInterface;
    
    class RegisterType extends AbstractType implements TranslationAwareInterface
    {
        public function getTranslationKey(): string
        {
            return 'form.register';
        }
    }
    
  3. First Use Case Use TranslationAwareTrait in child fields to auto-generate nested keys:

    use Elao\FormTranslationBundle\Form\TranslationAwareTrait;
    
    class EmailFieldType extends AbstractType implements TranslationAwareInterface
    {
        use TranslationAwareTrait;
    
        public function getTranslationKey(): string
        {
            return 'emails'; // Nested under parent's key (e.g., form.register.children.emails)
        }
    }
    

Implementation Patterns

Core Workflow

  1. Form Hierarchy

    • Parent forms define root keys (e.g., form.register).
    • Child fields append to the parent’s key (e.g., form.register.children.name).
    • Collections auto-generate label_add, label_delete, and prototype keys.
  2. Dynamic Key Generation

    • Use TranslationAwareTrait for child fields to inherit parent keys:
      class AddressType extends AbstractType implements TranslationAwareInterface
      {
          use TranslationAwareTrait;
      
          public function getTranslationKey(): string
          {
              return 'address'; // Auto-prepended to parent (e.g., form.register.children.address)
          }
      }
      
  3. Integration with Symfony Forms

    • Override buildForm() to inject translation keys:
      $builder->add('name', TextType::class, [
          'label' => $this->translator->trans('form.register.children.name.label'),
      ]);
      
    • Use TranslationAwareInterface for form types that need dynamic keys.
  4. Collection Handling

    • For CollectionType, the bundle auto-generates:
      • label_add (e.g., form.register.children.emails.label_add).
      • label_delete (e.g., form.register.children.emails.label_delete).
      • prototype keys for nested fields.
  5. Translation Files

    • Structure translations in translations/messages.{locale}.yml:
      form:
          register:
              children:
                  name:
                      label: "Full Name"
                  emails:
                      label: "Email Addresses"
                      label_add: "Add Email"
                      label_delete: "Remove Email"
                      children:
                          prototype:
                              label: "Email"
      

Advanced Patterns

  • Dynamic Keys with Data Use getTranslationKey() to generate keys based on runtime data:

    public function getTranslationKey(): string
    {
        return sprintf('form.user.%s', $this->userId);
    }
    
  • Custom Key Prefixes Override getTranslationPrefix() in child types:

    public function getTranslationPrefix(): string
    {
        return 'custom_prefix.';
    }
    
  • Event Listeners Subscribe to ElaoFormTranslationBundle.EventListener.FormTranslationEvent to modify keys dynamically:

    $eventDispatcher->addListener(
        ElaoFormTranslationBundle::EVENT_TRANSLATION_KEY,
        function (FormTranslationEvent $event) {
            $event->setKey(strtoupper($event->getKey()));
        }
    );
    

Gotchas and Tips

Common Pitfalls

  1. Key Collisions

    • Ensure unique keys for nested forms/fields. Use getTranslationPrefix() to avoid overlaps.
    • Example: Avoid form.user.name and form.user.profile.name in the same form.
  2. Translation Update

    • Keys are runtime-generated; translation:update won’t dump them. Manually add expected keys to .yml files.
  3. Collection Prototype Issues

    • If prototype keys don’t render, verify:
      • The collection field uses entry_type with TranslationAwareInterface.
      • The prototype key is correctly nested (e.g., form.register.children.emails.children.prototype.label).
  4. Caching Translations

    • Clear cache after adding new translation keys:
      php bin/console cache:clear
      
  5. Symfony 5.4+ Deprecations

    • If using Symfony 5.4+, ensure TranslationAwareInterface methods are public and non-abstract.

Debugging Tips

  • Log Generated Keys Add a listener to log keys during form rendering:

    $eventDispatcher->addListener(
        ElaoFormTranslationBundle::EVENT_TRANSLATION_KEY,
        function (FormTranslationEvent $event) {
            error_log('Generated key: ' . $event->getKey());
        }
    );
    
  • Check Parent Keys If a child key is malformed, verify its parent’s getTranslationKey() implementation.

  • Override Default Behavior Extend Elao\FormTranslationBundle\KeyGenerator\KeyGenerator to customize key logic:

    class CustomKeyGenerator extends KeyGenerator
    {
        public function generateKey(TranslationAwareInterface $form, string $suffix = ''): string
        {
            return parent::generateKey($form, '.custom_suffix');
        }
    }
    

    Register it in services.yaml:

    services:
        Elao\FormTranslationBundle\KeyGenerator\KeyGenerator:
            class: App\CustomKeyGenerator
    

Performance

  • Avoid Runtime Key Lookups in Loops Cache generated keys if used repeatedly (e.g., in form iterators):
    private $cachedKeys = [];
    
    public function getTranslationKey(): string
    {
        if (!isset($this->cachedKeys[$this->userId])) {
            $this->cachedKeys[$this->userId] = sprintf('form.user.%s', $this->userId);
        }
        return $this->cachedKeys[$this->userId];
    }
    

Extension Points

  1. Custom Key Generators Implement Elao\FormTranslationBundle\KeyGenerator\KeyGeneratorInterface for bespoke logic.

  2. Event Subscribers Extend ElaoFormTranslationBundle.EventListener.FormTranslationEvent to modify keys or validate them.

  3. Twig Integration Use the bundle’s keys in Twig templates:

    {{ 'form.register.children.name.label'|trans }}
    

    Or with dynamic keys:

    {% set key = form._translationKey %}
    {{ (key ~ '.label')|trans }}
    
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