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

symfony/form

Symfony Form Component helps you build, validate, and process reusable HTML forms with rich field types, data mapping, and CSRF protection. Integrates cleanly with HttpFoundation, Validator, and Twig, but can be used standalone in any PHP app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation:

    composer require symfony/form
    

    Laravel developers typically use this via the Symfony Form Component (often bundled with Laravel's HTTP foundation).

  2. First Use Case: Create a simple form in a controller:

    use Symfony\Component\Form\Extension\Core\Type\TextType;
    use Symfony\Component\Form\Extension\Core\Type\SubmitType;
    use Symfony\Component\Form\FormBuilderInterface;
    
    public function createForm(FormBuilderInterface $builder)
    {
        return $builder
            ->add('name', TextType::class)
            ->add('save', SubmitType::class)
            ->getForm();
    }
    
  3. Rendering the Form: Use Laravel's Blade templating with Symfony's form rendering:

    // In your controller
    $form = $this->createForm($builder);
    return view('form.example', ['form' => $form->createView()]);
    
    <!-- In Blade (form.example.blade.php) -->
    {{ $form->start() }}
        {{ $form->widget }}
    {{ $form->end() }}
    
  4. Handling Submission:

    public function handleSubmit(Request $request)
    {
        $form = $this->createForm($builder);
        $form->handleRequest($request);
    
        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getData();
            // Process data...
        }
    }
    

Implementation Patterns

1. Form Type Customization

Extend built-in types or create custom ones:

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class CustomType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('custom_field', TextType::class);
    }
}

2. Data Transformers

Convert between form data and domain objects:

use Symfony\Component\Form\DataTransformerInterface;

class UserToStringTransformer implements DataTransformerInterface
{
    public function transform($user)
    {
        return $user ? $user->getFullName() : '';
    }

    public function reverseTransform($name)
    {
        // Logic to find user by name
    }
}

3. Validation Integration

Combine with Laravel's validation or Symfony's Validator:

use Symfony\Component\Validator\Constraints as Assert;

$builder->add('email', EmailType::class, [
    'constraints' => [new Assert\NotBlank(), new Assert\Email()]
]);

4. Collections and Dynamic Forms

Handle dynamic fields (e.g., nested forms):

$builder->add('tags', CollectionType::class, [
    'entry_type' => TextType::class,
    'allow_add' => true,
    'allow_delete' => true,
    'by_reference' => false,
]);

5. Form Events

Use events for custom logic:

$form->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
    $data = $event->getData();
    // Pre-process data
});

6. Laravel-Specific Integration

Use Laravel's FormRequest with Symfony forms:

use Illuminate\Http\Request;
use Symfony\Component\Form\FormFactoryInterface;

public function __construct(FormFactoryInterface $formFactory)
{
    $this->formFactory = $formFactory;
}

public function store(Request $request)
{
    $form = $this->formFactory->createBuilder()
        ->add('title', TextType::class)
        ->getForm();

    $form->handleRequest($request);
    // ...
}

Gotchas and Tips

Common Pitfalls

  1. CSRF Protection: Ensure CSRF tokens are included in forms (Laravel handles this via @csrf in Blade or Symfony\Bridge\Twig\Extension\FormExtension).

  2. Data Binding:

    • Use by_reference: false for collections to avoid shared references.
    • Partial submissions (e.g., nested forms) may require handle_missing_data: true (v8.1+).
  3. Validation Errors:

    • Errors are stored in $form->getErrors() or $form->get('field')->getErrors().
    • Clear errors with $form->reset().
  4. Session Contamination: Avoid non-serializable objects in form data (use PRE_SET_DATA listeners to sanitize).

  5. Collection Indices: Mismatched indices in collections (e.g., tags[0][name] vs tags[1][name]) can cause data loss. Use allow_add: true and prototype: true for dynamic forms.

Debugging Tips

  • Dump Form Data:
    dd($form->getData(), $form->getErrors(true));
    
  • Check Submitted Data:
    $form->submit($request->request->all());
    
  • Enable Debug Mode: Symfony's form component logs errors in debug: true mode.

Performance Quirks

  • Caching: Form types are cached by default. Clear cache if modifying types dynamically.
  • View Transformers: Custom transformers may slow down rendering. Use sparingly.

Extension Points

  1. Custom Form Types: Extend AbstractType or use FormTypeExtensionInterface for built-in types.
  2. Data Transformers: Implement DataTransformerInterface for complex mappings.
  3. Event Listeners: Hook into FormEvents (e.g., PRE_SUBMIT, POST_SUBMIT) for custom logic.
  4. Validation: Use Symfony's Constraint classes or Laravel's validation rules via constraints option.

Laravel-Specific Workarounds

  • Form Request Binding: Use Symfony\Component\Form\FormInterface in Laravel's FormRequest for seamless integration.
  • Blade Integration: Register the Symfony Form extension in config/app.php:
    'view' => [
        'composer' => [
            'form' => \Symfony\Bridge\Twig\Extension\FormExtension::class,
        ],
    ],
    
  • Session Handling: Laravel's session driver must support Symfony's session format (JSON by default).
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle