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

bic/form-validation

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require bic/form-validation
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Bic\FormValidationBundle\BicFormValidationBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Basic Form Validation Extraction Inject the service into a controller or command:

    use Bic\FormValidationBundle\Service\FormValidation;
    
    public function __construct(private FormValidation $formValidation) {}
    
    public function index(Request $request)
    {
        $form = $this->createFormBuilder()->getForm()->handleRequest($request);
        $validation = $this->formValidation->extract($form);
        return $this->json($validation->toArray());
    }
    
  3. Key Files to Review

    • src/Service/FormValidation.php (core logic)
    • src/Model/FormValidation.php (data structure)
    • src/Validator/Constraints/ (custom constraints)

Implementation Patterns

Core Workflow

  1. Form Creation Use Symfony’s FormBuilder as usual, but ensure fields are properly typed (e.g., custom DocumentType).

    $form = $this->createFormBuilder($data)
        ->add('document', DocumentType::class)
        ->getForm();
    
  2. Validation Extraction Pass the handled form to the service:

    $validation = $this->formValidation->extract($form);
    
    • Returns a FormValidation object with:
      • Field names, types, constraints, and labels.
      • Nested support for compound forms (e.g., Register + Document).
  3. JavaScript Integration Convert the validation to JS-friendly format:

    $jsValidation = $this->formValidation->toJs($validation);
    // Outputs: { "phone": { "required": true }, "document": { "type": "DocumentType" } }
    
  4. API/CLI Validation Reuse the same logic for API responses or CLI tools:

    $apiSchema = $this->formValidation->toOpenApi($validation);
    

Integration Tips

  • Symfony Forms: Works seamlessly with Symfony’s FormBuilder and FormType classes.
  • Custom Types: Extend AbstractType and annotate constraints (e.g., @Assert\NotBlank()).
  • Dynamic Forms: Use FormBuilder methods like add() dynamically based on user roles/data.
  • Twig Integration: Pass $validation->toArray() to templates for client-side validation hints.

Gotchas and Tips

Pitfalls

  1. Constraint Mismatch

    • Issue: Custom constraints (e.g., @Assert\Custom) may not serialize correctly.
    • Fix: Ensure constraints implement ConstraintInterface and are registered in the validator service.
  2. Nested Forms

    • Issue: Deeply nested forms (e.g., User[Address[City]]) may not serialize as expected.
    • Fix: Use FormBuilder::createNamedBuilder() for explicit nesting control.
  3. Circular References

    • Issue: Forms with circular references (e.g., User ↔ Profile) can cause infinite loops in toArray().
    • Fix: Use JsonSerializable or SerializerComponent for safe conversion.
  4. Type Hints

    • Issue: PHP 8.0+ strict types may fail if the bundle lacks return type hints.
    • Fix: Patch the service or use /** @var */ casts.

Debugging

  • Validation Dump:
    dump($this->formValidation->extract($form)->toArray());
    
  • JS Output:
    $this->formValidation->toJs($validation, true); // Pretty-print
    
  • Constraint Debugging: Enable Symfony’s validator debug mode:
    # config/packages/validator.yaml
    services:
        _defaults:
            autowire: true
            autoconfigure: true
        Symfony\Component\Validator\Validator\ValidatorInterface: '@validator'
    

Extension Points

  1. Custom Serializers Implement Bic\FormValidationBundle\Serializer\FormValidationSerializerInterface to add new output formats (e.g., YAML, GraphQL).

  2. Constraint Adapters Extend Bic\FormValidationBundle\Validator\ConstraintAdapter to support non-Symfony constraints (e.g., Laravel’s Rule objects).

  3. Event Listeners Subscribe to form_validation.extract events to modify validation data pre-serialization:

    $eventDispatcher->addListener(
        'form_validation.extract',
        fn($event) => $event->setData(array_merge($event->getData(), ['custom' => true]))
    );
    
  4. Configuration Override default behavior via config/packages/bic_form_validation.yaml:

    bic_form_validation:
        include_constraints: ['NotBlank', 'Length'] # Whitelist constraints
        js_format: 'angular' # 'angular', 'jquery', or 'custom'
    
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.
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels