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

Symfony Form Generator Bundle Laravel Package

ecohead/symfony-form-generator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ecohead/symfony-form-generator-bundle
    

    For non-Flex projects, also enable the bundle in config/bundles.php.

  2. First Use Case: Replace a traditional Symfony form builder array with a fluent API. Example:

    use Ecohead\FormGeneratorBundle\Form\Generator;
    
    $form = $this->createFormBuilder()
        ->add('name', Generator::text('Name')->required())
        ->add('email', Generator::email('Email')->required()->unique())
        ->getForm();
    
  3. Key Files to Review:

    • src/Form/Generator.php (core fluent methods)
    • src/DependencyInjection/ (configurable options)
    • tests/ (real-world usage examples)

Implementation Patterns

Core Workflows

  1. Fluent Form Building: Chain methods for field configuration (e.g., Generator::text()->required()->unique()).

    $builder->add('username', Generator::text('Username')
        ->label('Your Username')
        ->attr(['placeholder' => 'Enter username'])
        ->constraints([new NotBlank(), new Length(['max' => 50])])
    );
    
  2. Dynamic Field Generation: Use Generator::choice() with dynamic options:

    $roles = ['admin', 'editor', 'user'];
    $builder->add('role', Generator::choice('Role', $roles)
        ->multiple()
        ->expanded()
    );
    
  3. Reusable Field Types: Create a custom generator class (e.g., CustomGenerator) extending Generator for project-specific defaults:

    class CustomGenerator extends Generator {
        public static function password(string $name): self {
            return self::text($name)
                ->attr(['autocomplete' => 'new-password'])
                ->constraints([new NotBlank(), new Length(['min' => 8])]);
        }
    }
    
  4. Form Events Integration: Attach event listeners after fluent generation:

    $form = $builder->getForm();
    $form->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        $data = $event->getData();
        // Modify form based on data
    });
    
  5. Symfony UX Integration: Combine with Symfony UX for enhanced interactivity:

    $builder->add('search', Generator::text('Search')
        ->attr(['symfony_ux_autocomplete' => true])
    );
    

Integration Tips

  • Twig Integration: Use form_row() with custom classes from fluent attributes:
    {{ form_row(form.username, {'attr': {'class': 'form-control'}}) }}
    
  • Validation Groups: Pass groups via fluent methods:
    Generator::text('Field')->validationGroup('registration');
    
  • CSRF Protection: Ensure csrf_token() is added to the form after fluent generation.

Gotchas and Tips

Pitfalls

  1. Method Chaining Order:

    • Constraints must follow field type declaration (e.g., Generator::text()->constraints()).
    • Attributes (attr()) override defaults but can be reset with attr(['key' => null]).
  2. Symfony Version Mismatch: The bundle targets Symfony 5.4+. Test with symfony/form ^5.4 in composer.json.

  3. Dynamic Options Caching: For Generator::choice() with database-driven options, cache the query result to avoid N+1 issues:

    $options = $this->entityManager->getRepository(Role::class)->findAll();
    $builder->add('role', Generator::choice('Role', $options)->byReference());
    
  4. Form Theming Conflicts: Fluent attributes may clash with Twig themes. Use attr(['class' => 'custom-class']) explicitly.

Debugging

  • Constraint Validation: If validation fails silently, enable debug mode and check:
    $form->getErrors(true); // Returns all errors (including nested)
    
  • Field Type Mismatches: Use Generator::text() instead of Generator::string() (Symfony 5.4+ uses text for strings).

Extension Points

  1. Custom Generators: Extend Ecohead\FormGeneratorBundle\Form\Generator to add project-specific methods:

    class AppGenerator extends Generator {
        public static function phone(string $name): self {
            return self::text($name)
                ->attr(['type' => 'tel'])
                ->constraints([new Assert\Regex('/^\+?[\d\s\-\(\)]{10,}$/')]);
        }
    }
    
  2. Override Defaults: Configure global defaults in config/packages/ecohead_form_generator.yaml:

    ecohead_form_generator:
        defaults:
            text:
                attr:
                    class: "form-control"
    
  3. Event Listeners: Subscribe to FormGeneratorEvents (if available) to intercept fluent generation:

    // config/services.yaml
    services:
        App\EventListener\FormGeneratorListener:
            tags:
                - { name: kernel.event_listener, event: ecohead.form_generator.build, method: onBuild }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware