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 Extensions Laravel Package

sonata-project/form-extensions

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require sonata-project/form-extensions
    

    Register the bundle in config/app.php (Symfony/Laravel bridge required):

    'providers' => [
        // ...
        SonataProject\Form\Extensions\Provider\SonataFormExtensionsServiceProvider::class,
    ],
    
  2. Basic Usage Extend a Symfony form type (e.g., EntityType) with Sonata’s extensions:

    use Sonata\Form\Extensions\Type\CollectionType;
    use Sonata\Form\Extensions\Type\ChoiceType;
    
    $builder
        ->add('tags', CollectionType::class, [
            'entry_type' => ChoiceType::class,
            'entry_options' => ['choices' => $tagChoices],
        ]);
    
  3. First Use Case Replace nested forms or complex collections with Sonata’s CollectionType for drag-and-drop or inline editing:

    $builder->add('items', CollectionType::class, [
        'prototype' => true, // Enables inline editing
        'allow_add' => true,
        'allow_delete' => true,
    ]);
    

Implementation Patterns

Common Workflows

  1. Dynamic Collections Use CollectionType for forms with variable-length arrays (e.g., user roles, product options):

    $builder->add('roles', CollectionType::class, [
        'entry_type' => EntityType::class,
        'entry_options' => ['class' => UserRole::class],
        'by_reference' => false,
    ]);
    
  2. Conditional Fields Leverage ConditionalFieldExtension to show/hide fields based on parent values:

    $builder->add('shipping', TextType::class, [
        'conditionally_enabled' => ['field' => 'needs_shipping'],
    ]);
    
  3. Grouped Fields Organize fields into collapsible sections with GroupType:

    $builder->add('billing', GroupType::class, [
        'fields' => ['address', 'city', 'zip'],
        'label' => 'Billing Information',
    ]);
    

Integration Tips

  • Laravel-Symfony Bridge: Use Symfony\Component\Form\FormFactory via Laravel’s service container:
    $formFactory = app(Symfony\Component\Form\FormFactory::class);
    $form = $formFactory->createBuilder()->getForm();
    
  • Twig Integration: Extend Twig templates with Sonata’s form themes (e.g., sonata_form_field.html.twig):
    {% extends 'SonataForm::standard_layout.html.twig' %}
    
  • Validation: Combine with Symfony’s validators (e.g., Callback, Expression) for custom logic:
    $builder->add('age', IntegerType::class, [
        'constraints' => [new Callback([$validator, 'validateAge'])],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Prototype Cloning

    • Issue: prototype: true may duplicate hidden fields in the DOM.
    • Fix: Use prototype_name to scope cloned fields:
      'prototype_name' => '__name__', // Unique identifier
      
  2. By-Reference Pitfalls

    • Issue: by_reference: true can cause detached entities in collections.
    • Fix: Set by_reference: false for detached entities or use ORM\Mapping\ClassMetadata.
  3. CSRF in AJAX

    • Issue: Dynamic forms may break CSRF protection.
    • Fix: Include _token in AJAX requests or use Symfony\Bridge\Twig\Extension\FormExtension:
      {{ form_start(form, {'attr': {'id': 'dynamic-form'}}) }}
      

Debugging

  • Form Dumping: Use Symfony’s dump() to inspect form data:
    dd($form->getData());
    
  • Event Listeners: Debug form events with PRE_SET_DATA/POST_SUBMIT:
    $builder->addEventListener(FormEvents::PRE_SET_DATA, function ($event) {
        dump($event->getData());
    });
    

Extension Points

  1. Custom Types Extend AbstractType to create reusable form types:

    class CustomCollectionType extends AbstractType {
        public function buildForm(FormBuilderInterface $builder, array $options) {
            $builder->add('items', CollectionType::class, [
                'entry_type' => $options['entry_type'],
            ]);
        }
    }
    
  2. Override Templates Override Sonata’s Twig templates in resources/views/vendor/sonata_form/:

    {# resources/views/vendor/sonata_form/field/collection.html.twig #}
    
  3. Configuration Quirks

    • Default Options: Sonata’s types (e.g., CollectionType) have strict defaults. Override them explicitly:
      'allow_add' => true, // Defaults to false
      'allow_delete' => true,
      
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